Stage 5 · Architecture patterns · Hard · 22 min

CQRS and event sourcing

Event sourcing stores every change as an event that is never edited. CQRS builds separate read views from those events. Learn replay, snapshots and lag.

What each interview level is expected to know

Learn first: Event-driven fan-out: push vs pull

After this lesson you can:

  • Store every change as an event, and rebuild state by replaying them.
  • Build read views from events, and explain why they can lag behind.
  • Use snapshots, and handle old events in a new shape.

Start here

See it in 60 seconds

A log of events, not a balance

Event sourcing stores every change as an event and never edits it; CQRS builds separate read views from those events for fast queries.

Scene 1 of 7 · A command arrives

The app sends a command, deposit 100, to the write side, which checks the rules first.

AppAppWrite sideWrite sideEvent logEvent logProjectorProjectorRead viewRead view
  • App — healthy
  • Write side — healthy
  • Event log — healthy
  • Projector — healthy
  • Read view — healthy
Balance, replayed from the events
not shown yet
  1. A command arrives. The app sends a command, deposit 100, to the write side, which checks the rules first.
  2. Append an event. It appends an event, Deposited 100, to the event log; nothing is ever changed in place.
  3. Never erase. A withdrawal adds a second event, Withdrew 30, instead of overwriting a stored balance.
  4. Replay for the balance. The balance is the events added up, + 100 − 30 = 70, and the full history stays.
  5. A separate read view. CQRS splits reading from writing: a projector turns each event into a read view that answers queries fast.
  6. Views can lag. A new deposit is stored, but the read view still says 70 until the projector catches up.
  7. It catches up. A moment later the projector applies the new event, and the read view says 170 too.
  8. Now you try. Tap commands in order, and see which events are stored and the balance they add up to. For example, tapping Deposit 100, Withdraw 500 and Withdraw 30 gives this: 2 events stored, 1 refused; replaying them gives a balance of 70. The write side refused withdraw 500, since the balance would go below 0, so no event was stored.

Scene 1 of 7: A command arrives. The app sends a command, deposit 100, to the write side, which checks the rules first.

Key points

  1. The write side checks each command against the rules before anything is stored.
  2. Accepted changes are appended as events; nothing is ever updated or deleted in place.
  3. The current state is the events replayed; long logs keep snapshots, so replay can start part-way.
  4. CQRS keeps separate read views, updated from the events, which can lag a moment behind.

Go deeper in the CQRS & event sourcing lab →

In plain words

Say a bank account starts empty, and the app asks to deposit 100. This request is called a command. The write side checks the rules and adds an event to a log: Deposited 100. Taking out 30 later adds another event, Withdrew 30. Nothing is overwritten. To get the balance, add up the log: 100 − 30 = 70. Storing changes this way is called event sourcing. Adding up a long log on every read would be slow. So a worker keeps a separate read view up to date from the events. Splitting writes from reads like this is called .

Two details keep it practical. Adding up a very long log is slow. So the system saves a snapshot now and then, such as a balance of 70 after event 2. A rebuild then starts from the latest snapshot. The read view also trails the log by a short delay, so a user may not see a deposit on the very next screen.

The problem it solves

One table shaped for writing is rarely shaped well for reading. Checking a withdrawal needs one account's balance. A search page, a monthly report and a dashboard each need the same data arranged another way. When they all share one model, heavy read queries slow the writes down. And when someone asks what happened last month, the old values are gone.

Why it matters

A normal table keeps only the latest value: when a balance changes from 100 to 70, the 100 is gone. Some systems need the whole story: money, orders, anything an auditor may ask about. Event sourcing keeps every change. CQRS, short for Command Query Responsibility Segregation, then answers how to read that data fast.

A worked example

Rebuilding an account from scratch means replaying every past record. If there are 60,000 records and replaying one takes 0.1 ms, that is 60,000 × 0.1 = 6,000 ms, or 6 seconds. A snapshot saved 500 records back cuts that to replaying only those last 500 records. That is 500 × 0.1 = 50 ms, 120 times faster.

Think of it like…

