DBRaven
Pattern · consistency

CQRS (Command Query Responsibility Segregation)

mature

Summary

Separate the write model (commands that mutate state) from the read model (queries that return data), allowing each side to be optimised, scaled, and evolved independently.

Problem

A single domain model optimised for writes (normalised, consistent, transactional) is a poor fit for read workloads that need denormalised, aggregated, or purpose-shaped data: and vice versa. Forcing both through the same model causes index explosion, complex queries, and scaling bottlenecks.

Description

In a CQRS system, the write side accepts commands: validated, domain-logic- bearing operations that produce state changes. The write model is typically a normalised relational schema or an event store optimised for consistency and integrity. Every successful command produces one or more events that are published to a stream or event bus.

The read side consumes those events and builds purpose-built read models (projections). Each projection is a denormalised data structure shaped exactly for one query pattern: a flat document for a list view, an aggregated row for a dashboard widget, a pre-joined result set for a product detail page. Read models live in whichever storage engine fits the query: Redis for hot-path lookups, Elasticsearch for full-text search, PostgreSQL for relational reporting, ClickHouse for analytical aggregates.

The separation allows the write side to remain simple and consistent while the read side can be horizontally scaled, cached aggressively, and rebuilt on demand. If a new query pattern emerges, a new projection is built by replaying the event stream : no schema migration on the write side is required.

The fundamental tradeoff is eventual consistency: after a command is accepted, there is a window (typically milliseconds to seconds) during which the read model has not yet been updated. Applications must be designed to handle this lag: showing optimistic updates in the UI or explicitly routing reads-after- writes to the command side.

Tradeoffs

Read performance
+0.9

Pre-shaped projections eliminate expensive joins at query time

Write simplicity
+0.7

Write model stays normalised and consistent

Query flexibility
-0.4

New query patterns require new projections; no ad-hoc SQL on write store

Consistency
-0.6

Eventual consistency is mandatory; read-your-own-writes requires routing logic

Operational complexity
-0.7

Multiple stores, projection consumers, and lag monitoring multiply ops surface

Scalability
+0.8

Read side scales independently and horizontally

When to use

Read and write workloads have substantially different scaling requirements

If reads are 10x–100x more frequent than writes, separate scaling is a significant cost and performance advantage

Multiple distinct query shapes are needed from the same domain data

Each projection can be tailored to its consumer without affecting the write model or other projections

Domain is already modelled with events or commands

CQRS pairs naturally with event sourcing; the event stream feeds all projections without additional coupling

Application can tolerate eventual consistency on reads

Projection lag is inherent; if all reads must see the latest write immediately, CQRS requires additional routing complexity

When not to use

Application is a simple CRUD system with no complex query needs

The projection infrastructure overhead is not justified when a single relational model serves all access patterns adequately

Strong read-your-own-writes consistency is required everywhere

Routing every read to the command side after a write negates most of the benefit; the architecture should be reconsidered

Team size is small and operational overhead must be minimised

Managing separate write stores, event streams, and multiple projections multiplies operational surface area significantly

Operational Requirements

mandatory

Instrument projection consumer lag and alert on sustained lag >1s

Projection lag directly equals read staleness; sustained lag means reads are returning data that may be minutes or hours behind writes

mandatory

Implement idempotent projection consumers

Event delivery may be at-least-once; applying the same event twice must produce the same result, otherwise projections will contain duplicates

recommended

Build and test projection rebuild tooling

Projections are derived data and must be fully rebuildable from the event stream; this capability must be exercised before production incidents require it

recommended

Define consistency SLA for each projection

Different projections may have different acceptable lag windows; define and communicate these explicitly to product and engineering

Characteristics

Scales on
read
Implementation complexityhigh
Operational complexityhigh
Scaling ceilingProjection lag becomes the primary operational constraint at high write rates. If the event stream produces 50,000 events/second and each projection consumer can process 10,000 events/second, five parallel consumer instances are needed. Projection rebuild time grows linearly with event history; a 1-billion-event log may take hours to replay, during which that projection is stale.

Technologies

Canonical

postgresqlrediselasticsearchkafka

Alternatives

axon frameworkeventstoredbclickhouse

Relationships

Evolves from

read replica

Complements

event sourcingmaterialized viewcache aside

Basis

Well-established pattern with clear operational characteristics; eventual consistency tradeoff is real and frequently underestimated in practice

Related Architecture Knowledge

Outbound: this entity affects

ComplementsPattern
materialized view
Grounded

CQRS separates the write model (normalized, ACID) from the read model; materialized views implement the read model by pre-computing the denormalized view that the query side serves. Each pattern makes the other more operationally tractable.

Tradeoffs

  • ·Eventual consistency between write model and materialized views is inherent to the pattern
  • ·Multiple views add storage and refresh overhead: each view is a separately maintained copy of data
  • ·Debugging requires understanding which view version a query returned: important for support workflows
Full relationship →

Inbound: affects this entity

ComplementsPattern
event sourcing
Grounded

Event sourcing naturally produces a normalized write model (the event log) that CQRS separates from purpose-built read models (projections). Each pattern addresses what the other lacks: event sourcing provides audit and temporal query; CQRS provides fast reads without replay cost.

