0% found this document useful (0 votes)
7 views21 pages

Microservices Latest

The document explains the concept of Microservices architecture, which involves building applications as a collection of small, independent services that communicate through APIs, contrasting it with Monolithic architecture where all components are tightly coupled. It details the advantages of Microservices, such as scalability, faster updates, and resilience, and describes the implementation of Microservices using Spring Boot, including practices for ensuring each service handles specific functionalities, communication strategies, database management, and error handling. Additionally, it highlights the use of patterns like Saga and Circuit Breaker to maintain data consistency and system resilience during failures.

Uploaded by

amit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views21 pages

Microservices Latest

The document explains the concept of Microservices architecture, which involves building applications as a collection of small, independent services that communicate through APIs, contrasting it with Monolithic architecture where all components are tightly coupled. It details the advantages of Microservices, such as scalability, faster updates, and resilience, and describes the implementation of Microservices using Spring Boot, including practices for ensuring each service handles specific functionalities, communication strategies, database management, and error handling. Additionally, it highlights the use of patterns like Saga and Circuit Breaker to maintain data consistency and system resilience during failures.

Uploaded by

amit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

1.

Can you explain what Microservices are and how they differ
from Monolithic architecture?
ANS - Microservices:
 Definition: Microservices is an architectural style where an
application is built as a collection of small, independent services,
each focused on a specific function (e.g., user service, payment
service).
 Key Feature: Each service runs independently, communicates
through APIs, and can be developed, deployed, and scaled
separately.
Monolithic Architecture:
 Definition: Monolithic architecture is a single, unified application
where all the components (e.g., UI, business logic, database) are
tightly coupled and run as a single unit.
 Key Feature: The entire application must be built, deployed, and
scaled as a whole.
Key Differences:
Aspect Microservices Monolithic

Scale individual services as Scale the entire


Scalability
needed. application.

Different teams can work Teams must coordinate


Development
independently. more.

Deploy the whole app


Deployment Deploy services separately.
together.

Failure Failure in one service Failure affects the


Impact affects only that part. entire app.

Can use different


Technology Single technology stack
technologies for each
Stack for the entire app.
service.
Example:
 Monolithic: A single application handles users, products, orders, and
payments.
 Microservices: Separate services manage users, products, orders,
and payments, all communicating via APIs.
2. Why did your project choose a Microservices architecture?
ANS --
Our project chose Microservices architecture because:
1. Scalability: We can scale services like payments or product catalog
independently.
2. Faster Updates: Each service can be developed, updated, and
deployed separately.
3. Resilience: If one service fails (e.g., payments), others (e.g.,
browsing) still work.
4. Flexibility: Each service can use the best technology for its function.
5. Quick Adaptation: Helps us manage external dependencies like
iSeries and CyberSource efficiently.
It ensures better performance, flexibility, and faster delivery for our e-
commerce platform.

2. Explain about microservices architecture?


ANS-
Microservices architecture is a way of building an application as a
collection of small, independent services. Each service does one
specific job, like handling users, processing payments, or managing
orders.
Key Points:
 Independence: Each service runs on its own and can be developed,
deployed, and updated separately.
 Communication: Services talk to each other through simple APIs.
 Scalability: You can scale only the services that need more power
without touching the rest.
 Flexibility: Developers can use different tools or programming
languages for different services.
 Reliability: If one service fails, the others can still work, making the
system more robust.
Overall, microservices make it easier to build, manage, and scale
complex applications by breaking them into manageable parts.

4. In the current project, how did you implement Microservices


using Spring Boot?
Ans:
In our current project, we implemented Microservices using Spring
Boot as follows:
1. Separate Services for Each Function
We built independent services for key functionalities like User
Management, Product Catalog, Orders, and Payments.
2. API Communication
 Each service communicates through REST APIs using Spring Boot's
@RestController for creating endpoints.
 For example, the Order service calls the Payment service API to
process payments.
3. Database Per Service
 Each microservice has its own database to maintain independence.
 Example: The User service uses a user database, while the Product
service uses a product database.
4. Service Discovery
 We used Spring Cloud Netflix Eureka for registering and
discovering services dynamically.
 Example: Services can find each other (e.g., Orders finding
Payments) through the Eureka Server.
5. Centralized Configuration
 Spring Cloud Config was used to manage service configurations
centrally, ensuring consistency and easier updates.
6. Fault Tolerance
 Spring Cloud Circuit Breaker (Resilience4j) was implemented
to handle failures gracefully.
 Example: If the Payment service is down, fallback logic prevents the