Think of a fitness app that logs every walk as a new entry and never edits an old one. A screen for today's total is kept ready from those entries.

Where this analogy stops working

A log of changes plus a ready-made view is the useful part. But in the app, the log and the total sit together and change together. In CQRS the view is a separate store that a worker updates afterwards. So a read can miss a change made a moment ago.

Try it

See it working

Guided walkthroughOpen the full lab →

CQRS & event sourcing

Send commands that add events to a log, and watch a read view built from those events. Move the slider to rebuild the balance as it was after any earlier event.

Step through one command

The bank account acct:42 has 3 events that add up to $100. Pick a command and when the app reads the balance, then press Next step. Back takes you to the step before.

The command
The app reads the balance view

On: the view is thrown away and built again by replaying every event.

With these settings: The withdrawal became event 4, and the account is now $70. The read at 50 ms showed $100, an old balance, because the view caught up only at 200 ms.

replayBank app, acct:42Bank appacct:42Write side, checks rules, NOWWrite sidechecks rulescheckingNOWEvent store, only addsEvent storeonly addsBalance view, read sideBalance viewread sideProjector, builds viewsProjectorbuilds viewsBroker, eventsBrokerevents
  • Bank app — acct:42 — healthy
  • Write side — checks rules — healthy — NOW — checking
  • Event store — only adds — healthy
  • Balance view — read side — healthy
  • Projector — builds views — healthy
  • Broker — events — healthy
  • Command
  • Read
  • New event or view update
  • Published event
Step 1 of 7

Step 1 of 7 · Write side

Done: The app sends a command

What happens
The command asks to take $30 from acct:42.
Why
A command is a request to change something, so it can still be refused.
What changes
The write side starts to check it.
Next
The write side loads the account's events

Event log

6 more to go. Press a line to go back to that step.

Events in the store
3
Write side
$100
Balance view
$100
matches
The app read
not yet

Step 1 of 7: Write side. The app sends a command. The command asks to take $30 from acct:42.

What this simplifies. This run follows one account, with whole events and a stated 200 ms lag. A real projector's lag depends on the broker and the load. A real replay of millions of events takes a long time, which is one reason teams keep snapshots.

Try it yourself

The same account, acct:42, starting at $100. Send commands in any order, then move the slider to see the balance after any earlier event, or rebuild the view from every event.

Materialized Balance
$100
Account Owner: Alice
Total Stored Events
3 immutable events
Append-only, never updated
Applied Read Version
v3 / v3
Projection sync status

Write Model: Immutable Event Store

APPEND-ONLY LOG
v1 · ACCOUNT_OPENED10:00:00 AM
Payload: {"accountId":"acct:42","initialBalance":80,"owner":"Alice"}
v2 · MONEY_DEPOSITED10:05:00 AM
Payload: {"accountId":"acct:42","amount":50}
v3 · MONEY_WITHDRAWN10:10:00 AM
Payload: {"accountId":"acct:42","amount":30}
Dispatch Domain Commands:

Read Model: Materialized View

OPTIMIZED FOR READS
Account ID:acct:42
Account Owner:Alice
Current Balance:$100
Snapshot Version:v3
Time Travel State Slider:Version 3

CQRS & Event Sourcing Audit Log

[5:35:57 AM]CQRS & Event Sourcing Engine initialized. Read model projected up to Version 3 ($100).

Mechanics

How it works