Tradeoffs

  • ·Two models to maintain: event schema evolution affects both command handlers and projection logic
  • ·Projection rebuild (full event replay) can take hours for mature systems with large event logs
  • ·Debugging requires correlating commands, events, and projection state across three separate stores
Full relationship →

Used In Architecture Scenarios

AI Retrieval-Augmented Generation Platformhigh

AI / RAG Application

A Retrieval-Augmented Generation (RAG) architecture that combines vector similarity search for semantic document retrieval with relational metadata filtering, using PostgreSQL with pgvector as the unified store for both embeddings and structured data. Redis provides a semantic cache to avoid redundant embedding model inference and reduce vector index query load for repeated or similar queries. Kafka manages the asynchronous embedding generation pipeline that keeps the vector index current as source documents are added or updated.

Analytics Data Platformhigh

Analytics Pipeline

An OLAP-oriented analytics architecture that ingests operational changes from PostgreSQL via WAL-based CDC into Kafka, then routes them to a columnar analytics store (ClickHouse or Snowflake) for product analytics, business intelligence, and operational reporting. The CQRS separation ensures analytical queries never degrade transactional write performance, and materialized views provide pre-aggregated query acceleration for the most expensive analytical patterns.

Content Management Platformmoderate

Read-Heavy Application

A CMS for publishing and serving structured content: articles, documentation, product pages, and localized variants: where read APIs serve 50–100x more traffic than editorial write APIs. PostgreSQL stores the content graph (articles, authors, categories, taxonomy) and workflow state (draft, in-review, scheduled, published). Redis caches published content objects for read APIs. Elasticsearch powers full-text content search with faceting and relevance ranking. Cache invalidation on publish must be fast and complete; N+1 query patterns on content relationship traversal are the dominant database performance risk during reads.

E-Commerce Order Platformhigh

Marketplace Platform

An e-commerce order lifecycle platform handling cart, checkout, payment, fulfillment, and returns across a mixed read/write workload where product discovery is read-heavy, checkout is write-transactional, and fulfillment is event-driven. The saga pattern orchestrates multi-step checkout: reserve inventory → charge payment → confirm order → notify fulfillment. PostgreSQL owns order records and inventory with row-level locking; Redis holds session state and cart contents with sub-millisecond access; RabbitMQ delivers fulfillment notifications with dead-letter handling; Elasticsearch serves product search and order history with faceted navigation. CQRS separates the write command path from the read model: the order read model is denormalized for fast order history queries without joining across domain tables.

Financial Ledger Platformexpert

Financial Ledger

A strict consistency financial architecture for double-entry accounting, payment processing, and audit trail management where every debit must have a corresponding credit, every state transition must be ordered and durable, and the complete history must be reconstructable without gaps. Event sourcing provides an append-only audit log; the outbox pattern guarantees at-least-once downstream event delivery without distributed two-phase commit (idempotent consumers deduplicate on event ID for effectively-once processing); PostgreSQL provides ACID guarantees for ledger entry atomicity.

Healthcare Records Platformexpert

Financial Ledger

An electronic health record (EHR) architecture built around strict auditability, HIPAA compliance, and append-only correctness. Clinical records are mutable by design (amendments, addenda) but corrections must be explicitly attributed, not silently overwritten. Event sourcing provides a reconstructable audit log; PostgreSQL row-level security enforces patient-level access control at the database layer; Kafka streams HL7 FHIR events to downstream clinical systems. The architecture must support breach detection, access auditing, and state reconstruction at any historical point: not just current state retrieval.

ML Feature Serving Platformexpert

AI / RAG Application

A low-latency feature serving platform for ML model inference, providing both batch (offline) and real-time (online) feature access with strict training-serving consistency. Redis serves the hot feature cache with p99 latency targets below 5ms for online inference requests; PostgreSQL provides point-in-time feature lookups for offline training jobs with temporal consistency guarantees; Cassandra stores high-cardinality feature entities at write scale beyond PostgreSQL's single-primary ceiling; Kafka streams feature computation events from online feature pipelines to update the cache; Qdrant stores vector features for embedding-based model inputs and similarity lookups; ClickHouse serves feature analytics and drift monitoring across training dataset populations. Feature versioning is first-class: every feature value is tagged with a pipeline_version and computed_at timestamp to support model reproducibility and training-serving skew diagnosis.

Search-Heavy Content Platformhigh

Search-Heavy Application

A content platform architecture centered on Elasticsearch for full-text search, faceted navigation, and ranked results, with PostgreSQL as the transactional source of truth and Redis for session management and hot content caching. WAL-based CDC maintains index freshness by streaming PostgreSQL changes into Elasticsearch asynchronously. The core tension is between search index freshness, query performance, and index maintenance cost under high write volume.

Two-Sided Marketplace Platformexpert

Marketplace Platform

A two-sided marketplace architecture serving buyers, sellers, listings, transactions, search, and notifications from a shared infrastructure, where multiple independent domains must coordinate without tight coupling. Event sourcing captures every state transition; the saga pattern orchestrates multi-step transactions (create order, reserve inventory, charge payment, notify seller) with compensating transactions for partial failures. Kafka decouples domain event publication from consumption; RabbitMQ handles notification fanout; Elasticsearch serves listing search; Redis caches listing display and session state.