entire system from crashing.
7. Load Balancing
 Spring Cloud Load Balancer distributes traffic across multiple
instances of the same service, improving performance.
8. Secure Communication
 We secured APIs using Spring Security and managed
authentication through tokens like JWT.
This approach helped us create a scalable, reliable, and maintainable
microservices-based e-commerce application.

6. How did you ensure that each Microservice handled its


specific functionality?
ANS: To ensure each microservice handled its specific functionality, we
followed these practices:

1. Single Responsibility Principle


 Each microservice was designed to handle only one specific task
or business function.
o Example:
 User Service: Handles user registration, login, and
profile updates.
 Payment Service: Manages payment processing and
status updates.
2. Separate Codebases
 Each microservice had its own independent codebase and
repository, ensuring no overlap in responsibilities.
3. Independent Databases
 Each microservice had its own database to manage only its data,
avoiding tight coupling.
o Example: The Order service only accesses the order database,
not the user or payment database.
4. Well-Defined APIs
 Communication between microservices was through REST APIs,
with clear input/output for each service.
o Example:
 Order service sends a payment request to Payment
service via an API.
 Payment service responds with success or failure.
5. Validation and Logic Within Each Service
 All business rules and validations for a specific functionality were
handled inside the corresponding service.
o Example: Payment service validates transaction details; the
Order service focuses only on order processing.
6. Testing and Isolation
 Each microservice was tested individually using unit tests and
integration tests to ensure it handled its own functionality without
dependencies.
7. Monitoring and Logs
 We implemented centralized logging (e.g., using ELK Stack) to
monitor if any service attempted to perform tasks outside its scope.
This structure made each service independent, reliable, and focused
only on its role.

7. How did Microservices in your project communicate with


each other?

microservices needed to communicate to work together effectively. Here’s


how we made it happen:
1. REST APIs
 Each microservice exposed its functionality through REST APIs.
o Example: If the Order service needs to process a payment, it
sends an HTTP request to the Payment service's API and gets
a response (e.g., success or failure).
2. Service Discovery with Eureka
 We used Eureka, a Service Registry, to help microservices find each
other.
o Instead of hardcoding service URLs, microservices registered
themselves with Eureka.
o Example: The Order service asked Eureka, "Where is the
Payment service?" and got the correct address.
3. Messaging (Asynchronous Communication)
 For tasks that didn’t need an immediate response, we used
message queues like RabbitMQ or Kafka.
o Example: After placing an order, the Order service sends a
message to the Notification service to send an email, instead
of waiting for the email to be sent.
4. Load Balancer
 We used a load balancer to evenly distribute incoming requests to
multiple instances of the same service.
o Example: If there are 3 instances of the Payment service, the
load balancer ensures no instance is overwhelmed.
5. API Gateway
 All external requests (e.g., from a user’s browser) passed through an
API Gateway, which directed them to the correct microservice.
o Example: A request to check an order's status goes to the API
Gateway, which forwards it to the Order service.
This setup allowed the microservices to communicate efficiently,
handle large traffic, and work together seamlessly.

8. Can you provide a real-time example from your project


where inter-service communication was critical?
ANS:
Real-Time Example: Order Placement and Payment Processing
When a customer places an order in our e-commerce project:
1. Step 1: Order Service Calls Payment Service (Synchronous
Communication)
o The Order Service sends a request to the Payment Service
to process the payment.
o The Payment Service validates the payment details (e.g.,
card info) and confirms if the payment is successful or failed.
o The Order Service waits for this response because it needs
to know if the order can proceed.
2. Step 2: Notification Service is Triggered (Asynchronous
Communication)
o Once the payment is successful, the Order Service sends a
message to the Notification Service (via a message queue
like RabbitMQ).
o The Notification Service sends an order confirmation email
or SMS to the customer.

Why Was This Critical?


 Synchronous: Payment confirmation is essential before proceeding
with the order.
 Asynchronous: Notifications can happen in the background,
ensuring the customer doesn't wait unnecessarily.
This combination ensured a smooth user experience and efficient
communication between services.

9. How did you manage databases in your Microservices


architecture?

Ans:
In our Microservices architecture, we followed the Database per Service
approach to ensure independence and scalability. Here’s how we managed
it:

In our Microservices architecture, we used the Database per Service


