CQRS: Separate the Read Model From the Write Model, in One Database First and With Events Second
A ticket dashboard sweeps the same table the agents write to. Split commands from queries, keep a board table in the same commit, then feed it from events with a projector: 9 events projected, a lag of 2, and a replay of 11 events that rebuilds the board exactly.
What you will learn
- Tell a command from a query and explain command query separation
- Split the read model from the write model inside one database with zero lag
- Build a read side from events with a projector and a checkpoint, and measure the lag
- Know what event sourcing adds and when CQRS is not worth it
Before you start
- Basic SQL
- Entities, Value Objects and Aggregates
CQRS stands for command query responsibility segregation. Behind the long name is a simple idea: the code that changes your data and the code that reads your data stop sharing one model. We'll take it in two steps, first a split inside one database, then a read side fed by events.
One model, two masters
Our example is a support-ticket app with an AI assistant. Agents like Ana and Ben open, assign and close tickets. Those writes all land in one tickets table.
Now look at who reads. The team dashboard wants tickets by status, the load on each agent, and which tickets are close to missing their deadline. The AI assistant asks what's on Ben's plate before it drafts a reply. Search wants its own view too. Every one of those reads goes to the table the writes are using.
The dashboard query groups every ticket by status and counts tickets per agent, so it sweeps across the whole table. At the same moment Ana closes ticket T1, and on a busy morning her write waits its turn. There's a quieter problem as well: the write side wants a model that protects the rules, and the screens want a model shaped like the screen. One model pulled two ways ends up serving neither well.
Command vs query
- A command changes state. "Close T1" comes in, the rules check it, the status goes from open to closed, and the answer is just
ok. Send "close T1" again and the answer isrejected: T1 already closed. A command can say no; that's its job. - A query answers. Ask for the board, get the counts back. Nothing changed.
Never both in one call. That rule is older than CQRS and is called command query separation. CQRS takes it one level up, from methods to whole models.
Step 1: split inside one database
Keep one database. On one side sits the write model: the tickets table plus the code that guards the rules. On the other sits the read model: a board table with a count per status and a load table with a count per agent, ready to show with no grouping.
When a command runs, it updates the ticket and the board in one transaction, so they commit together. The lag is zero, and the dashboard reads two tiny tables instead of sweeping the big one. For many teams, this step is enough.
Step 2: a projection fed by events
In step two, the command no longer updates the read side. It saves an event instead, in the same transaction as the change, so the log never misses a write. A small worker called a projector builds the read side from those events, and remembers how far it got with a bookmark called the checkpoint.
The numbers in the lecture come from a small SQLite simulation. Here's the write side: each command checks its rule, then changes the ticket and emits an event inside one with db: transaction.
import sqlite3
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE tickets(id TEXT PRIMARY KEY,
status TEXT, agent TEXT);
CREATE TABLE events(pos INTEGER PRIMARY KEY,
kind TEXT, tid TEXT, agent TEXT);
CREATE TABLE board(status TEXT PRIMARY KEY,
n INTEGER);
CREATE TABLE load(agent TEXT PRIMARY KEY,
n INTEGER);
""")
checkpoint = 0
# ---------------- write side: commands + rules
def emit(kind, tid, agent=None):
db.execute("INSERT INTO events(kind,tid,agent)"
" VALUES(?,?,?)", (kind, tid, agent))
def status_of(tid):
row = db.execute("SELECT status FROM tickets"
" WHERE id=?", (tid,)).fetchone()
return row[0] if row else None
def open_ticket(tid):
with db:
db.execute("INSERT INTO tickets VALUES"
"(?, 'open', NULL)", (tid,))
emit("Opened", tid)
def assign(tid, agent):
if status_of(tid) != "open":
return f"rejected: {tid} is not open"
with db:
db.execute("UPDATE tickets SET status="
"'assigned', agent=? WHERE id=?",
(agent, tid))
emit("Assigned", tid, agent)
return "ok"
def close(tid):
if status_of(tid) == "closed":
return f"rejected: {tid} already closed"
agent = db.execute("SELECT agent FROM tickets"
" WHERE id=?", (tid,)).fetchone()[0]
with db:
db.execute("UPDATE tickets SET status="
"'closed' WHERE id=?", (tid,))
emit("Closed", tid, agent)
return "ok"
And the read side. There are only three kinds of event, and each one moves a few counters:
# ---------------- read side: projector + queries
def bump(table, key, d):
db.execute(f"INSERT INTO {table} VALUES(?,?)"
f" ON CONFLICT DO UPDATE SET n=n+?",
(key, d, d))
def apply(kind, agent):
if kind == "Opened":
bump("board", "open", 1)
elif kind == "Assigned":
bump("board", "open", -1)
bump("board", "assigned", 1)
bump("load", agent, 1)
elif kind == "Closed":
bump("board", "assigned", -1)
bump("board", "closed", 1)
bump("load", agent, -1)
def project():
global checkpoint
rows = db.execute("SELECT pos,kind,agent FROM"
" events WHERE pos>? ORDER BY pos",
(checkpoint,)).fetchall()
with db:
for pos, kind, agent in rows:
apply(kind, agent)
checkpoint = pos
return len(rows)
def lag():
last = db.execute("SELECT MAX(pos) FROM events"
).fetchone()[0]
return last - checkpoint
The file also has three small queries: board() and load() read the read-model tables, and truth() groups the tickets table by status so we can compare.
That's the whole read model: the sum of the events. You can always build it again from the log.
The write side guards the rules
for t in ["T1", "T2", "T3", "T4", "T5"]:
open_ticket(t)
print("assign T1 Ana:", assign("T1", "Ana"))
print("assign T2 Ben:", assign("T2", "Ben"))
print("assign T3 Ana:", assign("T3", "Ana"))
print("close T1:", close("T1"))
print("close T1 again:", close("T1"))
print("events stored:", lag())
print("projected:", project())
print("board:", board())
print("load:", load())
assign T1 Ana: ok
assign T2 Ben: ok
assign T3 Ana: ok
close T1: ok
close T1 again: rejected: T1 already closed
events stored: 9
projected: 9
board: {'open': 2, 'assigned': 2, 'closed': 1}
load: {'Ana': 1, 'Ben': 1}
Five opens, three assigns and one close make nine events. The second close is rejected by the rule check, so no event is saved and the count stays at nine. Only what really happened goes into the log. The projector then reads all nine, the board rolls to two open, two assigned and one closed, and the checkpoint sits at nine.
The lag
That's the price of step two. Ana opens T6 and Ben takes T4. Two new events join the log, but the projector hasn't run yet.
open_ticket("T6")
print("assign T4 Ben:", assign("T4", "Ben"))
print("write side:", truth())
print("read side :", board())
print("lag (events behind):", lag())
print("projected:", project())
print("read side :", board())
print("load:", load())
print("lag (events behind):", lag())
assign T4 Ben: ok
write side: {'assigned': 3, 'closed': 1, 'open': 2}
read side : {'open': 2, 'assigned': 2, 'closed': 1}
lag (events behind): 2
projected: 2
read side : {'open': 2, 'assigned': 3, 'closed': 1}
load: {'Ana': 1, 'Ben': 2}
lag (events behind): 0
The write side says three assigned; the read side still says two, and Ben's load card would say one while he really has two. The gap has a size: two events behind. Then the projector runs and the lag rolls back to zero. This is eventual consistency: behind for a moment, then correct again.
Handling the lag
- Read your own write. When Ana assigns a ticket, show her the command's own answer, not the board, so her change never seems to vanish.
- Show freshness. Stamp the dashboard with the last event it has seen, like "as of event 9".
- Measure the lag as events behind, and alert when it grows.
- Decisions read the write side. "Can I close T1?" is never answered by the board; the command checks the rule itself.
The same goes for the AI assistant. It can read the board to summarise Ben's day. When it wants to act, it sends a command and the rules decide.
Event sourcing
One step further, the log itself becomes the source of truth. To show it, wipe the read side and replay:
# event sourcing: rebuild from the log alone
db.execute("DELETE FROM board")
db.execute("DELETE FROM load")
checkpoint = 0
print("replayed:", project())
print("rebuilt board:", board())
print("same as tickets:", board() == truth())
hist = db.execute("SELECT kind,agent FROM events"
" WHERE tid='T1' ORDER BY pos")
print("T1 history:", hist.fetchall())
replayed: 11
rebuilt board: {'open': 2, 'assigned': 3, 'closed': 1}
same as tickets: True
T1 history: [('Opened', None), ('Assigned', 'Ana'), ('Closed', 'Ana')]
Eleven events go through the projector, and the board comes back matching the tickets table exactly. You also get the full story of every ticket for free.
The cost is real, though. Events are kept forever, so every change to their shape needs a plan. Replays get slower as the log grows, so you add snapshots. A wrong event can't just be edited away. It's a strong tool, and the wrong default.
When CQRS pays
It pays when reads and writes really differ, in shape or in load: many screens, a search index, an AI assistant reading summaries all day. It doesn't pay for plain forms over a table, where you save a record and show the same record back. And it always costs something: two models, a projector to run and watch, and a lag to explain to users. Even its strongest supporters warn that for most systems it adds risky complexity.
| Rung | What you get | Lag |
|---|---|---|
| 1. One model | Simple; reads and writes share a table | None |
| 2. Split in one database | Read tables updated in the same commit | None |
| 3. Projection fed by events | Read side built by a projector at a checkpoint | Events behind |
| 4. Event sourcing | The log is the truth; replay and full history | Events behind |
Most systems stop at rung 2. Climb only when the step below really hurts.
Recap
- A command changes state through the model that guards the rules; a query reads a model built for the screen.
- Start with the split inside one database: one commit, no lag.
- When reads and writes pull apart, feed the read side from events and plan for the lag.
- Event sourcing goes one step further and is not the default.
Interview version, in one breath: commands go through the rules, queries read a view built for them, start in one database, and add an event-fed projection only when it pays.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
When the main model goes down, the backup has to be allowed to take the data, able to read the whole request and tested before the bad day. A simulated four-model chain for an EU customer: a 6,000-token request lands on mid-eu, flagged degraded; a 10,000-token request is served by nobody, on purpose.
Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
A bulk upload buries the chat. In a small simulation, one shared queue grows to 199 waiting and the middle chat answer takes 80.2 s. A bound plus a chat lane brings it to 0.35 s while 178 bulk jobs are told to retry in 10 s, and cancelling abandoned calls saves 21,000 wasted tokens.
Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
Six GPU replicas, two at 95% and four at 30%: round robin counts requests, and requests aren't equal. In a small simulation, least outstanding requests cuts p95 from 6.52 s to 3.05 s, prefix affinity lifts cache hits to 95% but pushes p95 to 11.45 s, a real health check takes errors from 48 to 2, and draining cuts 0 answers instead of 4.
A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
A queue doesn't lose a document, but it can hand one out twice. In a small simulation, a worker crash makes document two go from 3 to 6 chunks and the index holds 11 when the documents hold 8. An idempotent consumer brings it back to 8 with the same two deliveries, and a limit of three tries moves a poison file to a dead letter queue.
