Event sourcing

Queues, Kafka and event-driven systems Senior Python 3.13+ PostgreSQL 17+ Reviewed By Best Latest Apps

Predict the output

Replay the account's events. What's the balance?

Python 3.13
events = [("opened", 0), ("deposited", 100), ("withdrew", 30),
          ("deposited", 5)]
balance = 0
for kind, amount in events:
    if kind == "deposited":
        balance += amount
    elif kind == "withdrew":
        balance -= amount
print(balance)

Options
Hint 1 of 1

Fold every event in order.

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A 75

Correct. 0 + 100 − 30 + 5.

In event sourcing, current state is a fold over the history: start at 0 and apply each event in order. 100 in, 30 out and 5 in gives 75.

Why not the others?
  • B 105. The withdrawal subtracts 30.
  • C 5. State is the sum of all events, not the last one.
  • D 135. Withdrawals subtract.

30-second answer

Instead of storing the current state, you store every change as an immutable event (AccountOpened, MoneyDeposited) and derive state by replaying them. You get a complete audit trail, the ability to rebuild read models or answer 'what was the balance on 1 March', and natural integration events. The costs: queries need projections, replaying long streams needs snapshots, and changing event formats needs careful versioning because history is never rewritten.

Practise saying it · 35 s. No recording, just a timer

Explain event sourcing.

Say your answer out loud, then check which of these points you covered:

  • Store events, derive state
  • Audit and time travel
  • Projections for queries
  • Snapshots
  • Versioning, no rewrites

Deep dive

Optimistic concurrency per stream: append only if the stream's version is what you read.

Snapshots every N events keep load times bounded.

Events are facts in the past tense; validate commands before emitting them.

Deleting personal data (GDPR) needs a plan, such as crypto-shredding per-user keys.

Common mistakes

  • Event sourcing a simple CRUD app.
  • Editing stored events to fix bugs.
  • Exposing internal events directly as public integration events.

Senior take & follow-ups

Define it, list the benefits, then projections, snapshots and versioning costs.

Follow-up questions

Think of your answer first, then open the hint.

  1. How do you fix a wrong event?

    Show hint

    Append a compensating event.

  2. Event sourcing vs CQRS?

    Show hint

    Often together, but separate ideas.

Suggest a fix if something here is wrong or out of date.