Microservices Patterns/Event Sourcing & CQRS

CQRS & Read Model Projections

Command/query separation, materialized views, eventual consistency on reads, and pairing CQRS with event sourcing vs without.

4/5Overview: 35m

CQRS — Command Query Responsibility Segregation

Separate write model (commands, business rules) from read model (queries, denormalized views).

Can use CQRS without event sourcing (dual DB schemas). Often paired together.

Write side

  • Accept commands: PlaceOrder, CancelOrder
  • Enforce invariants on write model / aggregate
  • Persist events or updated rows

Read side

  • Materialized views optimized for queries
  • Updated synchronously (same txn — rare) or async projection (common)
Command → Write DB → event → Projector → Read DB (Elasticsearch, Redis, SQL view)

Eventual consistency on reads

User places order → read model may lag 100ms–seconds.

UX mitigations:

  • Return write model ID; poll or push when ready
  • Read-your-writes — route to primary or version check

Staff interview: state acceptable lag per use case.

Projection design

Read modelOptimized for
Order by customercustomer_id index
Ops dashboardpre-aggregated counts
SearchElasticsearch full-text

Multiple projectors consume same event stream — each builds its view.

CQRS + microservices

Each service may have internal CQRS. Cross-service: don't query another service's DB — call API or subscribe to events.

Anti-pattern: shared read replica across service boundaries.

vs caching

Cache = optional optimization on read path. CQRS = first-class separate schema maintained by pipeline.

Saga connection

Long-running workflows emit events; projectors update status views. Saga orchestration in Distributed Systems → Transactions.

When interviewer asks "CQRS?"

Answer: "Separates write complexity from read scale. Pays off when read patterns vastly outnumber writes or need different storage (graph vs relational). Costs operational complexity — projections, lag, schema drift."

Further Reading

Hands-On Tasks (Optional)

Architecture drills and whiteboard exercises. Assumes Communication & Data Transfer and Distributed Systems fundamentals.

  • Design CQRS read models for orders

    Write model: Order aggregate. Read models: customer order history (list), ops dashboard (counts by status). How do projections update? Lag tolerance?

    15m