CQRS and event sourcing in system design interviews
CQRS (command query responsibility segregation) splits a system's write model, which validates and applies changes, from its read models, which are shaped for queries and updated from the writes. Event sourcing stores every change as an immutable event and derives current state by replaying them. They are separate patterns that are often used together: the event log is the write side, and projections built from it are the read side.
By Evin JohnPublished 6 min read
1. What the two patterns are
CQRS. A command changes state ("place order"); a query reads it ("show my last ten orders"). In a classic design both go through one model and one schema, which forces compromises: the schema that keeps writes correct is rarely the one that makes a dashboard fast. CQRS gives each its own model. Commands go to a write model that enforces the rules; changes are then copied into one or more read models built for specific screens or searches.
Event sourcing. Instead of storing the current balance or the current cart and overwriting it, you store the facts that happened: ItemAdded, ItemRemoved, CheckedOut. Current state is a fold over those events. The event log is append-only and is the source of truth; any other table is derived from it and can be rebuilt.
2. Why interviewers ask about it
These patterns come up when a design has a heavy audit need (payments, ledgers, orders), very different read and write shapes (a feed, a dashboard, a search box over the same data), or a stream of events already flowing through a log. Interviewers want to hear that you know what each pattern costs, especially eventual consistency on the read side, and that you would not apply them to a simple settings page.
3. How event sourcing works
- LoadRead the events for one entity (an aggregate, such as one cart) and apply them in order to get its current state and version.
- DecideRun the command against that state: is the cart still open, is the item in stock? Reject it or produce new events.
- AppendAppend the new events only if the stream's version is still the one you loaded. If another writer got there first, reload and retry. This is optimistic concurrency on a single stream.
- PublishProjections read the new events and update read models: an order list, a search index, a revenue report.
from dataclasses import dataclass, field
@dataclass
class Cart: # state is derived, never stored directly
version: int = 0
items: dict = field(default_factory=dict)
checked_out: bool = False
def apply(cart, event):
kind, data = event["type"], event["data"]
if kind == "ItemAdded":
cart.items[data["sku"]] = cart.items.get(data["sku"], 0) + data["qty"]
elif kind == "ItemRemoved":
cart.items.pop(data["sku"], None)
elif kind == "CheckedOut":
cart.checked_out = True
cart.version += 1
return cart
def load(events, snapshot=None):
cart = Cart(snapshot.version, dict(snapshot.items), snapshot.checked_out) if snapshot else Cart()
for e in events[cart.version:]: # replay only what the snapshot lacks
apply(cart, e)
return cart
def add_item(events, sku, qty, expected_version):
cart = load(events)
if cart.version != expected_version: # optimistic concurrency on the stream
raise RuntimeError("conflict: reload and retry")
if cart.checked_out:
raise ValueError("cart already checked out")
events.append({"type": "ItemAdded", "data": {"sku": sku, "qty": qty}})- Snapshots. An entity with 50,000 events is slow to load. Save its state every few hundred events and replay only the events after the snapshot; snapshots are a cache and can be thrown away.
- Projections must be idempotent. A projection records the last event position it applied and skips anything at or below it, so redelivery after a crash does not double count.
- Rebuilds. A new read model, or a fixed bug in an old one, is built by replaying the log from the start into a fresh table, then switching reads to it.
4. Read models and eventual consistency
Projections run after the write commits, so a read model can be behind by milliseconds or, under load, by seconds. A user who adds an item and immediately opens a list built from a projection may not see it. Ways to handle that:
- Return the new state from the command itself and render it, rather than re-reading the projection.
- Pass the event position back to the client; the read API waits briefly until the projection reaches it (read-your-writes for that user).
- Read the write model directly for the one screen that needs it, and use projections everywhere else.
- Say in the product what may lag (search results, reports) and keep balances and limits on the write side.
This is the trade described in consistency and CAP: read models favour speed and availability and accept a delay.
5. Hard parts people underestimate
| Problem | Why it is hard | Usual answer |
|---|---|---|
| Event schema changes | Old events are immutable but code changes | Version events; upcast old versions to the new shape when reading; never repurpose a field |
| Deleting personal data | An append-only log resists deletion | Keep personal data out of events or in a separate store; some teams encrypt it per person and delete the key. Check your legal requirements |
| Queries across entities | The log is organised per entity | Build a projection for each cross-entity question |
| Publishing reliably | Writing state and publishing an event can disagree | With event sourcing the event store is the outbox; without it, use a transactional outbox table |
| Debugging | State is computed, not stored | Tools to replay an entity's stream and show state at each step |
6. When to use them, and when not
| Situation | CQRS | Event sourcing |
|---|---|---|
| Simple CRUD admin screens | No | No |
| Reads far outnumber writes and need different shapes (search, feeds, dashboards) | Yes | Optional |
| Full audit history is a requirement (ledgers, orders, compliance) | Often | Strong fit |
| Need to answer new questions about the past later | Helps | Strong fit: replay into a new projection |
| Strong consistency on every read across many entities | Hard | Hard |
7. How it shows up in common prompts
| Prompt | Write side | Read side |
|---|---|---|
| Payment system | Ledger entries as immutable events | Balances and reports as projections |
| Stock exchange | The sequenced input log, replayed to rebuild order books | Market data and trade reports from the output log |
| Ad click aggregator | Raw click events kept in a log | Per-minute counts, rebuilt by replay after a bug |
| Collaborative editor | A log of edit operations | The current document, with snapshots |
| Hotel reservation | Reservations and inventory in one database | Availability cache updated from booking events: CQRS without event sourcing |
8. Interview questions on CQRS and event sourcing
| Question | A strong answer covers |
|---|---|
| Are CQRS and event sourcing the same thing? | No; each works alone, and they combine naturally |
| How do you get current state in an event-sourced system? | Replay the entity's events, with snapshots to bound the cost |
| How do two concurrent commands on one entity not conflict? | Expected-version check on append, reload and retry |
| A user does not see their change in a list. Why? | The projection lags; how you would hide or bound it |
| How do you change an event's structure? | Versioned events and upcasting on read |
| How do you handle a request to delete a person's data? | Personal data outside the log, or per-person keys that can be deleted |
| When would you not use event sourcing? | Simple CRUD, no audit need, a team without experience in it |
9. Mistakes to avoid
- Treating the two patterns as one. Say which one you are proposing.
- Ignoring projection lag. Name the screen that might show stale data and what you do about it.
- Events that describe database rows (
CartRowUpdated) instead of business facts (ItemAdded). - No versioning plan. Events outlive the code that wrote them.
- Using it everywhere. Apply it to the part of the system that needs history, not the whole product.
10. How to talk about it in the interview
Fictional example
- Interviewer
- Why not just keep an orders table and update the status column?
- Candidate
- For most services I would. Here support and finance need to know exactly when each change happened and who made it, and we keep adding reports. So I would store order events, rebuild an order's state by replaying them with periodic snapshots, and project them into an order list table and a search index.
- Interviewer
- A customer cancels and the list still says confirmed.
- Candidate
- The projection is a second behind. The cancel call returns the new state and the app shows it straight away. Anything that decides money, such as whether a refund is allowed, reads the event stream, not the projection.
Practicing with Natively
These patterns are easy to name and hard to defend, so rehearse the follow-ups on lag, versioning and deletion out loud. Natively transcribes a practice call as it happens, can propose a talking point when you are asked when not to use event sourcing, and can draw the command, log and projection flow as a diagram. The transcript afterwards shows whether you kept the two patterns apart.
Questions people ask
What is CQRS?
Command query responsibility segregation splits the model that validates and applies changes from the models used to read data. Writes go to a write model; changes are copied into read models shaped for particular screens or searches, which usually lag slightly.
What is event sourcing?
Storing every change as an immutable event, such as ItemAdded or CheckedOut, instead of overwriting current state. Current state is rebuilt by replaying an entity's events, with snapshots to keep that fast, and other views are projections built from the log.
Do you need event sourcing to use CQRS?
No. Many systems use CQRS with an ordinary database on the write side and denormalised tables or a search index for reads. Event sourcing pairs well with CQRS but each pattern works on its own.
What are the downsides of event sourcing?
Read models are eventually consistent, event schemas need versioning because old events never change, deleting personal data from an append-only log needs a plan, and queries across entities require projections. For simple CRUD it adds cost without benefit.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
