Skip to main content

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)]
DimensionMonolithic ArchitectureMicroservices Architecture
DeploymentSingle all-or-nothing artifactIndependent CI/CD per service
Data StorageShared single relational schemaDatabase-per-Service pattern
ScalingScale entire application horizontallyScale only resource-intensive bottlenecks
Failure Blast RadiusSingle memory leak crashes whole systemIsolated failures with circuit breakers
ComplexitySimple networking; code becomes complexHigh 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:​

  1. Tight Coupling: Schema changes made by the Order team break the Payment team's queries without warning.
  2. Bypasses Domain Invariants: Bypasses business rules and auditing enforced by the service owning the data.
  3. 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.