Free — no signup required

CQRS: Splitting the Brain

2 min read

The Impedance Mismatch

In complex systems, the way you write data is often very different from how you want to read it. These two concerns have fundamentally different requirements, yet most applications force them to share the same data model.

  • Write: "Process this complex order with 50 validation rules." Needs strong consistency, transactional integrity, and domain logic enforcement.
  • Read: "Show me all orders placed by users in Texas, sorted by value." Needs speed, flexible filtering, and pre-joined data.

Using the same normalized SQL schema for both leads to painful compromise. Your write model is clean and consistent, but every read requires 10 slow JOINs across 8 tables. Alternatively, you denormalize for reads and your write logic becomes fragile.

Command Query Responsibility Segregation (CQRS)

CQRS — Command Query Responsibility Segregation — proposes a clean architectural split: the part of your system that changes state and the part that reads state should be completely separate, with separate models, separate databases, and separate code paths.

  1. Command Side (Write): Handles business logic. Accepts Commands — requests to change state (e.g., BookFlight, CancelOrder). Validates them against domain rules. If valid, produces Events (e.g., FlightBooked, OrderCancelled) and appends them to the Event Store.
  2. Query Side (Read): Handles data retrieval. Listens to Events from the Command side and updates one or more Read Models — purpose-built databases (like Elasticsearch, Redis, or a denormalized SQL table) optimized for specific query patterns.

The Consistency Trade-off

The Read side is Eventually Consistent. After a command succeeds and an event is written, it takes a small but nonzero amount of time — typically milliseconds to seconds — for the event to propagate to the Read Model. During that window, a query might return stale data.

This is acceptable for most read operations (showing a user their order history) but completely unacceptable for business-critical decisions (authorizing a financial transaction). Knowing which side to query for which purpose is the central skill in CQRS design.

Interview Tip

Interviewers frequently ask: "If CQRS has eventual consistency on the read side, how do you handle a user who just submitted a form and immediately sees stale data?" The answer is a pattern called read-your-own-writes: after a command succeeds, the client either polls until the read model reflects the change, uses a version token to request a minimum-version read, or optimistically updates the UI client-side while the projection catches up. Acknowledge the trade-off and demonstrate you know how to mitigate it.

This is one of 18 chapters

Every chapter is free — Kubernetes, Terraform, SRE, distributed systems, and more — with fast daily review built in.

Sign up free