📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is event sourcing? Explain storing events instead of current state, how projections and snapshots work, how you version events, and when event sourcing is worth its cost and when it is not.

Event sourcing at the architecture level: the event store and streams, rebuilding aggregates, projections and read models, snapshots, event schema evolution and upcasting, .NET tooling (Marten, KurrentDB, Eventuous), and the criteria for using or avoiding it.

Senior Theory Advanced architecture cqrs event-sourcing kurrentdb marten projections

🎯 Key points

  • State is derived by replaying an append-only stream of events per aggregate; the event log is the source of truth
  • Optimistic concurrency via expected stream version on append
  • Projections build read models (inline, async, live); usually paired with CQRS
  • Snapshots cap replay cost for long streams; they are a cache, not truth
  • Event versioning: additive changes, upcasting, weak schema, new event types; never rewrite history casually
  • Tooling: Marten on PostgreSQL, KurrentDB (formerly EventStoreDB), Eventuous, or a hand-rolled SQL Server table
  • Worth it for audit-heavy, temporal, behaviour-rich domains; not for CRUD or when the team lacks experience
  • Costs: eventual consistency of projections, GDPR/Privacy Act erasure (crypto-shredding), harder ad-hoc queries

⏱ 30-second answer

Event sourcing stores every state change as an immutable event in an append-only stream per aggregate, and derives current state by replaying those events. The event log is the source of truth; tables you query are projections built from it. Appends use the expected stream version for optimistic concurrency. Snapshots speed up replay for long streams, and events are evolved by additive changes and upcasting, never by editing history.

It's worth it when the history itself is valuable: audit, temporal queries ("what did we know on 1 July?"), complex behaviour. It's a poor fit for CRUD and for teams new to it, because you pay in eventual consistency, schema evolution and harder queries.

🗣 Full answer (senior)

How I would answer this in an interview

"In a normal system I store the current state of an order and overwrite it. With event sourcing I store the facts that led to that state: OrderPlaced, ItemAdded, OrderPaid, appended to a stream for that order. To load the aggregate I replay its stream through Apply methods; to change it, the aggregate decides, emits new events, and I append them with the stream version I read, so a concurrent writer gets a version conflict rather than a lost update. Everything users query comes from projections: handlers that fold events into read models, either inline in the same transaction or asynchronously. Long streams get snapshots so I replay from the snapshot instead of from event one. In .NET the usual choices are Marten on PostgreSQL, KurrentDB (what EventStoreDB is called now) with Eventuous or the native client, or a simple events table in SQL Server if the needs are modest.

For example, at [company] we [used event sourcing for a ledger or claims domain] because [auditors needed to see every change and the reason for it], and the payoff was [being able to rebuild a corrected read model in hours instead of writing data-fix scripts]. The hard parts were [versioning events after a model change, and explaining to the product owner why a list screen was a second behind].

The mistake I see is event sourcing chosen because it's interesting, applied to the whole system, including reference data and CRUD screens. Events become a public schema you can never really change, every query needs a projection, and erasing someone's personal data under the Privacy Act needs crypto-shredding. I'd use it for the one or two aggregates where history is the product, and keep the rest as plain state."


State-based vs event-sourced

State-based (EF Core tables) Event-sourced
Source of truth Current row values Append-only event stream
History Lost unless audited separately Complete, with intent
Writes UPDATE in place Append with expected version
Reads Query tables directly Query projections
Schema change Migration Event versioning, upcasting, projection rebuild
Fixing bad data Data-fix script Compensating events, rebuild projections
Learning curve Low High

When to use it

Use it when Avoid it when
Audit and regulatory traceability are core (ledgers, claims, trading) CRUD or reference data
You need temporal queries or replay of business decisions The team has no experience and a tight deadline
Multiple read models of the same facts are needed Strong read-your-writes everywhere is non-negotiable
The domain is behaviour-rich and events are the language of the business Heavy ad-hoc reporting on current state is the main use

