Event sourcing & CQRS

In one sentence

Event sourcing stores every change as an immutable event and derives state by replaying them; CQRS splits the write model from query-shaped read models. Great for audit and replay, costly in complexity and eventual consistency.

Analogy: A bank statement versus a balance: the balance tells you what you have; the statement tells you how you got there, and you can always recompute the balance from it.

Writes append events after replaying the stream; projectors build query-shaped read models asynchronously, which is where eventual consistency comes from.

How it works

  • Current state is a fold over each entity's event stream; snapshots every N events bound load time.
  • Fix a projection bug and replay history to rebuild it; you also get audit trails and time travel.
  • CQRS read models are projections shaped per query: a UI table, a search index, a cost dashboard.
  • The cost: projections lag, events are a public schema you version forever, and deletion fights the immutable log.
  • Use it only where history is the product, like an agent trajectory you audit, replay and mine for evals.

Check yourself

Answer to mark it learned; your answers aren't scored.

You fix a bug in a projection and rebuild it by replaying the event log. Minutes later, support reports that customers got every old order-confirmation email again. Root cause?

Go deeper

Full explanation

Event sourcing stores what happened instead of what is: every change is an immutable event (OrderPlaced, ToolCalled) appended to a per-entity stream, and current state is a fold over those events. The log is the source of truth, so you get a full audit trail, time travel (state as of any moment) and replay: fix a bug in a projection and rebuild it from history. Snapshots every N events keep load time bounded. Concurrency is optimistic: append only if the stream is still at the version you read.

CQRS (Command Query Responsibility Segregation) splits the write model, which validates commands and emits events, from one or more read models (projections) shaped for each query: a table for the UI, a search index, a cost dashboard. The two pair naturally, since events feed projections, but each works alone.

The cost is real:

  • Projections lag, so reads are eventually consistent; a user may not see their own write yet.
  • Events are a public schema you must version forever.
  • "Delete this user" fights an immutable log.

Martin Fowler's warning holds: for most systems CQRS adds risky complexity. Use it in the few places where history is the product. For AI, that includes an agent's trajectory: an event log you can audit, replay and mine for evals.

Code An agent run as an event stream (Postgres)
pythonAn agent run as an event stream (Postgres)
from dataclasses import dataclass, field
import psycopg
from psycopg.types.json import Jsonb

@dataclass
class AgentRun:                      # current state = fold(events)
    messages: list = field(default_factory=list)
    tool_calls: int = 0
    status: str = "running"

def apply(s: AgentRun, type_: str, data: dict) -> AgentRun:
    match type_:
        case "UserMessage" | "ModelResponded" | "ToolReturned":
            s.messages.append(data)    # recorded LLM output: replay never calls the model
        case "ToolCalled":
            s.tool_calls += 1
        case "RunFinished":
            s.status = "done"
    return s

def load(conn: psycopg.Connection, run_id: str) -> tuple[AgentRun, int]:
    rows = conn.execute("SELECT type, data FROM events WHERE stream_id = %s "
                        "ORDER BY version", (run_id,)).fetchall()
    state = AgentRun()
    for type_, data in rows:
        state = apply(state, type_, data)
    return state, len(rows)          # version = number of events

def append(conn, run_id: str, expected: int, events: list[tuple[str, dict]]) -> None:
    # UNIQUE (stream_id, version): a concurrent writer gets a conflict, not a fork
    with conn.transaction():
        for v, (type_, data) in enumerate(events, start=expected + 1):
            conn.execute("INSERT INTO events (stream_id, version, type, data) "
                         "VALUES (%s, %s, %s, %s)", (run_id, v, type_, Jsonb(data)))
Real example

A support agent's run is stored as events: UserMessage, ModelResponded (model id, prompt hash, output, 1,840 tokens), ToolCalled(refund, $40), HumanApproved, RunFinished. Three weeks later a customer disputes the refund; you replay the stream and see exactly which retrieved chunk and which model output led to it. The same log feeds three projections: the live chat view, a tokens-per-tenant cost dashboard, and an eval set of failed runs. Replays read the recorded model outputs, so debugging is deterministic and costs zero tokens.

Trade-offs +3 · −4

+ You gain

  • Full audit trail and time travel: you always know why state is what it is.
  • Read models are shaped per query and can be added or rebuilt later from history.
  • Writes are appends: simple, fast and a natural feed for streams and downstream systems.

− You pay

  • Eventual consistency between write and read sides; read-your-writes needs extra work.
  • Event schemas are forever: versioning, upcasting and replaying old shapes.
  • Many more moving parts, unfamiliar to most teams; projection bugs are hard to debug.
  • Right to erasure conflicts with an immutable log; needs crypto-shredding.

Use it when

Where history is the product or legally required: ledgers, orders, compliance, agent action audit trails. Or when many differently shaped read models must be served from one stream of writes.

Avoid it when

CRUD apps, most internal tools, or a whole system by default. If a table plus an audit-log table answers "how did we get here", use that.

Numbers to know 2
  • Kafka's default retention is 7 days (log.retention.hours=168): an event store needs retention set to forever.
  • Rule of thumb: snapshot a stream every ~100–1,000 events so loading never replays thousands.
Common pitfalls 4
  • A compacted Kafka topic as the event store: compaction keeps only the latest event per key and silently deletes history.
  • CRUD-shaped events (OrderUpdated with the whole row): you lose intent; name business facts.
  • Side effects in projections: a rebuild re-sends every email. Keep handlers idempotent and side effects out of replay.
  • Applying CQRS to the whole system instead of the one bounded context that needs it.
Interview questions 3

Answer out loud first, then reveal.

How would you make an agent's actions auditable and replayable?Show answer

I model each run as an event stream: user input, every model call with model id, prompt hash and output, tool calls and results, approvals. Append-only, keyed by run id, versioned for optimistic concurrency. Audit comes for free, and replay is deterministic because it reads the recorded model outputs instead of calling the LLM again: non-determinism is captured as data. Durable-execution engines like Temporal rebuild workflow state from history the same way. PII is encrypted with a per-user key, so erasure means deleting the key.

When would you NOT use event sourcing and CQRS?Show answer

Most of the time. If the domain is CRUD and nobody asks "how did we get here", the costs dominate: eventual consistency between writes and reads, permanent event schemas, rebuild tooling, and a team that has to learn all of it. I apply it to one bounded context where history is the product, like payments or an agent's action log, and keep the rest as plain tables plus an audit table or a CDC stream. CQRS alone is often enough: a read replica or materialized view is already a mild CQRS.

How do you give users read-your-writes with an async read model?Show answer

Three options, cheapest first. Return the new state in the command response so the UI renders it directly. Or return the event version, and have the query wait until the projection reaches it, with a timeout. Or serve the author's own view from the write model while everyone else reads the projection. I also expose projection lag as a metric with an alert, because a stuck projector looks exactly like data loss to users.