approach:
1. Separate Databases: Each service had its own database to maintain
independence.
o Example: User Service managed user data, Order Service
managed order data, etc.
2. Data Sharing:
o APIs: Services called each other to fetch required data.
o Messaging: Used message queues (e.g., RabbitMQ) for
updates and notifications.
3. Consistency: Ensured data consistency with event-driven updates
and idempotent APIs.
4. Flexible Databases: Services used the best database type for their
needs (e.g., MySQL for structured data, MongoDB for flexible data).
This ensured scalability, fault isolation, and flexibility across the
system.

9. Did each service have its own database, or did you use a
shared database? Why?

Each service had its own database to ensure:

1. Independence: Services managed their data separately.


2. Scalability: Databases could scale individually based on needs.
3. Fault Isolation: Issues in one database didn’t affect others.
4. Flexibility: Services used the best database type for their data.
5. Clear Ownership: Each service fully controlled its data.
This ensured a robust and scalable system.

10. Explain how you handled database transactions that


spanned multiple Microservices.
ANS: We handled database transactions across multiple microservices
using the Saga Pattern to maintain consistency.
How It Worked:
1. Choreography (Event-Driven):
o Each service performed its part of the transaction and
published an event (e.g., "Order Created").
o Other services reacted to these events to complete their
tasks.
o Example:
 Order Service creates an order and publishes an
event.
 Payment Service listens to the event, processes
payment, and publishes a "Payment Success" event.
2. Compensation for Failures:
o If a service failed, compensating actions were triggered to
undo previous changes.
o Example: If payment failed, the Order Service would cancel
the order.
Why Saga?
 Ensured eventual consistency without locking databases.
 Allowed each service to remain independent.
This approach maintained data consistency across services in a
distributed environment.

11. One of your Microservices is calling another service,


but the downstream service is occasionally slow or failing.
ANS : To handle cases where a downstream service is occasionally slow or
failing, we used the following strategies:

1. Circuit Breaker (Resilience4j/Spring Cloud Circuit Breaker)


 How it works: If the downstream service is failing or too slow, the
circuit breaker opens, preventing further calls to the failing
service. This avoids overwhelming the service and gives it time to
recover.
 Example: If the Payment Service is down, the Order Service
stops making calls until the Payment Service recovers.
2. Timeouts and Retries
 Timeouts: We set reasonable timeouts for requests to avoid waiting
too long.
 Retries: We implemented retry logic to attempt a few retries
before failing the request.
 Example: If the Product Service is temporarily slow, the Order
Service retries the request a few times before giving up.
3. Fallback Mechanism
 If a downstream service fails, we provided a fallback response
(e.g., cached data, default value) to ensure the system continues to
function.
 Example: If the Inventory Service fails, the Order Service uses
cached product availability.
4. Asynchronous Communication
 For non-critical tasks, we used message queues (e.g., RabbitMQ)
so that the failure or delay of a downstream service doesn’t block
the entire system.
 Example: If the Shipping Service is slow, the Order Service
sends a message and moves on to other tasks.
These strategies helped improve resilience, fault tolerance, and
availability in our microservices system

11:How to implement a circuit breaker to handle this?


To implement a circuit breaker using Resilience4j:
1. Add Dependencies
2. Configure in application.yml
3. Use Circuit Breaker in Service(@CircuitBreaker(name =
"paymentService", fallbackMethod = "paymentFallback"))
4. Fallback Mechanism(If the service fails, the paymentFallback
method is called, preventing further failures.)
5. Handling Circuit Breaker States
 Closed State: Service is healthy, and calls are being
made.
 Open State: Service is unhealthy, and calls are blocked
until the circuit breaker resets.
 Half-Open State: Circuit breaker allows a limited number
of calls to test if the service has recovered.

Benefits of Using a Circuit Breaker:


 Prevents cascading failures: If one service fails, the
circuit breaker prevents continuous retries, allowing the
service to recover.
 Resilience: The system becomes more resilient to
intermittent issues.
 Graceful Fallbacks: Ensures the system remains
functional by providing fallback responses when
necessary.
 By implementing this pattern, the system can recover
gracefully from service failures and prevent downtime.

12. Provide a real-world example of when this pattern was useful
in your projects.

In our e-commerce project, the Payment Service occasionally faced


slowdowns due to high traffic, especially during flash sales. This impacted
the Order Service, causing delays and failures when trying to process
payments.

Real-World Example:
 Issue: During a flash sale, many customers placed orders
simultaneously, which caused the Payment Service to become
unresponsive.
 Solution: We implemented a Circuit Breaker for the Payment Service
