Microservices Architecture
Microservices is an architectural style where applications are composed of small, independent services that communicate over well-defined APIs.
Monolith vs Microservices
| Aspect | Monolith | Microservices |
|---|---|---|
| Deployment | Single unit | Independent services |
| Scaling | Scale entire application | Scale individual services |
| Technology | Single stack | Polyglot |
| Complexity | Simpler initially | Distributed complexity |
| Team structure | Centralized | Team per service |
When to Use Microservices
Suitable scenarios:
- Large teams requiring independent deployments
- Different scaling requirements per component
- Need for technology flexibility
- Clear domain boundaries
Unsuitable scenarios:
- Small teams
- Simple applications
- Unclear domain boundaries
- Tight latency requirements
Key Patterns
Service Communication
Synchronous:
- REST APIs
- gRPC
Asynchronous:
- Message queues (Kafka, RabbitMQ)
- Event-driven architecture
Service Discovery
Services need mechanisms to find each other.
Client-side discovery:
- Client queries registry
- Client performs load balancing
Server-side discovery:
- Load balancer queries registry
- Simpler client implementation
API Gateway
Single entry point for clients.
Responsibilities:
- Request routing
- Authentication
- Rate limiting
- Response aggregation
Circuit Breaker
Prevents cascading failures.
The circuit breaker has three states: Closed, Open, and Half-Open. In the Closed state, requests flow normally. When failures exceed a threshold, the circuit trips to Open, blocking all requests. After a timeout period, the circuit moves to Half-Open, allowing a test request through. If the test succeeds, the circuit returns to Closed. If it fails, the circuit returns to Open.
Data Management
Database per Service
Each service owns its data.
Benefits:
- Loose coupling
- Independent scaling
- Technology freedom
Challenges:
- Distributed transactions
- Data consistency
- Cross-service queries
Saga Pattern
Manages distributed transactions with compensating actions.
Key Considerations
- Failure handling in microservices
- Service communication patterns
- Data consistency maintenance
- Appropriate use cases for microservices architecture