Microservice Patterns
CQRS
Separate the model that changes data from the model that reads it, so each can be designed and scaled for its job — and learn to live with read models that are slightly behind.
What you will learn
- Explain why one model rarely suits both writes and complex reads.
- Build a read model maintained by a projection from events.
- Measure and reason about staleness (projection lag).
- Handle read-your-own-writes and projection rebuilds.
Before you start
Overview
A library keeps the official register of books (accurate, normalised, updated carefully) and separately prints a catalogue sorted the way readers search. Librarians update the register; readers browse the catalogue, which is refreshed shortly after each change.
Command Query Responsibility Segregation splits a system into a command side that validates and applies changes, and a query side that serves reads from models shaped for each screen. A projection listens to the command side's events and keeps the read models up to date.
Why one model struggles
- Writes want a normalised model that protects invariants; reads want denormalised data shaped for a screen.
- Read traffic is usually 10–100× write traffic, but both compete for the same database.
- Every new screen adds joins and indexes that slow down writes.
Run it
Compare latency between A and B, then look at Stale reads (%). In C the projection is slow: reads stay fast, but many return yesterday's truth. Stop the projection with the fault button and watch staleness climb.
Living with staleness
- Read your own writes: after a command, return the new state from the command side, or let the UI show the change optimistically.
- Version checks: the command response carries a version; the UI waits (briefly) until the read model has reached it.
- Monitor projection lag in time, not just events, and alert when it exceeds what the product tolerates.
Implementation sketch
// Command side: validate, change the write model, publish an event (via outbox).
@Transactional
public void changeShippingAddress(ChangeAddress cmd) {
Order order = orders.findById(cmd.orderId()).orElseThrow();
order.changeAddress(cmd.address()); // invariants live here
outbox.save(OutboxEvent.of("Order", order.id(), "OrderAddressChanged", new OrderAddressChanged(order.id(), order.version(), cmd.address())));
}
// Projection: keep a denormalised row per order for the "My orders" screen.
@KafkaListener(topics = "order-events", groupId = "my-orders-projection")
@Transactional
void on(OrderAddressChanged e) {
jdbc.sql("UPDATE my_orders_view SET address = :a, version = :v WHERE order_id = :id AND version < :v")
.param("a", e.address().toString()).param("v", e.version()).param("id", e.orderId())
.update(); // version check: idempotent, ignores old events
}
// Query side: a single indexed read, no joins.
public List<MyOrderRow> myOrders(String customerId) {
return jdbc.sql("SELECT * FROM my_orders_view WHERE customer_id = :c ORDER BY placed_at DESC LIMIT 20")
.param("c", customerId).query(MyOrderRow.class).list();
}Advanced Projections must be rebuildable: keep the events (or a CDC stream) long enough to replay them into a fresh read model, build the new model next to the old one, and switch reads once it has caught up. This is also how you add a new read model for a new screen.
Trade-offs
| Benefits | Costs | |
|---|---|---|
| Performance | Reads are single indexed lookups; read and write sides scale separately. | Every change is written twice (write model + read models). |
| Consistency | The command side stays strongly consistent. | Read models are eventually consistent; UX must handle staleness. |
| Complexity | Each model is simple for its job. | Projections, rebuilds and monitoring are new moving parts — overkill for simple CRUD. |
Production considerations
- Apply CQRS to the parts of the domain that need it, not to the whole system.
- Make projections idempotent (version checks) — events will be redelivered.
- Track projection lag per read model and expose it on a dashboard.