using Resilience4j.
o Circuit Breaker: When the Payment Service exceeded the
failure threshold (e.g., 50% failures), the circuit breaker
opened, stopping further calls to the Payment Service.
o Fallback: The Order Service returned a fallback message like,
"Payment service is down, please try again later," instead of
continuously retrying and overloading the service.
Outcome:
 Prevention of System Overload: The circuit breaker prevented
excessive calls to the Payment Service, giving it time to recover.
 Improved User Experience: Customers were informed quickly and
did not experience prolonged delays.
 Resilience: The system remained stable, and after a set recovery
time, the circuit breaker allowed calls to resume.
This approach ensured a smooth customer experience even during high-
traffic situations, maintaining system stability.

13. Imagine your Microservices are exposed to external clients.


How did you handle routing, security, and aggregation?

To handle routing, security, and aggregation in our microservices exposed to


external clients, we implemented the following strategies:

1. Routing: API Gateway


 API Gateway (e.g., Spring Cloud Gateway) acted as the entry
point for all external requests.
 It routed requests to the appropriate microservices based on the
URL and request type.
o Example: A request to /orders/{id} would be forwarded to the
Order Service.
o Once the API Gateway discovers the Order Service via Eureka, it routes the
request to one of the available instances of the Order Service.
o

2. Security:
 Authentication & Authorization:
o We used OAuth2 and JWT tokens for securing APIs. External
clients had to authenticate using tokens.
o The API Gateway verified the JWT token before forwarding
the request to any microservice.
 HTTPS: All communications were encrypted using HTTPS to secure
data in transit.
3. Aggregation:
 API Gateway handled responses from multiple services,
aggregating them into a single response for the client.
o Example: For an order, the gateway might call Order
Service, Payment Service, and Inventory Service, then
aggregate the data into one response.
Eureka Server:

o The Eureka Server acts as a Service Registry. Each


microservice (like Order Service) registers itself with Eureka
when it starts, so the API Gateway can query Eureka to
discover the service instances.
o For example, if a request to /orders/{id} comes in, the API
Gateway will query Eureka to find the Order Service's
available instances.

 Service Mesh (e.g., Istio) could also be used for advanced routing
and aggregation in complex systems.
Outcome:
 Centralized Routing: API Gateway simplified client communication
by centralizing routing logic.
 Secure Communication: Ensured that only authenticated clients
could access services.
 Efficient Aggregation: Aggregated data from multiple services,
reducing client-side complexity.
requests don't go directly to the service; they first hit the API
Gateway, which uses Eureka to find the service and route the request
accordingly.
14. Did you use an API Gateway (e.g., Zuul, Kong, or Spring Cloud
Gateway)? If so, how did you implement it?

Yes, we used Spring Cloud Gateway as the API Gateway in our project. Here's
how we implemented it:

1. Dependencies
Add to pom.xml:
xml
Copy code
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

