Unit 7 cc
Unit 7 cc
Microservices:
Microservices are an architectural approach to developing software applications as a collection of
small, independent services that communicate with each other over a network. Instead of building
a monolithic application where all the functionality is tightly integrated into a single codebase,
microservices break down the application into smaller, loosely coupled services.
Microservice is a small, loosely coupled service that is designed to perform a specific business
function and each microservice can be developed, deployed, and scaled independently.
This architecture allow you to take a large monolith application and decompose it into small
manageable components/services. Also, it is considered as the building block of modern
applications.
Microservices can be written in a variety of programming languages, and frameworks, and
each service acts as a mini-application on its own.
How do Microservices work?
Microservices break complex applications into smaller, independent services that work together,
enhancing scalability, and maintenance. Below is how microservixes work:
Applications are divided into self-contained services, each focused on a specific function,
simplifying development and maintenance.
Each microservice handles a particular business feature, like user authentication or product
management, allowing for specialized development.
Services interact via APIs, facilitating standardized information exchange and integration.
Different technologies can be used for each service, enabling teams to select the best tools
for their needs.
Microservices can be updated independently, reducing risks during changes and enhancing
system resilience.
The key concept of Microservices refers to a software architectural style where a system is
composed of small, independent services that communicate with each other. These services focus
on doing a specific task and are designed to be self-contained. Here are the key concepts:
API Gateway: Acts as a central entry point for external clients also they manage requests,
authentication and route the requests to the appropriate microservice.
Service Registry and Discovery: Keeps track of the locations and addresses of all
microservices, enabling them to locate and communicate with each other dynamically.
Load Balancer: Distributes incoming traffic across multiple service instances and prevent
any of the microservice from being overwhelmed.
Caching: Cache stores frequently accessed data close to the microservice which improved
performance by reducing the repetitive queries.
Fault Tolerance and Resilience Components: Components like circuit breakers and retry
mechanisms ensure that the system can handle failures gracefully, maintaining overall
functionality.
Below is a tabular comparison between microservices and monolithic architecture across various
aspects:
Aspect Microservices Architecture Monolithic Architecture
Advantages of Microservices
o Dynamic scaling.
o Faster release cycle.
Disadvantages of Microservices
Scalability: Design services to scale horizontally by adding more instances when needed.
Resiliency: Ensure services are fault-tolerant and can recover from failures.
Elasticity: Utilize the cloud's ability to scale up or down based on demand.
Distributed Systems: Microservices work well in a distributed system, where components
are decoupled and communicate through APIs or events.
Cloud platforms like AWS, Google Cloud Platform (GCP), and Microsoft Azure offer managed
services that can simplify microservices architecture. These services help in areas like storage,
messaging, containerization, and monitoring.
Start by breaking down your system into smaller, domain-driven microservices. This is typically
done by identifying bounded contexts where each service encapsulates a business function, such
as:
Order Service
Inventory Service
Payment Service
User Profile Service
Bounded Contexts ensure that each service focuses on a specific area of the business domain,
reducing dependencies between services.
Microservices are generally stateless to scale more effectively in the cloud. Each service should
not store any state locally but rely on external storage systems like databases, object stores, or
caches.
Containers are a natural fit for microservices, providing isolation and portability. In the cloud, you
can use containerization technologies and orchestration platforms to deploy and manage
microservices.
Docker: Package microservices into containers to ensure consistency across environments
(development, staging, production).
Kubernetes: Use Kubernetes for orchestrating containerized microservices, including
managing deployments, scaling, and networking. Cloud providers offer managed
Kubernetes services:
o AWS EKS (Elastic Kubernetes Service)
o Google Kubernetes Engine (GKE)
o Azure AKS (Azure Kubernetes Service)
Kubernetes automates service discovery, load balancing, scaling, and self-healing, making it a core
component of managing microservices in the cloud.
6. Service Communication
HTTP/REST: Services expose REST APIs over HTTP for synchronous communication.
gRPC: For low-latency, high-performance communication, use gRPC. It works well with
cloud-native environments, especially for inter-service communication.
Event-driven communication: Utilize cloud messaging services like AWS SNS/SQS,
Google Pub/Sub, or Azure Event Grid to implement event-driven architectures for
asynchronous communication between microservices.
Cloud environments provide tools to scale microservices based on demand, both automatically
(auto-scaling) and manually:
Auto-scaling: Cloud platforms automatically scale services based on traffic or load. For
example, AWS ECS or Kubernetes can scale containerized services up or down based on
defined metrics (e.g., CPU utilization, memory usage).
Load Balancing: Use cloud load balancers like AWS ELB (Elastic Load Balancer),
Google Cloud Load Balancer, or Azure Load Balancer to distribute traffic among multiple
instances of microservices, ensuring even load distribution.
Cloud environments facilitate continuous integration and continuous delivery (CI/CD), which is
essential for microservices. You can automate testing, building, and deploying microservices using
cloud-native CI/CD tools.
Implement version control, automated testing, and deployment pipelines to ensure microservices
can be quickly iterated and deployed in the cloud.
Identity and Access Management (IAM): Use IAM policies to control access to cloud
resources.
API Gateway Security: Use API Gateway to secure service-to-service communication
and implement throttling, rate limiting, and authorization.
OAuth 2.0 / JWT Tokens: Use token-based authentication (e.g., JWT) to manage access
to APIs.
Encryption: Ensure that all sensitive data is encrypted in transit (using TLS/SSL) and at
rest.
Monitoring and observability are critical in cloud-based microservices to ensure reliability and
performance:
Centralized Logging: Use cloud services like AWS CloudWatch, Google Stackdriver,
or Azure Monitor to collect logs from all microservices in one place.
Distributed Tracing: Use tools like AWS X-Ray, Google Cloud Trace, or Azure
Application Insights for tracing the flow of requests across multiple services to identify
performance bottlenecks.
Metrics & Alerts: Set up monitoring and alerting to track service health and performance
using cloud-native tools.
Use AWS Cost Explorer, Google Cloud Billing, or Azure Cost Management to track
and optimize cloud costs.
Design services to be lightweight and optimized to minimize unnecessary resource usage.
1. Synchronous Communication
Synchronous communication occurs when a service makes a request and waits for a response
before continuing its operation. This communication style is tightly coupled in terms of timing and
interaction between microservices.
Key Features:
The caller service waits for a response from the callee service.
Both services must be available at the time of communication.
The communication is typically request-response based (e.g., HTTP/REST, gRPC).
HTTP REST APIs: One of the most common communication methods in microservices.
A service sends an HTTP request to another service, and the second service responds with
the data or result.
o Use case: A "User Service" might use REST APIs to request user information from
an "Authentication Service."
gRPC: A high-performance, open-source RPC (Remote Procedure Call) framework that is
more efficient than REST for low-latency, high-throughput scenarios.
o Use case: Microservices that require fast, reliable communication between
services, such as an e-commerce platform’s payment service calling the fraud
detection service.
GraphQL: A query language for APIs that allows clients to request specific data. It’s more
flexible than REST, allowing the client to define the structure of the response.
Advantages of Synchronous Communication:
Disadvantages:
Blocking calls: The calling service is blocked until a response is received. This can lead to
performance bottlenecks if one service is slow or unavailable.
Tight coupling: Services are dependent on each other's availability, which can introduce
reliability concerns.
Scalability limitations: If too many requests are waiting for responses at once, the system
can become overwhelmed, especially under high traffic conditions.
2. Asynchronous Communication
Key Features:
The caller service does not wait for a response and continues its operation independently.
The communication is often event-driven (e.g., message queues, publish-subscribe
systems).
Services are loosely coupled, as they don't directly rely on one another’s availability.
Message Queues: Systems like AWS SQS, RabbitMQ, and Apache Kafka allow
services to send messages to a queue, where the receiving service consumes them
asynchronously. This is common in event-driven architectures.
o Use case: An "Order Service" places a message in an "Inventory Queue" to update
stock levels after a new order is placed.
Event-Driven Systems: Microservices publish events when they change state or perform
an action. Other services can subscribe to these events and take appropriate actions without
waiting for an immediate response.
o Use case: An "Order Service" emits an event (e.g., OrderPlaced), and other services
like "Shipping" or "Billing" listen for the event and take action when they receive
it.
Webhooks: One service notifies another via HTTP callbacks. Webhooks allow external
services to communicate asynchronously with the microservices.
o Use case: Payment providers like Stripe or PayPal notify the "Payment Service"
when a transaction status changes.
Advantages of Asynchronous Communication:
Non-blocking: Services don't have to wait for responses, allowing them to handle other
tasks and increase throughput.
Scalability: By decoupling services and using queues or event-based systems, you can
scale the services independently and handle higher traffic loads efficiently.
Fault tolerance: Since services aren’t directly waiting for a response, they can be more
resilient. If one service is temporarily unavailable, messages can be queued and processed
when the service comes back online.
Improved performance: In many scenarios, asynchronous communication can improve
performance by offloading work to be done later or in parallel.
Disadvantages:
Example:
Real-time interaction (synchronous) for critical actions that need immediate feedback
(e.g., payment processing).
Scalable, decoupled communication (asynchronous) for tasks that can be delayed,
reducing dependencies between services.
When deciding which communication style to use, consider the following factors:
Latency and Response Time: If low-latency and fast response times are critical (e.g., user
login), synchronous communication is preferable.
Service Availability: If one service is likely to be temporarily unavailable or can handle
tasks asynchronously, asynchronous communication helps avoid blocking the entire
system.
Scalability: Asynchronous messaging and event-driven systems are often more scalable,
as they allow for the decoupling of services and more efficient use of resources.
Business Logic: Some business processes require an immediate response, like payment
authorization, whereas others, like inventory updates, can be handled asynchronously.
Phases of microservices:
The phases of microservices in cloud computing represent the stages involved in designing,
developing, deploying, and maintaining a microservices-based application within a cloud
environment. Each phase addresses different aspects of the system and ensures that the
microservices architecture is scalable, resilient, and aligned with cloud-native principles. Here's a
detailed breakdown of these phases:
The first phase is centered around the design and architectural decisions for the microservices
application. The goal is to break down the application into smaller, independent services and
determine how these services will communicate with each other.
Key Activities:
Service Decomposition:
o Identify Bounded Contexts: Break the application down into smaller services that
represent distinct business domains or bounded contexts. Each service is
responsible for a specific set of functionalities.
o Define Microservice Boundaries: Identify clear service boundaries to avoid
overlap and minimize interdependencies.
o Database per Service: Ensure each microservice has its own database to maintain
loose coupling and autonomy.
Define Communication Patterns:
o Synchronous Communication: Choose protocols like HTTP/REST, gRPC for
real-time interactions between services.
o Asynchronous Communication: Use message queues, event streaming (e.g.,
Kafka), or Pub/Sub models for decoupled communication.
Design API Contracts: Define the structure and format of data exchanged between
services using APIs (e.g., RESTful APIs, gRPC).
Cloud-Native Principles: Ensure the design follows cloud-native principles such as
scalability, resilience, and elasticity.
Tools:
2. Development Phase
In this phase, you start developing the individual microservices. This phase focuses on writing the
code for each microservice, setting up the necessary infrastructure, and ensuring that services are
independently deployable.
Key Activities:
Tools:
Integrated Development Environments (IDEs): IntelliJ IDEA, Visual Studio Code, etc.
Version Control Systems: Git, GitHub, GitLab, Bitbucket.
Containerization: Docker, Podman.
Microservice Frameworks: Spring Boot, Micronaut, Quarkus, etc.
3. Testing Phase
Testing is critical to ensure that each microservice works correctly and integrates smoothly with
other services. In cloud-based systems, testing should be automated and include both unit and
integration tests.
Key Activities:
Unit Testing: Test the individual functionality of each microservice in isolation (unit tests).
Integration Testing: Ensure that the interactions between microservices are correct and
they can communicate as expected (e.g., API calls, data exchange).
Contract Testing: Validate the API contracts between services to ensure compatibility and
correctness.
End-to-End Testing: Perform full-system testing, simulating real-world use cases to
check if all services work together as intended.
Performance Testing: Evaluate the microservices under load and stress conditions to
identify potential bottlenecks.
Fault Tolerance Testing: Ensure that the system behaves gracefully under failure
scenarios (e.g., service failure, network issues).
Tools:
In this phase, the focus shifts to deploying the microservices into the cloud environment and
orchestrating their interactions. This phase ensures that microservices are scalable, available, and
resilient.
Key Activities:
Tools:
After deployment, monitoring and logging are essential to ensure that the microservices are
running efficiently, detect failures, and optimize system performance.
Key Activities:
Application Monitoring: Monitor the health and performance of each microservice using
tools that provide real-time insights (e.g., request rates, error rates, latency).
Log Aggregation: Collect logs from all microservices into a central location for easier
analysis and troubleshooting (e.g., using tools like ELK Stack or Prometheus/Grafana).
Distributed Tracing: Implement tracing to understand the flow of requests across
microservices and identify performance bottlenecks or failures (e.g., AWS X-Ray,
Jaeger).
Alerting: Set up automated alerts based on predefined conditions (e.g., high response
times, error rates) to notify teams of issues in real-time.
Tools:
Once the microservices are deployed and running, scaling and optimization become crucial to
handle increasing workloads efficiently and cost-effectively. This phase ensures that the
architecture remains adaptable to changing demands.
Key Activities:
Tools:
Auto-scaling: Kubernetes Horizontal Pod Autoscaler, AWS Auto Scaling, Google Cloud
Autoscaler.
Cloud Monitoring Tools: AWS CloudWatch, Azure Monitor, Google Cloud Operations
Suite.
Security and compliance are continuous concerns, but this phase focuses on implementing and
maintaining security measures throughout the system lifecycle.
Key Activities:
API Security: Ensure that APIs are secured using industry-standard protocols (e.g., OAuth
2.0, JWT) and prevent unauthorized access.
Identity and Access Management (IAM): Use cloud IAM services to control access to
resources and ensure that only authorized users and services can interact with each
microservice.
Data Encryption: Encrypt data at rest and in transit to protect sensitive information.
Compliance: Ensure that microservices comply with relevant regulations (e.g., GDPR,
HIPAA).
Tools:
IAM Tools: AWS IAM, Azure Active Directory, Google Identity Platform.
API Gateway: AWS API Gateway, Kong, Apigee for managing security policies and
traffic.
Encryption: AWS KMS, Azure Key Vault, Google Cloud KMS.
This phase focuses on maintaining the system after it's live, ensuring that microservices are
updated, bugs are fixed, and performance is continually improved.
Key Activities:
Patching and Updates: Keep the system up-to-date with security patches and feature
updates.
Bug Fixing and Issue Resolution: Address bugs and performance issues identified
through monitoring or user feedback.
Continuous Improvement: Continuously refine and enhance the system based on
feedback and new requirements.
Tools: