7.1 Microservices Architecture Principles
← Back to Chapter 7: Microservices & Spring Cloud
A Microservices Architecture structures an application as a collection of small, autonomous, loosely coupled services aligned around distinct business capabilities.
1. Monolith vs Microservices
MONOLITH:
┌────────────────────────────────────────────────────────┐
│ UI + OrderService + PaymentService + InventoryService │
│ └── Shared Single Monolithic Database │
└────────────────────────────────────────────────────────┘
MICROSERVICES:
┌─────────────────┐ ┌─────────────────┐ ┌──────────────── ─┐
│ Order Service │ │ Payment Service │ │Inventory Service│
└────────┬────────┘ └────────┬────────┘ └────────┬────────┘
│ │ │
▼ ▼ ▼
[(Order DB)] [(Payment DB)] [(Inventory DB)]
| Dimension | Monolithic Architecture | Microservices Architecture |
|---|---|---|
| Deployment | Single all-or-nothing artifact | Independent CI/CD per service |
| Data Storage | Shared single relational schema | Database-per-Service pattern |
| Scaling | Scale entire application horizontally | Scale only resource-intensive bottlenecks |
| Failure Blast Radius | Single memory leak crashes whole system | Isolated failures with circuit breakers |
| Complexity | Simple networking; code becomes complex | High operational & distributed complexity |
2. The Database-per-Service Pattern
In true microservices, services must never query each other's databases directly.
Why Direct DB Sharing Fails:
- Tight Coupling: Schema changes made by the Order team break the Payment team's queries without warning.
- Bypasses Domain Invariants: Bypasses business rules and auditing enforced by the service owning the data.
- Connection Saturation: Multiple services compete for database locks.
The Golden Rule: Services communicate strictly across public network APIs (REST, gRPC) or asynchronous event streams (Kafka).
3. Distributed Transactions & The Saga Pattern
Because each service owns its private database, distributed ACID transactions (2-Phase Commit / 2PC) do not scale in cloud environments. We implement the Saga Pattern: a sequence of local transactions where each step updates data within a single service and publishes an event triggering the next step.
- Choreography: Each service listens to events from collaborating services and decides when to act.
- Orchestration: A dedicated orchestrator service coordinates the transaction steps and issues compensating transactions (rollback actions) if any step fails.