CQRS: Command Query Responsibility Segregation
Separate write (command) models from read (query) models when read and write shapes diverge—and know when plain CRUD is better.
TL;DR
CQRS splits Commands (writes that enforce invariants and change state) from Queries (reads tailored for UI/API shapes). You don't need Event Sourcing or two databases to start—often just bypassing heavy domain Aggregates on reads is enough—and you should skip CQRS for simple CRUD.
Intent
Optimize writes for data integrity and reads for query speed and UI shape, instead of forcing one bloated ORM entity to serve both.
Problem
In a growing Order service, PlaceOrder needs a rich Order Aggregate with line items and pricing rules, while the "Admin Orders Dashboard" needs a paginated table joining orders, customers, and shipments—something that causes N+1 queries or ugly lazy-loading hacks if forced through the same domain model.
Solution
CQRS separates the codebase into two distinct paths:
- Command path (writes): accepts an intent (
PlaceOrderCommand), loads the Aggregate, enforces invariants, persists state, and returns an ID or void (not a giant view model). - Query path (reads): runs a read-only query (plain SQL, Postgres view, or denormalized read table) directly into a flat
OrderSummaryDto—zero domain entities, zero setters.
At Level 1, both paths share the same relational database. At Level 2 (high read scale), writes emit domain events that asynchronously update a separate read store (Elasticsearch, Redis, or denormalized tables).
Real-world analogy
▶ Flow: watch it work
CQRS: Command Write vs Query Read
Press Start or tap any step dot to trace the path.
▸All steps (8)
Code
Same-database CQRS in TypeScript—no second database required:
// Command side: mutates state and enforces invariants
export async function placeOrderCommand(
cmd: { customerId: string; totalCents: number },
insertOrder: (row: { id: string; customerId: string; totalCents: number }) => Promise<void>,
): Promise<{ orderId: string }> {
if (cmd.totalCents <= 0) throw new Error('Total must be positive');
const orderId = crypto.randomUUID();
await insertOrder({ id: orderId, customerId: cmd.customerId, totalCents: cmd.totalCents });
return { orderId };
}
// Query side: read-only flat DTO directly from SQL/view
export interface OrderDashboardRow {
orderId: string;
customerName: string;
totalCents: number;
}
export async function getOrderDashboardQuery(
queryDb: () => Promise<OrderDashboardRow[]>,
): Promise<OrderDashboardRow[]> {
return queryDb();
}When to use / when to avoid
- Read traffic and write traffic have very different shapes, complexity, or scale (e.g., complex writes vs heavy search/dashboards).
- You use DDD Aggregates on writes and want fast, join-friendly SQL queries on reads without polluting the domain model.
- Simple CRUD apps where the form fields match the table columns—CQRS doubles boilerplate for zero gain.
- If your team cannot tolerate eventual consistency on UI reads after a write (stick to single-DB CQRS or plain CRUD).
How to implement
Start with single-DB CQRS
Keep one database; separate commands/ (domain-validated writes) from queries/ (read-only SQL/views).
Split stores only when measured
Introduce an async read replica or search index only when query load or joins actually bottleneck the primary DB.
Pros / Cons
- Keeps write invariants clean while letting read queries use optimal SQL, indexes, or projections.
- Scales read and write workloads independently if stores are separated.
- More code paths and DTOs than standard CRUD.
- Async read stores introduce eventual consistency ("read-your-own-writes" UX bugs if unhandled).
Relations
Check yourself
Check Yourself
1. Do you need Event Sourcing or two separate databases to practice CQRS?
2. What UX bug commonly appears when a team adopts async read projections in CQRS?
Sources
Related Notes
Sources
DDD Tactical Patterns: Entities, Value Objects, Aggregates
Model rich domain rules using Entities, Value Objects, Aggregates, Repositories, and Domain Events on the shared Order service.
Event-Driven Architecture & the Transactional Outbox
Distinguish commands from events, avoid the dual-write bug, and guarantee reliable event publishing with the transactional outbox pattern.