Give writes and reads separate models, and often separate stores, so each can be designed, scaled and changed on its own terms. The write side enforces business rules on normalized data. The read side serves precomputed, denormalized views built asynchronously from the write side's events. You accept a bounded delay between the two.
CQRS (Command Query Responsibility Segregation) means the code and storage that change state are not the code and storage that answer questions. Commands go to a write model built to enforce invariants. Queries go to one or more read models, each shaped for a specific screen or API and kept up to date by projections that consume change events. This guide uses a single invented incident. An expense-management product's month-end dashboards overloaded the database that also accepted new claims. You will see how splitting the models fixed it, what eventual consistency costs, and how to explain the trade-offs in an interview without overselling the pattern.
The problem
A situation where the obvious design starts to hurt.
Ledgerly is an expense-management SaaS used by about 2,300 companies. Employees submit expense claims, managers approve or reject them, and finance teams watch spend dashboards broken down by team, cost centre and month. Everything lived in one Postgres database with a normalized schema: claims, line_items, approvals, policies, teams and cost_centers.
On a normal day the claims service handles around 35 commands per second and a few hundred dashboard reads per second. During the last three business days of the month, finance teams close their books. Commands rise to about 220 per second, and dashboard reads reach 2,500 per second. The main dashboard query joins six tables and groups by team and month. It takes about 800 ms under load.
At the May close, those dashboard queries held most of the 100-connection pool. The p99 of POST /claims went from 140 ms to 6.8 s, and about 3 percent of submissions hit the mobile client's 10 s timeout. Employees retried, which created duplicates for the finance team to clean up.
The team tried a read replica. Replication lag spiked to 40 s during heavy write bursts. The queries were still slow because the replica had the same normalized schema. Any index added to speed up a dashboard also slowed every insert on the primary. One schema could not serve both the approval rules and the finance dashboards well.
The solution
What the pattern proposes.
Split the service in two.
The Claims Command API owns the write model: claims and their line items, with the approval state machine and policy limits enforced in a single Postgres transaction. Each successful command writes the state change and an event row (ClaimSubmitted, ClaimApproved, ClaimRejected) to an outbox table in the same transaction. Each event carries the claim's new version number.
An outbox relay publishes those rows to a Kafka topic, claim-events, with 12 partitions keyed by claim_id. That key keeps all events for one claim in order.
Three projectors consume the topic, and each builds a read model for one consumer: - A spend projector maintains team_spend_monthly, a flat table with one row per team and month holding pending and approved totals. The dashboard becomes a primary-key lookup instead of a six-way join. - An inbox projector keeps a Redis sorted set per approver holding the claims waiting for them. - A search projector indexes claims into OpenSearch for free-text lookup by finance.
A separate Query API reads only from these stores and never touches the claims database.
Projectors are idempotent. Each stores the last applied version per claim next to the data it guards, in the same transaction. It skips any event whose version is not newer and stops on a gap.
The cost is that reads are eventually consistent. The read-lag target is p99 under 2 s. Where a user must see their own write, the command response returns the claim's version. The UI either renders the result optimistically or passes min_version to the Query API, which waits up to 1.5 s for the projection to catch up before returning a stale-but-flagged view.
An everyday analogy
The same idea, outside software.
Think of a busy hospital ward. The nurses' station keeps the authoritative patient charts: every medication change is written there, checked against the doctor's orders and signed. Nobody runs the hospital's bed-occupancy report by flipping through every chart. A clerk reads each new chart entry as it happens and updates a whiteboard that shows beds, discharges and pending transfers at a glance. The whiteboard is usually a minute or so behind the charts, and everyone knows it. If the whiteboard gets smudged, the clerk wipes it and rebuilds it from the charts. Nobody ever writes a medication change on the whiteboard.
Structure
The pieces and how they relate.
Participants
- Command API and write model
- Accepts commands such as SubmitClaim or ApproveClaim. Loads the claim, checks invariants (policy limits, valid state transitions, approver authority) and writes the new state with an incremented version. It never serves dashboards or lists.
- Write store with outbox
- The source of truth, normalized for correctness. The outbox table is written in the same transaction as the state change, so an event exists if and only if the change committed.
- Outbox relay
- Reads unpublished outbox rows in commit order and publishes them to the topic, then marks them sent. It delivers at least once, so downstream consumers must tolerate duplicates.
- Event topic
- Durable, ordered-per-key log of what happened. Partitioning by claim_id guarantees that a claim's events arrive at a projector in version order. Retention of 14 days lets a lagging or redeployed projector resume.
- Projectors
- One consumer group per read model. Each translates events into updates on its store, records the last applied version per entity in the same transaction, skips duplicates and halts on gaps. A projector can be dropped and rebuilt without touching the write side.
- Read stores
- Denormalized views shaped for one query pattern each: a flat totals table, Redis inboxes, a search index. They can use different technologies and can be thrown away and regenerated.
- Query API
- Serves reads only from read stores. It supports a min_version parameter so a client that just wrote can wait briefly for its own change to appear. It also reports a staleness flag when it cannot wait any longer.
Pseudocode
The solution to the scenario, language-neutral.
// Write side: one transaction per command
function handleApprove(cmd):
begin transaction
claim = writeDb.selectForUpdate(claims, cmd.claimId)
if claim.status != 'submitted': reject 409
if not canApprove(cmd.approverId, claim): reject 403
claim.status = 'approved'
claim.version = claim.version + 1
writeDb.update(claims, claim)
writeDb.insert(outbox, {
type: 'ClaimApproved', claimId: claim.id,
version: claim.version, occurredAt: now()
})
commit
return { claimId: claim.id, version: claim.version }
// Relay: at-least-once publish in commit order
loop every 100 ms:
rows = writeDb.select(outbox where sent_at is null order by id limit 500)
for row in rows: topic.publish(key = row.claimId, value = row)
topic.flush()
writeDb.update(outbox set sent_at = now() where id in rows)
// Projector: idempotent, ordered per claim
on message(event):
begin transaction on readDb
last = readDb.select(claim_versions, event.claimId) or 0
if event.version <= last: commit; ack; return // duplicate
if event.version != last + 1: rollback; raise Gap // stop partition, alert
applyToView(event) // upsert totals, etc.
readDb.upsert(claim_versions, event.claimId, event.version)
commit
ack(event)
// Query side with read-your-own-writes
function getClaimView(claimId, minVersion):
deadline = now() + 1.5 s
while readDb.version(claimId) < minVersion and now() < deadline:
sleep 50 ms
view = readDb.load(claimId)
view.stale = readDb.version(claimId) < minVersion
return viewThe code
The same solution in TypeScript, Python and PHP.
// Idempotent, order-checking projector for the team_spend_monthly read model.
// In production, claims and spend are two tables in the read DB, updated in a
// single transaction together with the per-claim version.
type Submitted = {
type: 'ClaimSubmitted';
claimId: string;
version: number;
teamId: string;
month: string; // e.g. '2024-05'
amountCents: number;
};
type Decided = { type: 'ClaimApproved' | 'ClaimRejected'; claimId: string; version: number };
type ClaimEvent = Submitted | Decided;
type Status = 'submitted' | 'approved' | 'rejected';
interface ClaimRow {
teamId: string;
month: string;
amountCents: number;
status: Status;
version: number;
}
interface SpendRow {
pendingCents: number;
approvedCents: number;
}
class ProjectionGapError extends Error {}
class TeamSpendProjector {
private readonly claims = new Map<string, ClaimRow>();
private readonly spend = new Map<string, SpendRow>();
apply(event: ClaimEvent): 'applied' | 'duplicate' {
const current = this.claims.get(event.claimId);
const lastVersion = current?.version ?? 0;
// Redelivery from the relay or the broker: safe to acknowledge.
if (event.version <= lastVersion) return 'duplicate';
// A gap means a lost or misrouted event. Stop rather than build wrong totals.
if (event.version !== lastVersion + 1) {
throw new ProjectionGapError(
`claim ${event.claimId}: expected v${lastVersion + 1}, got v${event.version}`,
);
}
if (event.type === 'ClaimSubmitted') {
this.claims.set(event.claimId, {
teamId: event.teamId,
month: event.month,
amountCents: event.amountCents,
status: 'submitted',
version: event.version,
});
this.adjust(event.teamId, event.month, event.amountCents, 0);
return 'applied';
}
if (!current || current.status !== 'submitted') {
throw new Error(`claim ${event.claimId}: ${event.type} without a pending submission`);
}
const approvedDelta = event.type === 'ClaimApproved' ? current.amountCents : 0;
this.adjust(current.teamId, current.month, -current.amountCents, approvedDelta);
current.status = event.type === 'ClaimApproved' ? 'approved' : 'rejected';
current.version = event.version;
return 'applied';
}
spendFor(teamId: string, month: string): SpendRow {
const row = this.spend.get(`${teamId}:${month}`);
return row ? { ...row } : { pendingCents: 0, approvedCents: 0 };
}
// Used by the Query API to honour min_version (read-your-own-writes).
appliedVersion(claimId: string): number {
return this.claims.get(claimId)?.version ?? 0;
}
private adjust(teamId: string, month: string, pendingDelta: number, approvedDelta: number): void {
const key = `${teamId}:${month}`;
const row = this.spend.get(key) ?? { pendingCents: 0, approvedCents: 0 };
row.pendingCents += pendingDelta;
row.approvedCents += approvedDelta;
this.spend.set(key, row);
}
}
const projector = new TeamSpendProjector();
const events: ClaimEvent[] = [
{ type: 'ClaimSubmitted', claimId: 'c-1', version: 1, teamId: 't-ops', month: '2024-05', amountCents: 12_500 },
{ type: 'ClaimSubmitted', claimId: 'c-2', version: 1, teamId: 't-ops', month: '2024-05', amountCents: 4_000 },
{ type: 'ClaimApproved', claimId: 'c-1', version: 2 },
{ type: 'ClaimApproved', claimId: 'c-1', version: 2 }, // redelivered
{ type: 'ClaimRejected', claimId: 'c-2', version: 2 },
];
for (const event of events) {
console.log(event.type, event.claimId, projector.apply(event));
}
console.log(projector.spendFor('t-ops', '2024-05')); // { pendingCents: 0, approvedCents: 12500 }
console.log(projector.appliedVersion('c-1')); // 2# Idempotent, order-checking projector for the team_spend_monthly read model.
# In production, claims and spend are two tables in the read DB, updated in a
# single transaction together with the per-claim version.
from __future__ import annotations
from dataclasses import dataclass
from typing import Literal, Optional
EventType = Literal['ClaimSubmitted', 'ClaimApproved', 'ClaimRejected']
@dataclass(frozen=True)
class ClaimEvent:
type: EventType
claim_id: str
version: int
team_id: Optional[str] = None
month: Optional[str] = None # e.g. '2024-05'
amount_cents: int = 0
@dataclass
class ClaimRow:
team_id: str
month: str
amount_cents: int
status: str
version: int
@dataclass
class SpendRow:
pending_cents: int = 0
approved_cents: int = 0
class ProjectionGapError(Exception):
pass
class TeamSpendProjector:
def __init__(self) -> None:
self._claims: dict[str, ClaimRow] = {}
self._spend: dict[tuple[str, str], SpendRow] = {}
def apply(self, event: ClaimEvent) -> str:
current = self._claims.get(event.claim_id)
last_version = current.version if current else 0
# Redelivery from the relay or the broker: safe to acknowledge.
if event.version <= last_version:
return 'duplicate'
# A gap means a lost or misrouted event. Stop rather than build wrong totals.
if event.version != last_version + 1:
raise ProjectionGapError(
f'claim {event.claim_id}: expected v{last_version + 1}, got v{event.version}'
)
if event.type == 'ClaimSubmitted':
if event.team_id is None or event.month is None:
raise ValueError(f'claim {event.claim_id}: submission without team or month')
self._claims[event.claim_id] = ClaimRow(
team_id=event.team_id,
month=event.month,
amount_cents=event.amount_cents,
status='submitted',
version=event.version,
)
self._adjust(event.team_id, event.month, event.amount_cents, 0)
return 'applied'
if event.type not in ('ClaimApproved', 'ClaimRejected'):
raise ValueError(f'unknown event type {event.type}')
if current is None or current.status != 'submitted':
raise RuntimeError(f'claim {event.claim_id}: {event.type} without a pending submission')
approved_delta = current.amount_cents if event.type == 'ClaimApproved' else 0
self._adjust(current.team_id, current.month, -current.amount_cents, approved_delta)
current.status = 'approved' if event.type == 'ClaimApproved' else 'rejected'
current.version = event.version
return 'applied'
def spend_for(self, team_id: str, month: str) -> SpendRow:
row = self._spend.get((team_id, month))
return SpendRow(row.pending_cents, row.approved_cents) if row else SpendRow()
# Used by the Query API to honour min_version (read-your-own-writes).
def applied_version(self, claim_id: str) -> int:
row = self._claims.get(claim_id)
return row.version if row else 0
def _adjust(self, team_id: str, month: str, pending_delta: int, approved_delta: int) -> None:
row = self._spend.setdefault((team_id, month), SpendRow())
row.pending_cents += pending_delta
row.approved_cents += approved_delta
if __name__ == '__main__':
projector = TeamSpendProjector()
events = [
ClaimEvent('ClaimSubmitted', 'c-1', 1, 't-ops', '2024-05', 12_500),
ClaimEvent('ClaimSubmitted', 'c-2', 1, 't-ops', '2024-05', 4_000),
ClaimEvent('ClaimApproved', 'c-1', 2),
ClaimEvent('ClaimApproved', 'c-1', 2), # redelivered
ClaimEvent('ClaimRejected', 'c-2', 2),
]
for e in events:
print(e.type, e.claim_id, projector.apply(e))
print(projector.spend_for('t-ops', '2024-05')) # SpendRow(pending_cents=0, approved_cents=12500)
print(projector.applied_version('c-1')) # 2<?php
// Idempotent, order-checking projector for the team_spend_monthly read model.
// In production, claims and spend are two tables in the read DB, updated in a
// single transaction together with the per-claim version.
declare(strict_types=1);
final class ProjectionGapException extends RuntimeException {}
final class TeamSpendProjector
{
/** @var array<string, array{teamId: string, month: string, amountCents: int, status: string, version: int}> */
private array $claims = [];
/** @var array<string, array{pendingCents: int, approvedCents: int}> */
private array $spend = [];
/** @param array{type: string, claimId: string, version: int, teamId?: string, month?: string, amountCents?: int} $event */
public function apply(array $event): string
{
$claimId = $event['claimId'];
$current = $this->claims[$claimId] ?? null;
$lastVersion = $current['version'] ?? 0;
// Redelivery from the relay or the broker: safe to acknowledge.
if ($event['version'] <= $lastVersion) {
return 'duplicate';
}
// A gap means a lost or misrouted event. Stop rather than build wrong totals.
if ($event['version'] !== $lastVersion + 1) {
throw new ProjectionGapException(sprintf(
'claim %s: expected v%d, got v%d',
$claimId,
$lastVersion + 1,
$event['version'],
));
}
if ($event['type'] === 'ClaimSubmitted') {
if (!isset($event['teamId'], $event['month'], $event['amountCents'])) {
throw new InvalidArgumentException("claim {$claimId}: submission without team, month or amount");
}
$this->claims[$claimId] = [
'teamId' => $event['teamId'],
'month' => $event['month'],
'amountCents' => $event['amountCents'],
'status' => 'submitted',
'version' => $event['version'],
];
$this->adjust($event['teamId'], $event['month'], $event['amountCents'], 0);
return 'applied';
}
if (!in_array($event['type'], ['ClaimApproved', 'ClaimRejected'], true)) {
throw new InvalidArgumentException("unknown event type {$event['type']}");
}
if ($current === null || $current['status'] !== 'submitted') {
throw new LogicException("claim {$claimId}: {$event['type']} without a pending submission");
}
$approvedDelta = $event['type'] === 'ClaimApproved' ? $current['amountCents'] : 0;
$this->adjust($current['teamId'], $current['month'], -$current['amountCents'], $approvedDelta);
$this->claims[$claimId]['status'] = $event['type'] === 'ClaimApproved' ? 'approved' : 'rejected';
$this->claims[$claimId]['version'] = $event['version'];
return 'applied';
}
/** @return array{pendingCents: int, approvedCents: int} */
public function spendFor(string $teamId, string $month): array
{
return $this->spend[$teamId . ':' . $month] ?? ['pendingCents' => 0, 'approvedCents' => 0];
}
// Used by the Query API to honour min_version (read-your-own-writes).
public function appliedVersion(string $claimId): int
{
return $this->claims[$claimId]['version'] ?? 0;
}
private function adjust(string $teamId, string $month, int $pendingDelta, int $approvedDelta): void
{
$key = $teamId . ':' . $month;
$row = $this->spend[$key] ?? ['pendingCents' => 0, 'approvedCents' => 0];
$row['pendingCents'] += $pendingDelta;
$row['approvedCents'] += $approvedDelta;
$this->spend[$key] = $row;
}
}
$projector = new TeamSpendProjector();
$events = [
['type' => 'ClaimSubmitted', 'claimId' => 'c-1', 'version' => 1, 'teamId' => 't-ops', 'month' => '2024-05', 'amountCents' => 12500],
['type' => 'ClaimSubmitted', 'claimId' => 'c-2', 'version' => 1, 'teamId' => 't-ops', 'month' => '2024-05', 'amountCents' => 4000],
['type' => 'ClaimApproved', 'claimId' => 'c-1', 'version' => 2],
['type' => 'ClaimApproved', 'claimId' => 'c-1', 'version' => 2], // redelivered
['type' => 'ClaimRejected', 'claimId' => 'c-2', 'version' => 2],
];
foreach ($events as $event) {
printf("%s %s %s\n", $event['type'], $event['claimId'], $projector->apply($event));
}
print_r($projector->spendFor('t-ops', '2024-05')); // pendingCents 0, approvedCents 12500
echo $projector->appliedVersion('c-1'), "\n"; // 2When to use it
Situations where it pays off.
Read and write workloads differ by an order of magnitude or more, or peak at different times, as at Ledgerly's month-end close where reads reached roughly 11 times the commands.
Separate stores mean dashboard load cannot exhaust the connection pool or lock rows the command path needs. Each side gets its own capacity plan.
Queries need shapes the normalized write schema serves badly: aggregates across many rows, full-text search, per-user inboxes, or data joined from several services.
Each read model is precomputed for its query. A six-table join becomes a primary-key lookup, and a search index can live in a search engine instead of a relational table.
The write side has real invariants: state machines, limits, authorization rules that must hold under concurrency.
Keeping the write model free of reporting concerns lets it stay small, normalized and strictly transactional, which is where those rules are easiest to enforce.
The business can tolerate reads that trail writes by a second or two for most screens, and you can name the few screens that cannot.
CQRS with asynchronous projections is only viable if staleness is acceptable by default and can be handled explicitly in the exceptions.
How to implement it
Steps to introduce it in existing code.
List the read paths and the command paths separately, with their rates and latency targets. Ledgerly found three read shapes (team-month totals, approver inbox, search) that accounted for most of the database time.
Make the write model emit events transactionally. Add a version column to the aggregate and an outbox table, and insert the event in the same transaction as the state change.
Publish outbox rows to a log partitioned by aggregate id, so per-entity ordering holds. Accept that delivery is at least once.
Write one projector per read model. Store the last applied version per entity in the read store, in the same transaction as the view update. Skip events at or below it and halt on gaps.
Backfill each read model before cutting traffic over. Replay from the outbox archive, or seed it from a snapshot of the write DB plus events after the snapshot's position, then compare totals against the old query for a sample of teams.
Move reads to the Query API behind a flag, one screen at a time. Return the new version from every command so clients can request read-your-own-writes where it matters.
Monitor consumer lag per projector, in both messages and seconds. Alert when it crosses the staleness the product promised, not an arbitrary queue depth.
Pros and cons
What you gain and what you pay.
Pros
- Dashboard load at month-end no longer touches the claims database, so command latency depends only on command traffic.
- Each read model uses the store that fits its query (Postgres totals, Redis inboxes, OpenSearch search) without compromising the write schema.
- New read models can be added later by replaying events into a new projector, with no change to the write side.
- Read models are disposable: a bug in a projection is fixed by rebuilding it, not by a risky migration on the source of truth.
- Read and write sides scale independently. Ledgerly can run 6 Query API replicas at close and 2 otherwise.
Cons
- Reads are eventually consistent. Every screen that shows data right after a write needs an explicit answer for staleness.
- More moving parts: an outbox, a relay, a broker, several projectors and several stores, each needing monitoring, on-call runbooks and capacity planning.
- Changing an event schema now affects every projector. You need versioned event types and a compatibility policy.
- Debugging spans two models. A wrong total might come from a write bug, a lost event or a projection bug, and you need tooling to tell which.
- For a service with modest, similar read and write loads it is pure overhead. A few indexes or a cache would be cheaper.
Trade-offs
Decisions you'll have to make, each with its price.
Asynchronous projections via outbox and Kafka, rather than updating read tables in the command transaction
You gainCommand latency and availability no longer depend on read stores. Ledgerly's submit p99 went back to about 150 ms at close because the transaction touches only the claims DB.
You payReads trail writes. Normally that is under a second, but at close the spend projector peaked at 4 s behind, so every after-write screen needs an explicit staleness strategy.
12 partitions keyed by claim_id
You gainPer-claim ordering, plus up to 12 parallel consumers per projector. That is enough for 220 events/s with room to spare.
You payParallelism is capped at 12 consumers per group. Raising the partition count later reshuffles keys, so in-flight claims can be processed out of order during the change unless you drain first.
Three specialized read stores (Postgres totals, Redis inbox, OpenSearch) instead of one read replica
You gainEach query becomes a cheap lookup in the right engine. The dashboard went from about 800 ms to under 10 ms.
You payThree more systems to operate and back up, three projectors to keep in sync with event schemas, and three places a bug can show stale or wrong data.
min_version wait of up to 1.5 s on the Query API
You gainUsers who just acted see their change in nearly all cases without the whole system being strongly consistent.
You payEach waiting request holds a Query API worker. During a lag spike, waits can pile up, so the limit must stay well below the client timeout and be capped per instance.
Domain events through an outbox rather than change data capture
You gainEvents carry intent (ClaimApproved by whom, under which policy) and a stable contract independent of table layout.
You payEvery command handler must remember to write the outbox row. A missed insert silently starves projections, so you need a test per command that asserts the event.
How it fails
What goes wrong in production and how to prevent it.
Projector lag grows during month-end close and dashboards show totals several minutes old
What to doAlert on lag in seconds per projector at 5 s, not on queue depth. Size consumers to the partition count ahead of close. Keep projector writes batched (for example 200 events per read-DB transaction). Show an as-of timestamp on dashboards so finance knows what they are looking at.
A poison event (bad payload, unexpected state) makes a projector throw on every retry and blocks its whole partition
What to doRetry 5 times with backoff, then park the event and every later event for the same claim_id in a parked_events table. Keep consuming other keys and page the owner. Skipping only the bad event would break per-claim ordering and corrupt totals.
Relay crashes after publishing but before marking rows sent, so events are delivered twice
What to doExpected under at-least-once delivery. The per-claim version check in each projector turns duplicates into no-ops, and the version is stored in the same transaction as the view change, so a crash mid-apply cannot half-count an event.
A projection bug double-counts approved amounts and finance reconciles against wrong numbers
What to doRun a nightly reconciliation job that recomputes a sample of team-month totals from the write DB and compares them with the read model. On mismatch, rebuild the projection into a new table from retained events and swap it in. Keep event retention (14 days here) longer than your detection window.
An event schema change (renaming amountCents) breaks older projectors after deploy
What to doTreat events as a public contract: add fields, never rename or remove them in place. Introduce a new event version with an upcaster in consumers, and deploy consumers before producers. A schema registry with backward-compatibility checks can block an incompatible producer deploy.
In a system design interview
When to bring it up and how to explain it.
Bring CQRS up when the prompt has heavy or oddly shaped reads next to writes with real rules: dashboards, feeds, search, inboxes, cross-service views. It fits best when the interviewer has told you reads dwarf writes or that some views can lag. Do not open with it for a simple CRUD service. Mention replicas and caching first and explain why they fall short.
What you could say
I'd separate the write path from the read path. Commands like submit and approve go to a claims service that owns a normalized Postgres model. It enforces the state machine and policy limits, and bumps a version on each claim. In the same transaction it writes an event to an outbox table, so we never publish a change that rolled back. A relay pushes those events to Kafka, partitioned by claim id so each claim's events stay ordered. Then I'd have one projector per read model: a flat team-month totals table for dashboards, a Redis inbox per approver, and a search index. Each projector stores the last version it applied per claim, so duplicates are no-ops and gaps stop it instead of producing wrong numbers. The cost is eventual consistency, so I'd set a lag target, say p99 under two seconds, alert on it, and handle read-your-own-writes by returning the version from the command and letting the client wait briefly or render optimistically. The payoff is that month-end dashboard load can't touch the database that accepts claims.
Likely follow-ups
Why not just add read replicas and some indexes?
I would try that first. It fails here for two reasons. The replica has the same normalized schema, so the six-way join is still slow, and indexes added for dashboards slow every insert on the primary. Replica lag also spiked to tens of seconds under write bursts, which is the same staleness problem without the benefit of query-shaped data.
How do you handle the user who approves a claim and immediately reloads their inbox?
The approve response returns the claim's new version. The inbox call passes it as min_version. The Query API waits up to 1.5 s, polling the projector's stored version, then returns either the fresh view or the old one flagged as stale. The UI can also just remove the item locally, since it knows what it did.
How would you add a new read model six months from now?
Write the projector, start a new consumer group from the earliest retained offset if retention covers the full history, or seed it from a consistent snapshot of the write DB and then consume events after the snapshot's position. Validate it against the source, then point the Query API at it. The write side doesn't change at all.
What breaks if two events for the same claim land in different partitions?
Ordering is lost, so an approval could be applied before the submission. The version check would catch it as a gap and halt rather than corrupt totals, but you'd be stuck. That's why the partition key must be the aggregate id and why repartitioning needs a drain-and-switch plan.
Relations with other guides
Patterns it's often confused or combined with.
- Transactional Outbox: Commit State and Events Together
The outbox is how the write side publishes events without dual-write bugs: the event row commits atomically with the state change, so projections never see a change that rolled back or miss one that committed.
- Event Sourcing: Store What Happened, Derive What Is
Often paired with CQRS but separate from it. With event sourcing the event log is the write model itself. Ledgerly keeps state tables as the source of truth and uses events only to feed projections.
- Change Data Capture: Stream Database Changes from the Log
An alternative to the outbox for feeding projections: tail the write DB's replication log. It needs no application changes, but you get row diffs instead of intent-carrying domain events.
- Read Replicas: Scaling Reads Without Serving Stale Writes
The simpler step to try first. Replicas offload reads but keep the same schema, so they do not help when the query shape itself is the problem, as Ledgerly found.
- Idempotency Keys: Making Retried Writes Safe
Projectors must be idempotent under at-least-once delivery. The per-entity version check is an idempotency key derived from the event itself.
- Competing Consumers: Many Workers, One Queue, No Duplicates
Each projector scales by adding consumers within its group, up to the partition count. Ordering per claim is preserved because a partition has exactly one active consumer.
Common questions
Short answers to the usual doubts.
Is CQRS the same thing as event sourcing?
No. CQRS only says the write and read models are separate. The write model can be ordinary tables, as at Ledgerly, with events emitted through an outbox. Event sourcing makes the event log itself the write model's storage. The two combine well because an event log is a natural feed for projections, but either works without the other.
Do I need separate databases for reads and writes?
Not necessarily. The minimal form is separate code paths and separate tables in the same database, for example a projection table updated in the command's own transaction. You move the read models to separate stores when read load or query shape needs it. For Ledgerly that was the point: dashboard reads had to stop competing for the claims database's connections.
How do I rebuild a projection after fixing a bug in it?
Build a new version alongside the old one: a new table or index name and a new consumer group starting from the earliest retained offset, or from a write-DB snapshot plus events after it. Let it catch up, compare a sample of rows against the old one, then switch the Query API to it with an alias or config flag and drop the old one. Never rewrite the live projection in place.
What does the user see right after submitting a claim?
The command response includes the claim id and its new version. The client shows the claim optimistically from what it just sent. If it needs server data, it calls the Query API with min_version. The Query API waits up to 1.5 s for the projection to reach that version and otherwise returns the last known view, flagged as stale so the UI can show a pending indicator.
Why version per claim instead of a global offset?
Kafka offsets are per partition and change if you repartition or replay from another source. A version number on the aggregate is assigned by the write model, travels with the event, and lets any projector detect duplicates and gaps for that entity no matter how events were delivered.
Now, practise it
Put it to work straight away.
Tests, exercises and problems that use what you've just read.
- Analytics without killing the live databaseSolve the exercise