---
title: "CQRS Pattern Explained: CQRS vs. Event Sourcing & 3 Levels of Complexity"
description: "How the CQRS pattern actually works in production: separating reads from writes in 3 progressive levels, CQRS vs Event Sourcing, and fixing eventual consistency."
author: Aleksei Aleinikov
date: 2026-11-26
lang: en
tags: [cqrs, cqrs pattern, cqrs vs event sourcing, cqrs architecture, command query responsibility segregation, eventual consistency]
canonical: https://www.alekseialeinikov.com/en/blog/topics/architecture/cqrs-pattern-and-event-sourcing
source: alekseialeinikov.com
---

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

**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.

> [!KEY]
> **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](https://media.alekseialeinikov.com/architecture/cqrs-pattern/three-levels-1200.3fd9dce32f04b630.webp "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

| 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](https://www.alekseialeinikov.com/en/blog/topics/architecture/domain-driven-design-2026-a-practical-guide) and keeps a [modular monolith](https://www.alekseialeinikov.com/en/blog/topics/architecture/monolith-vs-microservices-2026-honest-trade-offs) 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**.

> [!NOTE]
> Never perform a dual write (writing to PostgreSQL and publishing to Kafka/Elasticsearch in two separate network calls). If the second call fails, your read model silently drifts forever. Pair Level 3 CQRS with the [Transactional Outbox Pattern](https://www.alekseialeinikov.com/en/blog/topics/architecture/transactional-outbox-pattern) so state mutation and event emission share one ACID transaction.

![CQRS + Transactional Outbox + Eventual Consistency Lifecycle](https://media.alekseialeinikov.com/architecture/cqrs-pattern/outbox-consistency-1200.2b1b63941167746f.webp "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:

```sql title="write-side-command.sql" {1-2,10-15}
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:

```sql title="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.
