CQRS Pattern

Decide whether separate command and query models solve a real problem, how to begin in one store, and when a read model can tolerate lag.

published: reading time: 9 min read author: Geek Workbench updated: November 8, 2026
Quick Summary

CQRS separates the model that handles commands from the model that answers queries. The two models can begin in one application and one database; separate stores and asynchronous projections are optional choices that bring synchronization work and possible read lag. Use CQRS when different read and write needs justify that complexity. Event sourcing is a separate choice for systems that need durable event history or replay.

CQRS Pattern

CQRS separates commands that change state from queries that return data. It does not require separate databases, event sourcing, or asynchronous updates. Start by asking whether different read and write models make the code easier to shape or maintain.

Introduction

A command expresses an intent such as PlaceOrder; a query asks for information such as GetOrderSummary. CQRS gives each a distinct model. The models can still live in one application and use one database. A separate read store is an optional step when a query shape or workload needs it.

This guide focuses on that decision. For durable event history and replay, see Event Sourcing: Projections, Replay, and Recovery only when those capabilities are required.

Command Model vs Query Model

A command represents intent to change state. “Place order,” “update shipping address,” “cancel subscription.” Commands return success or failure, not data.

A query represents a request for data. “Show my orders,” “what is my account balance,” “list products in category.” Queries return data without changing state.

In a typical CRUD system, these look identical. A POST to /orders might create an order and return it. A GET to /orders lists orders. Both hit the same database and often the same table structure.

CQRS separates these. Commands go to one model, queries to another.

class PlaceOrderCommand:
    def __init__(self, customer_id, line_items):
        self.customer_id = customer_id
        self.line_items = line_items

class GetCustomerOrdersQuery:
    def __init__(self, customer_id):
        self.customer_id = customer_id

One model, then separate read and write models

Before CQRS, the same query may assemble the order summary from several normalized tables:

SELECT o.id, o.status, c.name, SUM(i.quantity * i.unit_price) AS total
FROM orders o
JOIN customers c ON c.id = o.customer_id
JOIN order_items i ON i.order_id = o.id
WHERE o.id = :order_id
GROUP BY o.id, o.status, c.name;

With CQRS, keep the command model responsible for validating and saving changes, then expose a read model shaped for this query:

OrderSummary(order_id, status, customer_name, total)

The query model can be a view or table in the same database. Move it to a separate store only if measured query needs justify the extra synchronization and recovery work.

Consistency and the read path

CQRS alone does not make reads eventually consistent. If command and query handlers use the same transactional store, a query can read committed state according to that store’s isolation rules. If the read model updates asynchronously, a query may lag behind a successful command until its projection catches up.

Choose that trade-off per query. For a view where stale data could mislead users, read from the authoritative model or return the confirmed command result. For a view that can tolerate lag, show its freshness or a pending state. Measure append-to-query visibility in your own system and set an objective based on what the user needs.

Handling the gap in a user interface

After a command succeeds, the user may check a read model that has not caught up. The UI can show that the change was accepted and mark the view as updating. It can also wait until the projection reaches the command’s version, refresh on a bounded schedule, or show the confirmed command result locally. If the command fails, present the rejection and reconcile any optimistic state.

Event sourcing is optional

CQRS separates command and query models. Event sourcing stores domain changes as the source of truth and rebuilds state from that history. You can use CQRS with current-state storage, and you can use event sourcing without separate query models.

Choose event sourcing only when durable history, replay, or historical reconstruction has a concrete use. It adds event retention, schema evolution, privacy, and recovery work. The event-sourcing guide covers those operations.

When CQRS Makes Sense

CQRS may help when:

  • The read representation differs from the command model.
  • Read and write workloads need different query or storage designs.
  • Separate models make validation or access control easier to reason about.

Illustrative example: an order command updates normalized transactional records, while an order-history query serves a customer-ready summary. The read model can start as a view in the same database. This separation does not guarantee faster queries; measure before adding another store.

When CQRS Is Overkill

CQRS adds a second model and mapping logic. A separate store adds synchronization, lag handling, monitoring, and recovery. Keep a single CRUD model when reads and writes fit the same data shape and the current system meets its needs.

Relationship with Read/Write Splitting

