SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
  • Client-Server
  • Monolithic Architecture
  • Microservices
  • Serverless
  • Event-Driven Architecture
  • Peer-to-Peer (P2P)
  • Hexagonal Architecture
  • CQRS
  • Event Sourcing
  • Domain-Driven Design (DDD)
  • Layered (N-Tier) Architecture
  • Containers and Docker
  • Kubernetes Basics
  • Clean Architecture and Modular Monolith
  • Multi-Tenancy
  • Cloud Basics: Regions, Zones and Edge
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Architecture/Architectural Patterns

Event Sourcing

Store every change as an event, and rebuild the current state by replaying them.

⏱ 15 min readAdvancedInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Event Sourcing stores every change as an event in an append-only log, instead of storing only the latest state. The current state is found by replaying the events.

  • Instead of "balance = 120", you store "Deposited 100", "Withdrawn 30", "Deposited 50".
  • Events are facts in the past. They are never edited or deleted, only added.
  • You get a full history, audit trail and time travel for free.
  • Long histories are made fast with snapshots, and read views are made with projections.

02Concept: What is it?

Most systems store the current state. When something changes, the old value is overwritten. The row says the balance is 120, but not how it got there.

With Event Sourcing the events are the source of truth. Each event is a small fact named in the past tense: OrderPlaced, ItemAdded, PaymentReceived. The state is just a fold (a running total) over those events.

State storage vs event sourcing
Store the state
🗄️balance = 120old values are lost
↓UPDATE
🗄️balance = 150how did we get here?
Store the events
+100
-30
+50
+30
↓replay (add them up)
🧮balance = 150and the full story
State storage keeps the result. Event sourcing keeps the steps, and the result can be rebuilt at any time.

To change something, you send a command ("Withdraw 30"). The code loads the past events, rebuilds the current state, checks the rules, and, if all is fine, appends a new event. A command can be rejected, but an event, once stored, always happened.

🧠Mistakes are fixed by new events
You never edit an old event. If a deposit was wrong, you add a correcting event ("DepositReversed"). The history shows both, which is exactly what an auditor wants.

03Real-Life Example

🍵The Bank Passbook and the Chess Game
A bank passbook does not just say "You have 150". It lists every line: deposit, withdrawal, deposit. The balance is the total of the lines. You cannot erase a line with a pen. If there was a mistake, the bank adds a new line to correct it. In chess, the same thing: a notation sheet of every move lets you rebuild the board at any moment, replay the game, or go back to move 12 and see what happened.
Passbook
Event Sourcing
One line in the passbook
One event
The whole passbook
The event store (the log)
Adding up the lines for the balance
Replaying events to get state
No erasing, only new lines
Append-only. Fix with a new event
A summary page printed each year
A snapshot
Looking at the balance on 1 March
Time travel (replay up to a point)
A clerk's monthly summary sheets
Projections (read models)
Handling one command
✍️CommandWithdraw 30
→↓
📜Load eventsrebuild state
→↓
🧩Check rulesenough money?
→↓
➕Append eventWithdrawn 30

04Why Do We Need It?

🧾Perfect audit trail
Every change is kept with who, when and why. Great for banking, health and law.
⏪Time travel
Rebuild the state at any past moment to debug or answer 'what did we know then?'.
🐞Debug and replay
Copy production events to a test system and replay them to reproduce a bug.
🔮New views later
Need a new report? Replay old events into a new projection. The data was always there.
⚡Fast writes
Appending to a log is simple and quick. No updates in place.
📣Natural events
The events can be shared with other services, which fits event-driven systems.
Do not throw the story away and keep only the last line. Keep the story and work out the last line when you need it.

05Where Do We Use It?

🏦Finance
Ledgers, payments and trading. Every change must be traceable.
🏥Health and legal
Records that must show exactly what was known and when.
🛒Orders and carts
A cart has a story: items added, removed, coupon applied, checkout.
🧩With CQRS
Events form the write side. Projections make the read side.
📍Tracking and IoT
Location pings and device state changes are naturally events.
🕹️Collaboration
Editors and games that store actions, supporting undo and replay.
📝It is not the same as logging
An application log is for people to read, and the system does not depend on it. In Event Sourcing the events are the data. If you lose them, you lose the system's state.

