What it is
Event sourcing stores every change to an entity as an event, appended to that entity's stream, instead of overwriting its current state. AccountOpened, Deposited(100), Withdrew(30) are the record; balance = 70 is computed from them. The ordered, append-only log is the source of truth. Current state, read models and caches are all derived from it.
Why it exists
A state table remembers only the latest value. Questions such as "how did we get here?", "what was the balance on 1 March?" or "which orders would the new rule have flagged last year?" need history that a state table has thrown away. Audit tables and change logs try to recover it, but they are secondary copies that can drift from the truth. Event sourcing makes the history the primary data, so audit, temporal queries and new read models come from the same place, and events are natural integration points for the rest of the system.
How it works
Streams and events. Each aggregate (account, order) has a stream identified by its id. Events are immutable, named in the past tense in the domain's language (see DDD), and carry the data of what happened. The store also keeps a global order (a position across all streams) for subscribers.
Handling a command. Load the stream, fold the events into state (Apply(event) for each), run the business rules, and append new events with the expected version the decision was based on. If another writer appended in the meantime, the store rejects the append (optimistic concurrency) and the command is retried on fresh state.
public sealed class Account
{
public decimal Balance { get; private set; }
public long Version { get; private set; } = -1;
public static Account Rehydrate(IEnumerable<object> events)
{
var account = new Account();
foreach (var e in events) account.Apply(e);
return account;
}
private void Apply(object e)
{
Balance = e switch
{
Deposited d => Balance + d.Amount,
Withdrew w => Balance - w.Amount,
_ => Balance,
};
Version++;
}
public Withdrew Withdraw(decimal amount) =>
amount <= Balance ? new Withdrew(amount) : throw new InvalidOperationException("Insufficient funds");
}
// Handler: load, decide, append with the expected version (store API varies:
// KurrentDB/EventStoreDB take an expected revision/StreamState, Marten has
// AppendOptimistic or an expected version on Append).
var account = Account.Rehydrate(await store.ReadStreamAsync(id, ct));
var @event = account.Withdraw(cmd.Amount);
await store.AppendAsync(id, expectedVersion: account.Version, new[] { @event }, ct);
Snapshots. For long streams, periodically store the folded state with its version. Loading becomes "latest snapshot + events after it". Snapshots are a cache; they can be discarded and rebuilt. An alternative is to keep streams short by design, e.g. closing an accounting period and opening a new stream with the carried-over balance.
Projections. Subscribers read the global event feed, update read models (tables, documents, search indexes) and store a checkpoint. Because the history is complete, a new projection can start from position 0 and build a read model that includes the past. This is CQRS fed by the event store, with the same eventual consistency.
Versioning. Event schemas evolve. Old events stay as they were written; readers either handle all versions or use upcasters that convert old versions to the current shape on read. Additive changes (new optional fields) are easiest; renaming or splitting events needs care, sometimes a copy-and-transform migration into new streams.
When to use it
- The history itself has business value: ledgers, payments, orders, insurance claims, workflows.
- Audit requirements demand a complete, tamper-evident record of changes.
- You need temporal queries or the ability to build new views over past data.
- The domain is naturally described as a sequence of events (event storming produces them anyway).
When not to
- CRUD data where only the latest value matters (settings, reference data, profiles).
- Teams new to DDD and CQRS; event sourcing amplifies modelling mistakes, because bad events are permanent.
- Systems that need ad-hoc queries over current state without building projections.
- Where hard deletion of data is a core requirement and cannot be designed around.
Trade-offs
| Choice | You gain | You pay |
|---|---|---|
| Events as source of truth | Full history, audit, temporal queries, new views from the past | Projections for every query; versioning forever |
| Optimistic concurrency on streams | No locks while deciding; clean conflicts | Retries under contention on hot streams |
| Snapshots | Bounded load time for long streams | Snapshot versioning and invalidation |
| Short streams (closing the books) | No snapshots needed | Modelling effort; cross-period queries need projections |
| Asynchronous projections | Fast appends, independent read models | Lagging, eventually consistent reads |
Alternatives
- State storage + audit log/history table: simpler; history is secondary and may drift.
- Temporal tables (SQL Server system-versioned tables, PostgreSQL extensions): row history without changing the programming model, but rows, not domain events.
- Change data capture: emits row changes from a normal database as a stream for others to consume.
- Transactional outbox: publishes domain events from a state-stored model without making them the source of truth.
Failure modes
- Unbounded streams. Load time grows with every event; without snapshots or stream closing, commands slow down until the store saturates (the lesson's simulation shows it).
- CRUD events.
AccountUpdated { ...all fields }captures no intent; you get event sourcing's cost without its benefit. - Breaking schema changes. Changing an event's meaning in place corrupts every replay. Version events; never reuse names for new meanings.
- Non-idempotent projections. At-least-once delivery replays events into read models; without checkpoints or version checks, totals are counted twice.
- Personal data in events. Makes erasure requests hard; design for crypto-shredding or references.
- Hot streams. One stream written by many concurrent users produces constant version conflicts; split the aggregate.
In production
Choose a store with per-stream optimistic concurrency and a global subscription: KurrentDB (formerly EventStoreDB), Marten on PostgreSQL in .NET, or a relational table with a unique (stream_id, version) constraint. Keep events small and meaningful, version them explicitly, and test upcasters. Monitor projection lag and rebuild time; build new projection versions alongside the old and switch when caught up. Snapshot only when measurements show long loads. Publish integration events for other services separately from internal domain events, so internal changes don't break consumers.
Common misconceptions
- "Event sourcing is the same as event-driven architecture." EDA is about services communicating through events; event sourcing is a persistence model inside one service. Either can exist without the other.
- "You need Kafka for event sourcing." Kafka lacks per-entity streams with optimistic concurrency on append; it is commonly used to distribute events, rarely as the event store for aggregates.
- "Replay means re-running side effects." Replay rebuilds state; side effects (emails, payments) must not be repeated, which is why handlers that cause them are kept out of the fold.
- "Event sourcing requires CQRS with separate databases." It requires projections for queries, which may live in the same database.
Interview angle
Explain the loop: load stream → fold → decide → append with expected version. Then cover the hard parts unprompted: snapshots for long streams, projections and their lag, idempotent projectors with checkpoints, event versioning with upcasters, GDPR via crypto-shredding, and the distinction from event-driven integration. Mention where you would not use it.
Model assumptions
Most of this lesson is a scripted illustration: appends, stream reads, version conflicts, projections and replays are scripted packets over scenery nodes, not simulated. Two steps (Long stream, Snapshots) and the challenge run on the simulation engine: commands arrive as a Poisson stream; the account service has 64 workers and 3 ms of work per command; the event store has 8 connections, and the time to load a stream and append is modelled as one query of 6 ms (short stream), 150 ms (5,000 events) or 8 ms (snapshot plus tail), lognormal with cv 0.3. Commands waiting more than 500 ms for a connection fail. Real stores read streams in pages and cache hot streams; the numbers are illustrative orders of magnitude, not benchmarks.