Microservices Latest
Microservices Latest
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
Ans:
In our Microservices architecture, we followed the Database per Service
approach to ensure independence and scalability. Here’s how we managed
it:
9. Did each service have its own database, or did you use a
shared database? Why?
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.
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:
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
AWS API
AWS cloud infrastructure Fully managed, scalable
Gateway
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.
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?
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?
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.