Production example

A [loan servicing] ledger stored around 30 million events across 400,000 streams in Marten. Average stream length was 75 events, so aggregate loads took about 4 ms without snapshots; a few accounts with 20,000+ events got snapshots every 500 events, bringing their loads from 600 ms to 8 ms. A projection bug was fixed by rebuilding the read model in 50 minutes, with no data-fix scripts.

🔍 What the interviewer is checking

Checks that the candidate understands event sourcing mechanics (streams, concurrency, projections, snapshots, versioning) and, above all, has the judgement to know where it is and isn't worth the cost.

Green flags

  • Explains append with expected version and replay through apply
  • Distinguishes inline and async projections and their consistency
  • Has a concrete event versioning strategy (upcasting)
  • Raises privacy erasure and crypto-shredding
  • Recommends it narrowly, with alternatives such as temporal tables

Red flags

  • Equates event sourcing with publishing events or with CQRS
  • Proposes it for the whole system by default
  • Plans to edit stored events to fix mistakes

📚 Learn in depth

1. The model

Stream: order-7f3a
  v1 OrderPlaced     { customerId, lines }
  v2 ItemAdded       { sku, qty }
  v3 OrderPaid       { paymentId, amount }
  v4 OrderShipped    { carrier, trackingNo }

Load:  state = fold(Apply, initial, events)
Write: newEvents = aggregate.Decide(command, state)
       append(stream, newEvents, expectedVersion: 4)  -> conflict if someone else appended v5

The decide/evolve split (Decide(command, state) -> events, Evolve(state, event) -> state) keeps the aggregate pure and trivially testable: given these events, when this command, then these events.

2. Projections in detail

Event store --(subscription / daemon)--> Projection handlers --> Read models
                                             |                     - OrderSummary table
                                             |                     - Search index
                                             |                     - Reporting warehouse
Kind How it runs Consistency Write cost Typical use
Inline Applied in the same transaction as the append (Marten ProjectionLifecycle.Inline) Read-your-writes Every append pays for every inline projection The one or two views a user checks straight after acting (an account balance)
Async A daemon or subscription tails the global log from a stored checkpoint (Marten async daemon, KurrentDB persistent or catch-up subscriptions) Eventually consistent, typically tens to hundreds of ms behind None on the write path Lists, dashboards, search indexes, reporting, integration feeds
Live Computed on demand by replaying the stream at read time Always current None stored Small streams, rarely-read views, debugging

Operational rules for async projections:

  • Store the checkpoint (global position) in the same transaction as the read-model update, so a crash never double-applies or skips events.
  • Make handlers idempotent anyway; rebuilds and replays happen.
  • Monitor projection lag (head position minus checkpoint) as an SLO and alert on it.
  • Rebuild by deploying the projection under a new name, replaying from position 0 alongside the old one, then switching reads. This is the main operational superpower of event sourcing.

3. Snapshots: when and how

A snapshot is serialised aggregate state at version N. Load = snapshot + events after N. Snapshots are a cache: if the aggregate's shape changes, discard and rebuild them.

When to add them:

  • First, check stream design. Most aggregates should be short-lived (a stream per order or per policy term, not per customer for ten years).
  • Measure aggregate load time against stream length. Replaying a few hundred small JSON events usually takes single-digit milliseconds; snapshots are rarely needed below about 500 to 1,000 events per stream.
  • Add them when p99 load time exceeds your budget (say 50 ms) or a known set of streams grows without bound. Snapshot every N events (for example every 500), or on a schedule for hot streams.
  • Track the distribution of stream lengths (Marten and KurrentDB both expose stream versions) and alert on outliers, rather than snapshotting everything up front.

4. Versioning events