The pictures follow one bank account, acct:42. Its first 3 events add up to a balance of $100.

  1. Write side: commands

    Pick a case to follow below

    With this case: The command passed its check, so event 4, Withdrawn $30, was saved and published. The account is now $70.

    Bank app, acct:42Bank appacct:42Write side, checks rules, NOWWrite sidechecks rulescheckingNOWEvent store, only addsEvent storeonly addsBalance view, read sideBalance viewread sideProjector, builds viewsProjectorbuilds viewsBroker, eventsBrokerevents
    • Bank app — acct:42 — healthy
    • Write side — checks rules — healthy — NOW — checking
    • Event store — only adds — healthy
    • Balance view — read side — healthy
    • Projector — builds views — healthy
    • Broker — events — healthy
    • Command
    • Read
    • New event
    • Published event
    Step 1 of 4

    Step 1 of 4 · Write side

    Done: The app sends a command

    What happens
    The command asks to take $30 from acct:42.
    Why
    A command is a request to change something, so it can still be refused.
    What changes
    The write side starts to check it.
    Next
    The write side loads the account's events
    Events stored
    3
    Balance from the events
    $100

    Step 1 of 4: Write side. The app sends a command. The command asks to take $30 from acct:42.

    A command is a request to change something, such as "withdraw $30 from acct:42". The write side loads the account's events, adds them up and checks the rules. If the command passes, it saves an event that says what happened: Withdrawn $30. Events are only ever added, never edited. That list of events is the event store.

    In the picture, withdrawing $30 passes the check and becomes event 4, so the account is now $70. Withdrawing $500 breaks the rule, so nothing is saved.

  2. Publish the events

    Each new event is published to a message such as . Any service that cares can subscribe.

  3. Read side: projections

    Pick a case to follow below

    With this case: A read at 50 ms showed $100, because the view caught up only at 200 ms.

    Bank app, acct:42Bank appacct:42Write side, checks rulesWrite sidechecks rulesEvent store, only adds, NOWEvent storeonly adds4 eventsNOWBalance view, read sideBalance viewread side$100Projector, builds viewsProjectorbuilds viewsBroker, eventsBrokerevents
    • Bank app — acct:42 — healthy
    • Write side — checks rules — healthy
    • Event store — only adds — healthy — NOW — 4 events
    • Balance view — read side — healthy — $100
    • Projector — builds views — healthy
    • Broker — events — healthy
    • New event
    • Read
    • Published event
    Step 1 of 4

    Step 1 of 4 · Event store

    Done: Event 4 is saved at 0 ms

    What happens
    The write side now works out $70.
    Why
    The write side is always up to date, because it reads the events themselves.
    What changes
    The balance view still says $100.
    Next
    The user reads the balance at 50 ms
    Write side
    $70
    Balance view
    $100
    Watch: one event behind
    The user saw
    not read yet

    Step 1 of 4: Event store. Event 4 is saved at 0 ms. The write side now works out $70.

    Workers read the events and keep read-ready views up to date. One view might be a search , another a table of each user's orders. A view built this way is called a projection. It lags the write side by a short time.

    In the picture, the projector runs 200 ms behind. A read of the balance view at 50 ms still shows $100, and a read at 300 ms shows $70. The write side was right all along; the view needed a moment to catch up.

  4. Replay

    Because every event is kept, you can rebuild any view by reading the events again from the start. This also gives a full history for audits. A new kind of view can be built from old events.

  5. Snapshots

    Pick a case to follow below

    With this case: Loading the account took 10,250 reads, and the number grows with every event.

    Bank app, acct:42Bank appacct:42Write side, checks rules, NOWWrite sidechecks rules10,250 readsNOWEvent store, only addsEvent storeonly addsBalance view, read sideBalance viewread sideProjector, builds viewsProjectorbuilds viewsBroker, eventsBrokerevents
    • Bank app — acct:42 — healthy
    • Write side — checks rules — healthy — NOW — 10,250 reads
    • Event store — only adds — healthy
    • Balance view — read side — healthy
    • Projector — builds views — healthy
    • Broker — events — healthy
    • Read
    Step 1 of 1

    Step 1 of 1 · Write side

    Watch: The write side reads every event

    What happens
    To check one new command, it reads all 10,250 events for the account.
    Why
    With no snapshot, the balance must be added up from the first event.
    What changes
    Every new command pays for the whole history.
    Next
    The run ends here.

    How it ended. Loading the account took 10,250 reads, and the number grows with every event.

    Reads to load the account
    10,250
    Watch: grows with every event

    Step 1 of 1: Write side. The write side reads every event. To check one new command, it reads all 10,250 events for the account.

    What these pictures simplify. These pictures use one account, whole events and a stated 200 ms lag. A real projector's lag depends on the broker and the load, and a real store holds many accounts.

    Replaying a long log from the start is slow. A snapshot saves the state at one point, such as the balance after event 10,000. Loading the account then means reading the snapshot and replaying only the events after it.

    In the picture, the account has 10,250 events. With no snapshot, every new command reads all 10,250. With a snapshot at event 10,000, it reads the snapshot and 250 events: 251 reads.

