Microservices CQRS

Most applications read data far more often than they write it. Reads and writes need different shapes: writes enforce rules, and reads want fast, ready-made answers. CQRS, short for Command Query Responsibility Segregation, separates the two jobs into different models so each can excel.

Layman Explanation

A library has a returns desk and a reading room. Staff at the returns desk check membership, update records, and apply fines. Visitors in the reading room only browse shelves and search catalogs. Mixing both jobs in one counter would slow everyone down. CQRS splits the counter in two.

Commands and Queries

Command

A command asks the system to change something: PlaceOrder, CancelOrder, UpdateAddress. A command can succeed or fail, and it returns little more than an acknowledgment.

Query

A query asks a question: GetOrderSummary, ListOrdersForCustomer. A query never changes data.

Diagram: Separate Paths

                    +-------------------+
 Command  --------> |  Write model      | --> Write database
 (PlaceOrder)       |  validates rules  |       (normalized)
                    +---------+---------+
                              |
                         publishes event
                              |
                              v
                    +-------------------+
 Query  <---------  |  Read model       | <-- Read database
 (OrderSummary)     |  fast lookups     |       (denormalized)
                    +-------------------+

The write side protects business rules. The read side holds data pre-shaped for screens. An event carries each change from the write side to the read side.

Example: Online Store Order Page

The order page shows customer name, items, prices, and delivery status in one view. Building it from four tables on every request is slow. The read model stores one ready-made document per order and updates it whenever an event arrives.

Event: OrderPlaced      --> create summary document
Event: PaymentReceived  --> set status "Paid"
Event: OrderShipped     --> set status "Shipped", add tracking code

A query now fetches one document by id in a single lookup.

Benefits

  • Reads scale separately from writes, with as many read replicas as needed.
  • Each side uses the best database for its job, such as a relational store for writes and a search engine for reads.
  • Write logic stays focused on rules without display concerns.
  • Teams can add new read views without touching the write model.

Eventual Consistency

The read model updates a moment after the write. A user who places an order and instantly opens the order list may not see it for a short time. Designers handle this with a "processing" message, with optimistic screen updates, or by reading from the write side right after a command.

Levels of CQRS

LevelDescription
LightSeparate command and query code, one shared database
MediumSeparate read and write databases, synced by events
FullSeparate services, often paired with event sourcing

Start with the light level. Move up only when load or complexity demands it.

When to Avoid CQRS

Simple create, read, update, delete screens gain little from CQRS. The extra moving parts add cost without benefit. Reach for the pattern when read and write needs clearly differ or when read traffic dwarfs write traffic.

Choosing Databases for Each Side

The write side favors strong consistency and clear relationships, so a relational database fits well. The read side favors speed and flexible search, so a document store, a cache, or a search engine often wins. Separate models let you match the tool to the job without compromise.

Key Takeaways

CQRS gives commands and queries their own models. Events keep the read side current, and the price is brief inconsistency. Adopt it where the benefits outweigh the extra machinery.