2. Configuration in application.yml
Add Filters (optional
3. Security Configuration
JWT Authentication:

4 Key Features
 Dynamic Routing: Routes requests via Eureka to microservices.
 Security: Handles JWT validation.
 Load Balancing: Distributes requests across service instances.
This approach simplified routing, ensured security, and integrated
smoothly with Eureka for service discovery.

Comparison Table
API Gateway Ideal For Key Features

Spring Cloud Seamless integration with


Spring Boot-based projects
Gateway Spring

Zuul Legacy Netflix OSS systems Basic routing and filtering

Plugin ecosystem, multi-


Kong Enterprise-grade setups
protocol

AWS API
AWS cloud infrastructure Fully managed, scalable
Gateway

Kubernetes/Docker-based Auto-discovery, simple


Traefik
microservices configuration

High-performance routing Reverse proxy, caching,


NGINX
needs TLS termination

Lightweight, modern API Dynamic routing,


Apache APISIX
management extensibility

15. How did you ensure secure communication between


Microservices? Did you use OAuth2, JWT, or any other method?

We ensured secure communication between microservices using OAuth2 and


JWT. Here’s how we did it:

1. Authentication and Authorization


 OAuth2: We used OAuth2 for authorization to ensure that only
authenticated users could access certain services.
 JWT (JSON Web Tokens): After user login, a JWT was generated and
passed in requests to authenticate and authorize microservices.
2. How It Worked:
 JWT Token: When a user logs in, an authentication server generates
a JWT token.
 API Gateway: The API Gateway (Spring Cloud Gateway) checked the
JWT in the request header to validate the user's identity before
routing the request to the relevant microservice.
 Service-to-Service Communication: For inter-service communication,
each service validated the JWT to ensure that only authorized
services could communicate with each other.
3. Benefits:
 Secure Access: Ensured only authorized users and services could
access resources.
 Centralized Security: All authentication logic was centralized at
the API Gateway level.
 Scalable: Each service didn’t need to store session information—
JWTs handled stateless authentication.
This approach ensured secure and authorized communication between
microservices.

16. Provide an example where implementing security across


Microservices was a challenge, and how you resolved it.

ANS
In one of our projects, we had multiple microservices that needed to securely
communicate with each other and with external clients. The challenge was
ensuring consistent security across all services, especially since each service
had its own security requirements, and managing them individually was
complex.

Solution:
1. JWT and OAuth2 for Authentication:
o We implemented JWT tokens for authentication. When a user
logged in, they received a JWT, which was passed along with
every request to verify the user’s identity.
o OAuth2 was used to handle authorization, ensuring users had
the right permissions.
2. Centralized Security with API Gateway:
o We centralized security at the API Gateway level (using
Spring Cloud Gateway). The Gateway handled token validation
(via JWT), ensuring that only authenticated requests were
forwarded to the microservices.
3. Service-to-Service Communication:
o For internal communication between microservices, we
required that each service validate the JWT token from
incoming requests. This ensured that microservices
communicated securely and only trusted services could
interact with each other.

Example : To ensure secure service-to-service communication:


o Passing JWT: Each microservice includes the JWT token in the
Authorization header when making internal API calls to
other services.
o JWT Validation: In each service, we used Spring Security
with the OAuth2ResourceServer to validate the JWT:
o Common Security Key: All services shared the same public
key to validate JWT tokens.
his ensured only trusted services could communicate with
each other securely.
Outcome:
 This approach allowed us to centralize security management,
making it easier to handle user and service authentication.
 It also ensured that sensitive data was protected and only
authorized users and services had access.
This solution resolved the complexity of securing each service individually
and ensured consistency across the entire system.

17. Suppose you have a payment Microservice and an order


Microservice. A user places an order, and the payment fails. How
can you ensure consistency between the services?

To ensure consistency between the Payment and Order microservices when a


payment fails, we can use a saga pattern or a compensating transaction. Here's
how:

1. Saga Pattern:
 Step 1: The user places an order in the Order service.
 Step 2: The Payment service attempts the payment.
 Step 3: If the payment fails, we trigger a compensating transaction
to roll back the order in the Order service.
2. Steps in Detail:
 Local Transactions: Each service (Order and Payment) handles its
own transaction (e.g., Order creation and Payment processing).
 Compensation: If the payment fails:
o The Payment Service notifies the Order Service.
o The Order Service cancels or rolls back the order, ensuring
data consistency.
3. Event-Driven Approach:
 We can use event-driven communication (e.g., Kafka or RabbitMQ)
to notify services about the status:
o If the payment fails, an "Order Cancelled" event is sent to the
Order Service to rollback the order.
Outcome:
This approach ensures that if one service fails (like Payment), the other
service (Order) is updated to maintain consistency between the two
services.

18. Did you use Sagas, 2-phase commit, or another pattern for
distributed transactions?
Ans : In our project, we used the Saga Pattern for managing distributed
transactions between microservices.
Why Saga Pattern?
 2-Phase Commit can be slow and block resources, making it less
suitable for microservices.
 Saga allows services to work independently, ensuring that if one
service fails, the other can "compensate" and keep the system
consistent.
How We Used the Saga Pattern:
1. Step 1 (Order Creation): When a user places an order, the Order
Service starts the transaction.
2. Step 2 (Payment): The Payment Service processes the payment.
o If the payment succeeds, the order is confirmed.
o If the payment fails, a compensating action is triggered in the
Order Service to cancel or rollback the order.
3. Event-Driven: We used events to communicate between services. If
payment failed, an "Order Cancelled" event would be sent to the
Order Service.
This approach ensured that both services remained consistent without
blocking resources, even in the case of failures.

19. What did you do when one Microservice had high latency,
which impacted the overall application performance?

To handle high latency in a microservice that impacted performance, we took


these steps:

1. Circuit Breaker:
 Implemented a circuit breaker (e.g., Hystrix or Resilience4j) to fail
fast and avoid blocking the system if the service was slow.
2. Timeout & Retry:
 Added timeouts to limit waiting time and retry logic with exponential
backoff for temporary issues.
3. Asynchronous Communication:
 Switched to asynchronous communication (e.g., using Kafka or
RabbitMQ) to avoid blocking the application while waiting for
responses.
4. Load Balancing & Scaling:
 Used load balancing and horizontal scaling to distribute traffic and
handle high loads efficiently.
5. Monitoring & Alerts:
 Set up monitoring and alerts to quickly detect and resolve
performance issues.
These steps ensured better system resilience and reduced the impact of
high-latency services.
20. In a Microservices architecture, multiple teams often work on
different services. How did you manage dependencies and
coordinate deployments?

To manage dependencies and coordinate deployments across teams in a


Microservices architecture:
1. Versioning & API Contracts:
 Used API versioning and contract-first development (e.g., Swagger)
to ensure compatibility between services.
2. CI/CD Pipelines:
 Implemented CI/CD for automated testing and deployment, with
separate pipelines for each service.
3. Service Discovery:
 Used Eureka for service discovery, allowing services to find and
communicate with each other.
4. Dependency Management:
 Maintained loose coupling between services and used shared
libraries for common functionality.
5. Deployments:
 Adopted Blue/Green or Canary deployments to minimize risks during
updates.
6. Communication:
 Coordinated across teams with Agile practices, regular meetings,
and clear documentation.
This approach ensured smooth collaboration, minimized downtime, and
reduced deployment risks.

Q What is saga design pattern ?

The Saga Design Pattern is a way to manage long-running transactions


across multiple microservices while ensuring data consistency.
How It Works:
1. Local Transactions: Each service does its part of the task (like
processing an order or payment).
2. Compensating Actions: If one service fails (like a payment failing),
the previous services can "undo" their actions (e.g., cancel the
order).
3. Communication: Services use events to notify each other about the
success or failure of their tasks.
Benefits:
 Handles Failures: If something goes wrong, it can "roll back" actions.
 Scalable: Works without locking resources, unlike 2-phase commit.
 Independent Services: Each service operates independently,
reducing tight dependencies.
In simple terms, it helps keep the system consistent when tasks span
multiple services, even if one service fails.
Example :
Saga Pattern in Action:
 Step 1: The Order Service starts by creating an order.
 Step 2: The Payment Service is called, and if the payment fails, it
sends an event to the Order Service to cancel the order
(compensating action).
 Step 3: If the payment is successful, the Shipping Service is
called to ship the product. If shipping fails, it sends a rollback
request to Payment Service to refund the customer.
This ensures that even if one part of the process fails (e.g., payment or
shipping), the system remains consistent, and previous actions can be
undone.

Q Synchronous Communication: ans ASynchronous


Communication: ?
Synchronous Communication:
In synchronous communication, the client sends a request to a service
and waits for a response before proceeding. Both services are tightly
coupled, and the client is blocked until the service returns a result.
 Examples:
o HTTP/REST APIs: A service makes an HTTP call to another
service and waits for the response.
o gRPC: A fast, binary protocol used for synchronous
communication between services.
 Pros:
o Simple to implement.
o Immediate feedback for the client.
 Cons:
o Blocking calls: The client must wait for the service's response,
potentially causing delays.
o Higher coupling between services.

Asynchronous Communication:
In asynchronous communication, the client sends a request to a
service and doesn't wait for a response. Instead, it continues with other
tasks, and the service processes the request independently, notifying the
client when done.
 Examples:
o Message Queues (RabbitMQ, Kafka): Services
communicate by sending messages to queues, which are
processed asynchronously.
o Event-Driven Architecture: Services emit events (e.g.,
"OrderPlaced"), and other services listen and react to those
events.
 Pros:
o Non-blocking: The client doesn’t wait for a response, allowing
for better performance and scalability.
o Decouples services, making them more independent.
 Cons:
o More complex to implement.
o Handling failures and message retries can be challenging.
In summary:
 Synchronous: Client waits for the service's response.
 Asynchronous: Client doesn't wait; services work independently
and may notify the client later.

Q Circuit Breaker pattern


The Circuit Breaker pattern prevents cascading failures in microservices. It
works as follows:

1. Closed State: Requests are allowed. If a service fails, the circuit


breaker counts the failures.
2. Open State: After too many failures, the circuit breaker opens,
rejecting requests to the failing service to prevent overload.
3. Half-Open State: After a cooldown, the circuit breaker tests the
service with limited requests. If successful, it closes; otherwise, it
opens again.
Benefits:
 Protects the system from cascading failures.
 Improves fault tolerance by limiting retries to a failing service.
Tools: Hystrix, Resilience4j, Spring Cloud Circuit Breaker.

You might also like