Events are written once and read forever. Strategies, in order of preference:

  1. Additive change: add optional fields with defaults; old events still deserialise.
  2. Upcasting: transform old event JSON to the new shape on read (Marten and Eventuous support upcasters).
  3. New event type: OrderPlacedV2 alongside V1, both handled.
  4. Copy-and-transform migration: rewrite streams into a new store. Rare, expensive, risky.

Never rename event types casually: the type name is stored with each event.

5. Privacy and erasure

An immutable log conflicts with deletion requests. Patterns: keep PII out of events (store references to a separate, deletable store), or crypto-shredding (encrypt PII per subject and delete the key). In Australia this matters under the Privacy Act 1988, especially APP 11.2 (destroy or de-identify personal information you no longer need); if you also handle EU residents, GDPR's right to erasure applies.

6. How it compares with neighbouring patterns

Pattern What it gives you Relationship to event sourcing
CQRS Separate write and read models Often paired, but each works without the other
Temporal tables Row history, point-in-time queries Cheaper history, but no business intent
Audit log Who changed what, when Compliance trail only; can't rebuild state
Outbox + integration events Reliable notifications to others Event sourcing can feed it, but internal events are not the public contract
Change data capture Stream of row changes Technical changes, not domain facts

7. .NET tooling (as of November 2026)

  • Marten: document database and event store on PostgreSQL with inline, async and live projections; part of the Critter Stack with Wolverine.
  • KurrentDB: the purpose-built event store database. Event Store Ltd rebranded as Kurrent in December 2024 and renamed EventStoreDB to KurrentDB; the first release under the new name was 25.0, and the .NET client is published as the KurrentDB client package. Older material and many interviewers still say "EventStoreDB".
  • Eventuous: a lightweight .NET event sourcing library; since 0.16 its KurrentDB integration ships as Eventuous.KurrentDB (the old EventStore package names remain as obsolete aliases for a transition period).
  • SQL Server by hand: an Events table with a unique (StreamId, Version) key works for modest volumes, but you then own subscriptions, checkpoints and projections.

Try it yourself

  1. Implement an Account aggregate with Decide and Evolve and write given-when-then tests.
  2. Store events in a SQL Server table with a unique (StreamId, Version) index and trigger a concurrency conflict with two parallel appends.
  3. Build an async projection with a checkpoint table updated in the same transaction; kill it mid-run and confirm it resumes without double counting.
  4. Add a field to an event, then write an upcaster for old events.
  5. Generate a stream of 50,000 events and measure load time with and without a snapshot using BenchmarkDotNet; find the stream length where your budget is exceeded.

💻 Code

A minimal event-sourced aggregate with decide/evolve, and an append with optimistic concurrency against a SQL Server events table.

namespace Banking.Domain;

public interface IEvent;
public sealed record AccountOpened(Guid AccountId, string Owner) : IEvent;
public sealed record MoneyDeposited(decimal Amount) : IEvent;
public sealed record MoneyWithdrawn(decimal Amount) : IEvent;

public sealed record Account(Guid Id, decimal Balance, bool IsOpen, long Version)
{
    public static readonly Account Empty = new(Guid.Empty, 0m, false, 0);

    // Evolve: pure fold of one event into state.
    public Account Apply(IEvent e) => (e switch
    {
        AccountOpened o => this with { Id = o.AccountId, IsOpen = true },
        MoneyDeposited d => this with { Balance = Balance + d.Amount },
        MoneyWithdrawn w => this with { Balance = Balance - w.Amount },
        _ => this
    }) with { Version = Version + 1 };

    // Decide: validates the command against current state and returns new events.
    public IReadOnlyList<IEvent> Withdraw(decimal amount) =>
        !IsOpen ? throw new InvalidOperationException("Account is closed.")
        : amount > Balance ? throw new InvalidOperationException("Insufficient funds.")
        : [new MoneyWithdrawn(amount)];

