Architecture
ArchitectureAdvanced

CQRS Pattern Explained: CQRS vs. Event Sourcing & 3 Levels of Complexity

How the CQRS pattern actually works in production: separating reads from writes in 3 progressive levels, CQRS vs Event Sourcing, and fixing eventual consistency.

Cover image: CQRS Pattern Explained: CQRS vs. Event Sourcing & 3 Levels of Complexity
Contents

CQRS (Command Query Responsibility Segregation) is the architectural pattern of separating operations that mutate state (Commands) from operations that read state (Queries)—using distinct models, code paths, and optionally distinct storage engines for each.

Most tutorials turn CQRS into an all-or-nothing jump straight to Kafka, microservices, and Event Sourcing. In reality, CQRS is a spectrum of three complexity levels, and 80% of production backends get the cleanest wins at Level 1 or Level 2 on a single PostgreSQL cluster—with zero eventual consistency bugs.

The core rule. CQRS ≠ Event Sourcing. CQRS separates how you write from how you read. Event Sourcing is a storage choice for the write side. You can—and usually should—adopt CQRS without Event Sourcing first.

CQRS Pattern Architecture: 3 Levels of Complexity from Single DB to Outbox Projections
CQRS scales progressively: start by splitting code models on one database before introducing async read stores.

From CQS to CQRS: why one model breaks down

Bertrand Meyer introduced Command-Query Separation (CQS) for object methods: a method should either change state or return data, never both. Greg Young scaled that idea to system architecture as CQRS: instead of forcing one ORM entity to serve both strict transactional writes and complex UI dashboards, split them into two dedicated models.

In a traditional CRUD service, a single Order entity quickly degrades:

  • Writes need strict invariants, normalized foreign keys, row-level locks, and minimal round-trips.
  • Reads need flattened joins across 6 tables, pre-computed totals, full-text search, and zero lock contention.

Trying to satisfy both with one repository creates N+1 queries on reads and bloated validation hooks on writes.

CQRS vs. Event Sourcing vs. CRUD

CQRS vs. Event Sourcing vs. CRUD
Dimension Classic CRUD CQRS (State-Based) CQRS + Event Sourcing
What it separates Nothing (shared entity) Write model vs. Read model Write event log vs. Read projections
Source of truth Current row state Current row state (Write DB) Immutable append-only event stream
Audit & time travel Requires manual audit triggers Requires manual audit table Built-in (replay events to any timestamp)
Consistency Strong (ACID) Strong (Level 1) or Eventual (Level 2–3) Eventual on all read projections
Operational cost Lowest Low–Medium High (event versioning, snapshots, upcasting)
Best fit Simple forms, admin panels Read/write skew, heavy dashboards, search Financial ledgers, compliance, collaborative state

The 3 Levels of CQRS Complexity

Level 1: Single Database, Separate Code Models

You keep one PostgreSQL database, zero message brokers, and zero eventual consistency. You only split your application layer into two slices:

  • Command handlers validate business rules and execute INSERT/UPDATE against normalized tables.
  • Query handlers bypass heavy domain aggregates completely and run tuned SELECT statements mapped straight to response DTOs.

This fits naturally inside the bounded contexts of Domain-Driven Design and keeps a modular monolith fast without distributed-systems overhead.

Level 2: Write Primary + Read Replicas / Materialized Views

When heavy reporting queries start exhausting CPU or buffer-pool cache on your primary database, route Query handlers to a read replica or query pre-aggregated PostgreSQL Materialized Views.

  • Replication lag on a read replica is typically 10–100 ms.
  • Command paths stay untouched; only read-heavy endpoints (GET /analytics, GET /orders/export) switch connection pools.
  • When refreshing materialized views in production, always create a UNIQUE INDEX on the view and run REFRESH MATERIALIZED VIEW CONCURRENTLY—otherwise PostgreSQL acquires an ACCESS EXCLUSIVE lock and blocks all concurrent reads until the refresh completes.

Level 3: Separate Read Store via Transactional Outbox (or Event Sourcing)

When PostgreSQL alone cannot serve your read shape—such as faceted full-text search in Elasticsearch/OpenSearch, sub-millisecond feeds in Redis/Valkey, or billion-row OLAP rollups in ClickHouse—you build an asynchronously updated Read Projection.

CQRS + Transactional Outbox + Eventual Consistency Lifecycle
Transactional Outbox eliminates dual-write drift, while version tokens prevent stale reads right after a command.

Practical Example: Command vs. Query in PostgreSQL + Outbox

Here is what clean Level 3 CQRS looks like without framework magic. The Command side enforces invariants and writes both the normalized order and an outbox event in one transaction:

