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.

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
| 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/UPDATEagainst normalized tables. - Query handlers bypass heavy domain aggregates completely and run tuned
SELECTstatements 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.
Commandpaths stay untouched; only read-heavy endpoints (GET /analytics,GET /orders/export) switch connection pools.- When refreshing materialized views in production, always create a
UNIQUE INDEXon the view and runREFRESH MATERIALIZED VIEW CONCURRENTLY—otherwise PostgreSQL acquires anACCESS EXCLUSIVElock 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.

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:
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_centsFROM 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:
-- Query handler executes a single index lookup with zero joinsSELECT order_id, customer_name, item_count, total_cents, status, versionFROM order_summaries_viewWHERE customer_id = $1ORDER BY created_at DESCLIMIT 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:
- User submits
POST /orders→ returns201 Created. - Browser immediately redirects to
GET /orders25 ms later. - 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:
- Return a Version / LSN Token on Command: Return
{ orderId, version: 1 }in the201response. The client sends?minVersion=1(orX-Min-Version: 1) on the immediate follow-upGET. - 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 singleorderIddirectly from the primary write DB. - 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 aprocessed_eventsinbox 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/:idreturns the exact columns written byPUT /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
- Start at Level 1: separate
CommandandQueryhandlers inside one database first—you get 80% of the maintainability gain with zero eventual consistency. - 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.
- Use the Transactional Outbox at Level 3: pair async projections with
minVersionread-your-own-writes checks so users never observe stale state after a write.