Use it when

  • Ledgers for banking and accounting, where an auditor must be able to see every change and when it happened.
  • Data written one way and read in several, such as orders in a list, a search page and a report. Each view gets its own shape.
  • A process with clear steps, such as an order that is placed, paid, packed and shipped. Each step is an event, and the history shows where the order stands.

Skip it when

  • A simple app that only stores and shows rows, such as a blog or an internal tool: one database model is enough.
  • A screen that must show the user's own write at once: the read view is updated a moment later, so plan for that lag.
  • Data you must be able to erase, such as personal details under a privacy law: an event log is built to keep everything. Keep such data outside the events.

Check yourself

In event sourcing, how do you find an account's current balance?

Judgement

Trade-offs and how it fails

What you give up

Auditability
Every change is kept, so you can see what happened and when, and rebuild the state as it was on any past day. The price is storage that only grows.
Consistency
A read view is updated after the write, so it can be out of date for a moment. How long depends on how fast the projector keeps up. If it falls behind, the lag grows.
Complexity
There are more moving parts: an event log, a broker, projectors and one or more read stores. And a change to the shape of an event must still let the code read years of old events.

Failure modes

  • Old events in a new shape: an event's fields change over the years, but the old events stay in the log. Code that replays them must still understand every earlier version.
  • Slow : an account with millions of events takes too long to load from event 1. Save a snapshot every so often and replay only the events after it.
  • A projector that falls behind or stops: writes still succeed, but every read view shows older and older data. Watch the gap between the newest event and the last one applied.
  • An event applied twice: the projector crashes after updating the view but before recording its position. Make each update .

In the real world

Trade-offs to be ready to discuss: Cqrs vs crud · Event sourcing vs crud state

Check yourself

What is the main cost of CQRS?

Interview

What interviewers look for

  • With event sourcing, add snapshots: "We save the state every so often, such as every 1,000 events, and replay only what came after."
  • Name the lag: "The read view is updated a moment after the write. Right after a write, the app shows the user their own change from the write result."
  • Say why you need it before you propose it: an audit trail, or reads that need a different shape from writes. With neither, use one database model.
  • Keep the two ideas apart: "Event sourcing is how I store changes. CQRS is separate models for writing and reading. Each can be used without the other."

Say it out loud: What is a snapshot in event sourcing, and why is it needed?

In a CQRS system a user places an order, then opens "My orders" at once and does not see it. What is the most likely reason?

Expected depth by interview level

Levels describe the depth interviewers probe, not years of experience. Choose a level on the learning path to highlight it.

JuniorBeyond this level
Not usually expected.
MidUseful
Separate read models for heavy queries.
SeniorExpected
Projections, eventual consistency and replay.
StaffExpected
When the complexity pays off — and when it doesn't.

Practice

Apply it

Three harder questions

The first two use the idea on a new case. The last asks you to judge a design.

Apply it

An account has 25,000 events. A snapshot was saved after event 20,000. How many events must be replayed to load it?

Apply it

An event-sourced shop wants a new view: what each customer spent in each month of the last 3 years. How is it built?

Judge a design

A team of two builds a to-do app with one table and about 50 users. Someone proposes CQRS with event sourcing. Is it a good fit?

Next: distributed transactions, how to keep several services in step when no single database transaction covers them.

Go deeper

Sources and further reading

First-hand sources to check this page against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.

  • Engineering guideCQRSMartin FowlerSeparate models for writing and reading, and a clear warning about when not to use it.
  • Engineering guideEvent SourcingMartin FowlerStoring every change as an event and rebuilding state by replaying them.
  • Engineering guideCQRS patternMicrosoft Azure Architecture CenterA worked design with a read store kept up to date from events, and its problems.