CQRS

Also known as: Command query responsibility segregation

On this page 7

CQRS, or command query responsibility segregation, is a software architecture pattern that splits an application into a write model that handles commands and a separate read model that answers queries, so that each side can use its own data structures, storage and scaling strategy. It is applied mainly in domains where the way data is changed differs sharply from the way it is viewed.

The pattern grew out of the command-query separation principle, which says a method should either change state or return data, never both. CQRS lifts that rule from individual methods to the level of whole models and services, which brings real flexibility but also significant added complexity.

How CQRS separates commands from queries

CQRS works by routing every request down one of two distinct paths. A command expresses an intent to change state, such as PlaceOrder or ChangeShippingAddress, and returns at most an acknowledgment or an identifier. A query asks for data and must never change state, which makes it safe to cache, repeat and scale freely.

On the write side, a command handler loads the relevant domain object, often a domain-driven design aggregate, checks business rules and invariants, and persists the result. On the read side, query handlers read from denormalized projections shaped exactly for each screen or API response, so a dashboard can fetch one prepared row instead of joining ten normalized tables.

When the two sides use separate stores, changes travel from the write model to the read model through domain events or change data capture. A component called a projector consumes those events and updates the read tables. The table below lists the main building blocks.

ComponentSideResponsibility
CommandWriteCarries an intent to change state
Command handlerWriteValidates rules and updates the write model
Write storeWriteHolds authoritative, normalized or event data
Domain eventBridgeRecords a fact that has already happened
ProjectorBridgeTurns events into read-model updates
Read storeReadHolds query-optimized, denormalized views
Query handlerReadReturns data without side effects
Core components of a CQRS system

Levels of CQRS implementation

CQRS is not a single fixed design but a spectrum of separation, and teams should adopt only as much as the problem requires. The lightest form keeps one database and simply separates code paths; the heaviest uses different databases, technologies and deployment units for each side.

LevelData storageConsistencyTypical use
Separate code pathsOne shared databaseImmediateClean code organization in modest applications
Separate read viewsOne database with views or tablesImmediate or near real-timeHeavy reporting on a transactional schema
Separate data storesDifferent databases per sideEventual, often milliseconds to secondsHigh read load or specialized search
CQRS with event sourcingEvent store plus projectionsEventualAudit-critical, temporal domains
Degrees of separation in CQRS

Moving down the table increases independent scalability and modeling freedom, but every step also adds infrastructure, failure modes and operational work. Many successful systems stop at the second level.

CQRS is often confused with neighboring patterns because they frequently appear together. The most important distinction is that CQRS does not require event sourcing, and event sourcing does not strictly require CQRS, although event-sourced systems almost always need separate read models to be queryable.

ConceptCore ideaRelationship to CQRS
Command-query separationMethods either change state or return dataThe object-level principle CQRS generalizes
Event sourcingStores state as a sequence of eventsCommon write-side companion, not mandatory
Event-driven architectureComponents react to published eventsOften carries updates to read models
MicroservicesIndependently deployable servicesCQRS may apply inside one service, not across all
Classic CRUD modelOne model for create, read, update, deleteThe simpler alternative CQRS replaces
How CQRS relates to neighboring concepts

CQRS should be applied within a bounded context, not across an entire system. A single application can use CQRS for its pricing engine while keeping straightforward CRUD for user profile settings.

When to apply CQRS

CQRS pays off when read and write workloads differ strongly in volume, shape or rules. Typical signals are read-to-write ratios of a hundred to one or more, many different views of the same data, complex validation on writes, and collaborative domains where many users change the same records.

SituationRecommendationReason
Simple forms over a databaseUse plain CRUDSeparation adds cost without benefit
Heavy reporting on transactional dataAdd separate read viewsRemoves expensive joins from queries
Search, analytics and transactions on one datasetSeparate data storesEach store is tuned for its workload
Strict audit and history requirementsCombine with event sourcingEvents provide a complete change log
Small team with tight deadlinesDefer full CQRSOperational overhead can outweigh gains
Decision guide for adopting CQRS

A practical rule is to start with the lightest level and introduce separate stores only when measurements show that a single model is the bottleneck.

Limitations and common mistakes with CQRS

The central trade-off of CQRS is eventual consistency: with separate stores, a user may submit a change and briefly see stale data. Interfaces must handle this deliberately, for example by returning the new state from the command response, showing a pending status, or reading from the write side immediately after an update.

  • Applying CQRS system-wide turns simple modules into needlessly complex ones; limit it to contexts that need it.
  • Returning query data from commands reintroduces coupling and blurs the separation.
  • Ignoring projection failures leaves read models silently out of date; projectors need monitoring, retries and idempotent handlers.
  • Lacking a rebuild strategy makes schema changes painful; read models should be rebuildable from the source of truth.
  • Assuming CQRS improves performance automatically is wrong, because extra hops and synchronization can slow simple workloads.

Understanding it simply

Think of a busy library. One desk handles returns and new books, and it carefully checks and records every change. A separate display board shows what is available, arranged in the way visitors like to browse. CQRS organizes software the same way, with one part for making changes and another part for answering questions.

Because the two parts are separate, each can be built and grown for its own job. The cost is that the board may lag behind the desk for a moment, and running two parts takes more effort than running one.

Applied in practice

An online ticketing platform sells seats for concerts. Writes are relatively rare but must enforce strict rules, since no seat may be sold twice, while reads are enormous: during a popular on-sale, thousands of visitors per second refresh seat maps and event listings.

The team applies CQRS inside its booking context. Commands such as ReserveSeat go to a transactional relational database that locks seats and validates payment holds. Each successful reservation publishes a SeatReserved event, and projectors update a cached seat-availability view and a search index, usually within about one second.

During the next major sale, read traffic is served by horizontally scaled read replicas and caches, and the write database handles only reservations. The platform stays responsive, and the brief lag is covered by a final availability check when the visitor confirms the purchase.