06Types / Parts / How It Works

The main pieces

PieceWhat it doesExample
EventAn immutable fact in the past tense, with data and a timestampMoneyWithdrawn { account: 7, amount: 30 }
Event storeAn append-only database of events, grouped per streamEventStoreDB, Kafka (with care), a SQL table
Aggregate / streamOne thing whose events are kept together in orderAccount 7, Order 1042
CommandA request to do something. It may be rejectedWithdrawMoney
ProjectionBuilds a read view by consuming eventsAccount summary table, search index
SnapshotA saved copy of state at some event numberBalance 1,250 after event 5,000
Snapshots keep replay short
📜Events 1 to 5,000old, not needed now
→↓
📸Snapshot @5,000saved state
→↓
📜Events 5,001 to 5,012replay only these
→↓
🧮Current state
Snapshot Events replayed
Instead of replaying 5,000 events, load the snapshot at event 5,000 and replay only the few events after it.

Events vs commands

CommandEvent
TenseImperative: WithdrawMoneyPast: MoneyWithdrawn
MeaningA wish. Could be refusedA fact. Already happened
Stored?Usually notYes, forever
CountOne targetZero or more listeners
VisualizerAppend events, replay history, use snapshotsAdd deposits and withdrawals, drag the slider back in time, try a withdrawal that is too big, then turn on snapshots and watch how many events must be replayed.
Event log (append only). Faded events are after the chosen point in time.
  1. #1Deposited 100balance 100
  2. #2Withdrawn 30balance 70
  3. #3Deposited 50balance 120
Snapshots (a saved balance, so we do not replay everything)
Balance at this point
120
now
Events stored
3
never deleted
Replayed to get current balance
3
from the start
The balance is not stored anywhere. It is worked out by replaying every event from the start. Add some events, or drag the slider back in time.

Tip: keep adding deposits. Without snapshots the replay count grows with every event. With snapshots it never passes the snapshot interval.

07How to Use It / Steps / Implementation

Building an event-sourced feature

  1. 1
    Find the events
    Talk to the business and list what happens, in the past tense: OrderPlaced, ItemShipped. Use the words they use.
  2. 2
    Pick the streams
    Decide which events belong together (one account, one order). Order only matters inside a stream.
  3. 3
    Write the event store
    Append-only table or a store with a stream id, version number and event data. Use the version to detect two writers at once (optimistic concurrency).
  4. 4
    Rebuild state with a fold
    A function applies each event to the state in order. Keep it free from side effects, so replay always gives the same answer.
  5. 5
    Handle commands
    Load events, fold to state, check rules, append new events. Reject with an error if a rule fails.
  6. 6
    Add projections
    Consumers read events and keep read tables up to date. Make them idempotent and able to rebuild from the beginning.
  7. 7
    Add snapshots and versioning
    Snapshot every N events when streams get long. Plan how old events are upgraded when the shape of an event changes.
💡Name events by what happened for the business
"CustomerMoved" says more than "CustomerUpdated". Meaningful events make projections and audits much easier to write.
⚠️Personal data and deletion
Events cannot be edited, but laws such as GDPR may require erasing data. Common ways: keep personal data outside the events (referenced by id) or encrypt it per person and delete the key ("crypto-shredding").

08Key Terms to Know

TermMeaning in easy words
EventAn immutable record of something that happened, named in the past tense
Event storeAn append-only database that keeps events in order
StreamThe ordered events of one entity, such as one account
AggregateA group of objects treated as one unit that decides if a command is allowed
Replay / rehydrateApply the events in order to rebuild the state
FoldCombine a list of events into one state value
SnapshotA saved state at an event number, to skip old events
ProjectionA read view built from events
Optimistic concurrencyReject a write if the stream changed since you read it
UpcastingConverting an old event shape to the new one when reading
Compensating eventA new event that fixes an earlier mistake