    public static Account Rebuild(IEnumerable<IEvent> history) => history.Aggregate(Empty, (s, e) => s.Apply(e));
}
-- The (StreamId, Version) unique key is the optimistic concurrency check.
CREATE TABLE dbo.Events (
    GlobalPosition BIGINT IDENTITY PRIMARY KEY,
    StreamId       UNIQUEIDENTIFIER NOT NULL,
    Version        BIGINT NOT NULL,
    EventType      NVARCHAR(200) NOT NULL,
    Payload        NVARCHAR(MAX) NOT NULL,
    OccurredAt     DATETIMEOFFSET NOT NULL,
    CONSTRAINT UQ_Events_Stream_Version UNIQUE (StreamId, Version)
);
namespace Banking.Application;

using Banking.Domain;

public sealed class WithdrawHandler(IEventStore store)
{
    public async Task HandleAsync(Guid accountId, decimal amount, CancellationToken ct)
    {
        var history = await store.ReadStreamAsync(accountId, ct);
        var account = Account.Rebuild(history);
        var newEvents = account.Withdraw(amount);

        // Throws a concurrency exception if another writer appended after we read (unique key violation).
        await store.AppendAsync(accountId, expectedVersion: account.Version, newEvents, ct);
    }
}

public interface IEventStore
{
    Task<IReadOnlyList<IEvent>> ReadStreamAsync(Guid streamId, CancellationToken ct);
    Task AppendAsync(Guid streamId, long expectedVersion, IReadOnlyList<IEvent> events, CancellationToken ct);
}

⚠ Common mistakes

  • Mistake: Event sourcing the whole system. Why it is wrong: CRUD and reference data gain nothing and every screen needs a projection. Instead: apply it to the aggregates where history is the product.
  • Mistake: Treating events as the integration contract with other services. Why it is wrong: internal event changes then break consumers. Instead: publish separate integration events.
  • Mistake: Editing or deleting stored events to fix bugs. Why it is wrong: destroys the audit trail and breaks projections' positions. Instead: append compensating events and rebuild projections.
  • Mistake: Putting PII directly in events. Why it is wrong: conflicts with deletion obligations under the Privacy Act. Instead: references to a deletable store or crypto-shredding.
  • Mistake: Long-lived streams (one per customer for years) without snapshots. Why it is wrong: load time grows linearly. Instead: design shorter streams, add snapshots where measured.
  • Mistake: Non-idempotent projections without checkpoints. Why it is wrong: restarts double count. Instead: track position and make handlers idempotent.
  • Mistake: Events named after CRUD (OrderUpdated). Why it is wrong: they lose intent, which is the main benefit. Instead: business-named facts (DeliveryAddressChanged).
  • Mistake: Ignoring read-your-writes in the UI. Why it is wrong: users see stale lists right after acting. Instead: inline projections for critical views or return the new state from the command.

🏛 Senior insight: trade-offs

Event sourcing is a local decision for an aggregate or a bounded context, not a system architecture. I ask three questions: is the history itself a business requirement, does the team have someone who has run it in production, and can we live with projections being eventually consistent? Two yeses and a credible plan for the third, and I'll consider it; otherwise temporal tables or an audit log give 80% of the value for 10% of the cost.

The long-term cost is schema evolution. Events are a forever contract with your own future code, so I insist on an upcasting strategy and a projection rebuild runbook before the first event is stored.

Option When it fits Cost When not to
Event sourcing (Marten, KurrentDB, Eventuous) Audit-critical, behaviour-rich aggregates Versioning, projections, skills CRUD, ad-hoc reporting
SQL Server temporal tables Need row history and point-in-time reads Storage, no intent captured You need the reason for each change
Audit log table via interceptor Compliance trail of who changed what Low Need to rebuild state from history

