Intermediate → Advanced25 min read· Topic 8.5

Data patterns in microservices

Shared database anti-pattern, Saga, CQRS, event sourcing, API composition

🗄️Key Takeaways

  • 1
    Shared database is the #1 microservice anti-pattern — creates tight coupling and coordination problems
  • 2
    Saga pattern: chain of local transactions with compensating actions for rollback
  • 3
    API Composition: aggregate data from multiple services at the application layer
  • 4
    CQRS: separate optimized read models from write models — powerful for complex query requirements

Managing Data Across Service Boundaries

The hardest part of microservices isn't building services — it's managing data across them. Without shared databases, how do you query data spanning multiple services? How do you maintain consistency across service boundaries? These patterns answer those questions.

Data Patterns

A saga is a sequence of local transactions. Each service does its work and publishes an event. If any step fails, execute compensating transactions to undo previous steps.

Choreography: services react to events autonomously. Simple but hard to track end-to-end.

Orchestration: central coordinator directs the workflow. Easier to reason about but creates a SPOF.

Example: Order → Reserve Inventory → Charge Payment → (fail) → Refund → Release Inventory.

⚠️Shared Database Anti-Pattern
If multiple services read/write the same database tables, you have a distributed monolith — not microservices. Schema changes, performance, and deployment of one service are tightly coupled to all others. Each service MUST own its data.

Advantages

  • Saga pattern enables distributed transactions without 2PC
  • CQRS enables highly optimized read models
  • CDC provides real-time data sync without code changes

Disadvantages

  • Saga compensations are complex to implement correctly
  • CQRS adds significant architectural complexity
  • Eventual consistency requires careful UI/UX handling

🧪 Test Your Understanding

Knowledge Check1/1

In a Saga orchestration, what coordinates the workflow?