write-side-command.sql
BEGIN;
INSERT INTO orders (id, customer_id, status, total_cents, version)
VALUES ($1, $2, 'CONFIRMED', $3, 1);
INSERT INTO order_items (order_id, sku, qty, unit_price_cents)
SELECT $1, sku, qty, unit_price_cents
FROM jsonb_to_recordset($4::jsonb) AS x(sku text, qty int, unit_price_cents int);
INSERT INTO outbox_events (id, aggregate_id, event_type, payload, version)
VALUES (gen_random_uuid(), $1, 'OrderConfirmed', jsonb_build_object(
'orderId', $1, 'customerId', $2, 'totalCents', $3, 'version', 1
), 1);
COMMIT;

An outbox worker (or Debezium CDC) projects that event into a flat, pre-joined read table (or Elasticsearch document) optimized purely for UI rendering:

read-side-projection.sql
-- Query handler executes a single index lookup with zero joins
SELECT order_id, customer_name, item_count, total_cents, status, version
FROM order_summaries_view
WHERE customer_id = $1
ORDER BY created_at DESC
LIMIT 20;

Solving the #1 CQRS Bug: Eventual Consistency on Read-After-Write

Every team hitting Level 2 or Level 3 CQRS hits the same bug in week one:

  1. User submits POST /orders → returns 201 Created.
  2. Browser immediately redirects to GET /orders 25 ms later.
  3. The outbox worker takes 80 ms to update order_summaries_view, so the user sees an empty list and clicks “Submit” again.

Three production patterns eliminate this cleanly:

  1. Return a Version / LSN Token on Command: Return { orderId, version: 1 } in the 201 response. The client sends ?minVersion=1 (or X-Min-Version: 1) on the immediate follow-up GET.
  2. Short Read-Barrier or Write-Store Fallback: If the read projection’s version < minVersion, either wait up to 150 ms for the projection to catch up or read that single orderId directly from the primary write DB.
  3. Optimistic UI for Non-Critical Views: For feeds and dashboards, render the confirmed command payload locally while the background projection catches up.

Idempotent Projections & Zero-Downtime Rebuilds

At Level 3, out-of-order deliveries and schema changes are guaranteed over time:

  • Guard updates with version checks: Every projection handler must be idempotent. When updating an existing row, add WHERE version < $event_version (or insert into a processed_events inbox table) so a replayed or out-of-order message never overwrites newer state.
  • Rebuild projections blue-green: When product requirements add new columns to a read view, create order_summaries_v2, backfill it in batches from the write store (or replay the event log while dual-subscribing new events), verify row counts, and swap the read alias/table atomically without downtime. If you use Event Sourcing, pair long-lived streams with periodic snapshots and event upcasters so replays do not stall on millions of historical events.

When You Should NOT Use CQRS

Skip CQRS (or stay strictly at Level 1) when:

  • Your domain is simple CRUD: standard settings pages, user profiles, and back-office tables do not benefit from split models.
  • Read and write shapes are identical: if GET /users/:id returns the exact columns written by PUT /users/:id, splitting them only doubles boilerplate.
  • Your team cannot absorb operational overhead: Level 3 CQRS + Event Sourcing adds schema evolution, projection rebuilds, dead-letter queues, and lag monitoring.

The Bottom Line

  1. Start at Level 1: separate Command and Query handlers inside one database first—you get 80% of the maintainability gain with zero eventual consistency.
  2. Do not confuse CQRS with Event Sourcing: keep state-based PostgreSQL tables on the write side unless your business genuinely requires an immutable event ledger.
  3. Use the Transactional Outbox at Level 3: pair async projections with minVersion read-your-own-writes checks so users never observe stale state after a write.

Frequently asked questions

What is the difference between CQRS and Event Sourcing?

CQRS separates the write model (commands) from the read model (queries). Event Sourcing stores every state change as an immutable sequence of domain events instead of overwriting current state in a table. You can use CQRS with plain relational tables and zero Event Sourcing.

Can I use CQRS without microservices or Kafka?

Yes. Most teams get 80% of the benefit inside a modular monolith backed by a single PostgreSQL database: commands execute domain invariants in normalized tables, while queries read tuned SQL views or projections without ORM bloat.

Does CQRS always introduce eventual consistency?

Only when the read model lives in an asynchronously updated store (Level 3) or a lagging read replica (Level 2). At Level 1, where both models query the same primary database, reads are strongly consistent.

How do you handle eventual consistency in CQRS APIs?

Return a monotonic entity version or commit LSN from the command endpoint, pass it on the next read, and either wait briefly until the projection reaches that version or fall back to reading from the write store for that single request.

When should you NOT use CQRS?

Avoid CQRS for standard CRUD admin panels, low-traffic internal tools, or domains where write and read shapes are nearly identical. Splitting models adds boilerplate that only pays off when read and write workloads diverge.

How do CQRS and the Transactional Outbox pattern fit together?

At Level 3, the command handler updates the normalized write table and inserts a domain event into an outbox table in the same ACID transaction. A relay publishes that event to update the read projection reliably without dual-write data loss.

ENDE