09Pros, Cons and Trade-offs

✅ Pros
  • Complete history and audit by design
  • Time travel and easy bug replay
  • New read models can be built from old data
  • Fast, simple append-only writes
  • Fits event-driven systems well
⚠️ Cons
  • Harder to learn and to design well
  • Queries need projections, so reads are eventually consistent
  • Event shapes must be versioned over time
  • Deleting personal data is hard
  • Long streams need snapshots
  • Tooling and skills are less common

Trade-offs

ChoiceWe gainWe lose
Events as truthHistory, audit, replayNo simple SELECT of current state
SnapshotsFast loading of long streamsExtra storage and code, snapshots must be kept in sync with event shapes
Small, focused eventsClear meaning and simple projectionsMore event types to manage
Large 'state changed' eventsFew typesMeaning is lost, consumers are tightly coupled
Sync projectionsRead your own writesSlower writes and more coupling
Async projectionsFast writes, scalable readsLag and duplicate handling

10Common Problems and Mistakes

Common mistakes

  1. Using it for everything. Most parts of most apps do not need it. Apply it to the core where history has value.
  2. CRUD events. "RowUpdated" events carry no business meaning and give little benefit.
  3. Editing past events. This breaks trust in the log and any projection that already used it.
  4. Changing event shapes without a plan. Old events still exist forever. Use versions and upcasters.
  5. Side effects in replay. Sending an email while rebuilding state sends it again on every replay. Keep the fold pure.
  6. No snapshots. A stream with millions of events takes too long to load.
  7. Treating the broker as the store. A message bus with short retention does not give you a durable log of facts unless set up for it.

Things to watch

⚔️Concurrent writers
Two commands on one stream. Use version checks and retry.
🔁Duplicate delivery
Projections must handle the same event twice.
🧬Event evolution
Plan versions early. Upcast on read or migrate carefully.
🧹Privacy
Plan for the right to be forgotten, for example with crypto-shredding.

11Real-World Examples

🏦Ledgers
Accounting is event sourcing by nature: an append-only journal, and balances computed from it.
🗃️Version control
Git stores a history of changes, and any version can be rebuilt. The same idea.
🛢️Database internals
A database write-ahead log is an event log used to rebuild state after a crash.
🛒Order systems
Order history with exact steps for support and disputes.
📡Kafka pipelines
Logs of facts consumed by many services, each building its own view.
🧰Tools
EventStoreDB, Axon Framework, Marten (.NET), or a plain SQL events table.
📝Note
Event Sourcing is a big design choice that is hard to undo later. Try it first on one bounded part of the system.
Mini case: shopping cart
🛒ItemAdded
🛒ItemAdded
🗑️ItemRemoved
🎟️CouponApplied
→↓replay
🧮Cart now1 item, discounted
The cart state is always the result of its events, and 'abandoned carts' is just a new projection.

12Related Topics to Read Next

CQRS→

The usual partner: events on the write side, projections on the read side.

Event-Driven Architecture→

Events also tell other services what happened.

Message Queues→

Often carry events to projections and other consumers.

Delivery Semantics→

Decide how duplicates and lost messages are handled.

Idempotency→

Makes projections safe when an event arrives twice.

LSM Trees→

Another structure built on appending instead of updating in place.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: store every change as an immutable event. State = replay of events.
  • ✔Events: past tense facts (MoneyWithdrawn). Commands are requests that can fail.
  • ✔Fix mistakes: append a compensating event. Never edit history.
  • ✔Speed: snapshots for long streams, projections for reads.
  • ✔Concurrency: version number per stream (optimistic locking).
  • ✔Evolution: version events, upcast old ones, keep the fold pure.
  • ✔Costs: complexity, eventual consistency, privacy deletion is hard.
  • ✔One line: “Keep the story, and work out the current state from it.”
← Previous
CQRS
Next →
Domain-Driven Design (DDD)