I'd measure aggregate load time by stream length, projection lag, and rebuild duration, and keep those as SLOs.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions projections and read models. Why: Checks they can separate CQRS from event sourcing.
    How to answer

    CQRS splits the model that changes state (commands) from the model that reads it (queries). It grows out of Meyer's CQS (a method either changes state or returns data), applied to whole models.

    • Write side: aggregates with invariants, loaded through repositories, committed by the unit of work.
    • Read side: flat DTOs shaped per screen, projected with Select/AsNoTracking or Dapper.

    There are levels. Separate handlers on one database is cheap and often enough. Denormalised read tables updated in the same transaction stay consistent. A separate read store fed by events scales reads but is eventually consistent, so the UI needs read-your-writes or "processing" states.

    CQRS doesn't need MediatR or event sourcing. It's overkill for CRUD where reads and writes have the same shape. The trade-off is optimised, simple models on each side against more moving parts and, at the top level, stale reads.

  2. When: Candidate says event sourcing is for auditing. Why: Checks they know a cheaper alternative for history.
    How to answer

    A system-versioned temporal table makes SQL Server copy the previous version of a row into a history table on every UPDATE and DELETE, stamping period columns (PeriodStart/PeriodEnd, UTC). Since EF Core 6 you configure it with ToTable(t => t.IsTemporal()); the period columns become shadow properties and migrations create the history table. You query history with TemporalAsOf(utc), TemporalAll(), TemporalFromTo, TemporalBetween and TemporalContainedIn, which return untracked results; restoring a deleted row is a TemporalAsOf query followed by Add. Temporal tables record what and when, not who, so you still need a ModifiedBy column. The trade-off: point-in-time history for free in code, paid for in history storage that grows with every update and needs a retention policy.

  3. When: Candidate mentions snapshots. Why: Checks the link between snapshots and the Memento idea.
    How to answer

    Memento captures an object's internal state as a snapshot so you can restore it later, without exposing that state. The originator creates and restores snapshots; the caretaker (an undo stack) stores them but can't look inside.

    In C# the cleanest way is a private nested snapshot record behind a public marker interface, so only the originator can read it.

    Immutability makes it cheap: with immutable records, the previous instance is the snapshot, and ImmutableList<T> shares structure, so snapshots don't copy everything.

    Compared with Command-based undo, Memento stores whole states (simple, but memory-hungry) while Command stores operations and their inverses (compact, but each needs a correct Undo). In event sourcing, periodic snapshots are mementos that speed up rebuilding state from events.

    The trade-off is memory per snapshot against simplicity of restore.

🛠 Real-world problems: how you handle them

Projection rebuild needed after a currency rounding bug
Situation
An event-sourced [loan servicing] ledger on Marten held [~30 million] events. A projection that built account balances rounded interest incorrectly for [~2%] of accounts over [three weeks].
Signals
Reconciliation against the core banking system flagged balance differences of [cents to a few dollars]; customer support received [a handful] of statement queries; the events themselves were correct.
Investigation
Compared the projection's balances with a live aggregation of events for sampled accounts; traced the difference to a rounding mode in the projection handler; checked projection checkpoint positions and lag in Application Insights.
Resolution
Fixed the rounding (banker's rounding to `MidpointRounding.ToEven` replaced by the contractually required `AwayFromZero`), deployed the projection under a new name, rebuilt it from the event log in [~50 minutes] side by side, then switched reads over. No data-fix scripts and no event edits.
Prevention
Property-based tests comparing projections with live aggregation; a nightly job sampling [1,000] accounts for drift; a rebuild runbook with blue/green projection names; ADR documenting rounding rules.

How to tell it (STAR)

**S:** Our ledger's balance projection had a rounding bug affecting [~2%] of accounts for [three weeks]. **T:** As [tech lead], I had to correct balances without touching the immutable events. **A:** I confirmed the events were right by comparing against live aggregation, fixed the rounding, and rebuilt the projection under a new name alongside the old one, then switched reads once reconciliation matched. I wrote a rebuild runbook and added a nightly drift check. **R:** Balances were corrected in [under an hour] with zero downtime, and the drift check has since caught [one] other projection bug before customers did.

↩ Usually asked after

More in Architecture Patterns

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me