Read/write splitting sends queries to a replica while writes go to a primary. It keeps the same data model and can expose replication lag. CQRS separates the application models; it may use one store or separate stores. Use read replicas when the same model works for both paths. Use CQRS when the read and write representations themselves need to differ.

Production Failure Scenarios

Failure Impact Mitigation
Asynchronous projection falls behind A query returns an older view Track freshness, show pending state where needed, and investigate consumer errors before scaling
Write commits but change notification is lost The read model misses an update Use a transactional outbox or change feed when the store and publisher cannot share a transaction
Duplicate change is processed A projection applies an update twice Make handlers idempotent and persist a checkpoint or processed version
Two commands race A stale command overwrites a newer change Use the database’s concurrency control and return a retryable conflict
A new read model is introduced Existing queries and new projection may disagree during rollout Build and compare the new model before switching readers; keep rollback available

CQRS vs Traditional CRUD Trade-offs

Dimension CQRS Single CRUD model
Model shape Separate command and query models One model serves both paths
Storage Same store is possible; separate stores are optional Usually one store
Consistency Depends on how models share and update data Depends on the database and transaction design
Query performance May improve when the read model matches the query Depends on schema, indexes, and query design
Operational work Mapping and, if asynchronous, projection monitoring and recovery One main data path
Best fit Distinct read/write needs justify separate models The same model fits reads and writes well

See Also

Interview Questions

1. An asynchronous read model is stale after a successful command. How would you investigate?

First check the projection's checkpoint, oldest unprocessed change, handler errors, and destination-store health. Compare append-to-query visibility with the freshness objective. Scale workers only after checking whether the work can be partitioned without breaking ordering. Show a pending state or a read-your-writes path if the user needs confirmation before the projection catches up.

2. Does CQRS require separate databases?

No. Begin with distinct command and query models in one application and one database. A view or query table may be enough. Separate stores add synchronization, monitoring, and recovery work, so move data only when a measured need justifies it.

3. Two commands try to change the same record. What should happen?

Use the storage layer's transaction or concurrency check so a command based on stale state cannot silently overwrite a newer change. Return a conflict that lets the caller reload and decide whether to retry. The exact mechanism depends on the database; CQRS does not supply it automatically.

4. When is CQRS unnecessary?

When one model serves the read and write paths clearly and performs well enough. Keep CRUD if you cannot name a concrete problem that separate models solve.

5. How do commands differ from events?

A command asks the system to do something and may be rejected. An event records something that already happened. A command handler may emit an event after validation, but CQRS does not require a message broker or asynchronous delivery.

6. What if a database commit succeeds but publishing a change fails?

If the write and message broker cannot share a transaction, a transactional outbox can record the change beside the database update. A publisher retries from the outbox, and consumers handle duplicates idempotently. Use this when asynchronous propagation is part of the design; a same-store query path does not need an event bus.

7. Do multiple read models need to contain the same data?

No. Each read model can answer a different query. Track whether each one has processed the required changes, keep handlers retry-safe, and compare important projections with the authoritative write data. Different views should agree on shared facts, but they do not need identical schemas or rows.

8. When should CQRS be paired with event sourcing?

Only when durable event history or replay has a clear use. Event sourcing adds retention, schema evolution, privacy, and recovery concerns. See the event-sourcing operations guide for that separate decision.


Further Reading

Architecture Resources:

Implementation Guides:

Design Patterns:


Conclusion

CQRS separates the model that handles commands from the model that answers queries. The models can share a database; asynchronous projections and separate stores are optional choices with added operational costs.

Start with one model. Split it when different read and write needs are making a concrete problem, and keep event sourcing as a separate decision for durable history or replay.


Category

Related Posts

Event Sourcing

Storing state changes as immutable events. Event store implementation, event replay, schema evolution, and comparison with traditional CRUD approaches.

#database #event-sourcing #cqrs

Event Sourcing: Projections, Replay, and Recovery

An operations guide to event streams, idempotent projections, schema changes, snapshots, lag, and safe read-model rebuilds.

#microservices #cqrs #event-sourcing

Publish/Subscribe Patterns: Topics, Subscriptions, Filtering

Learn publish-subscribe messaging patterns: topic hierarchies, subscription management, message filtering, fan-out, and dead letter queues.

#messaging #patterns #architecture