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.
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.
"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 throughApplymethods; 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 (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 |
| 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 |
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.
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
Red flags
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.
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:
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:
Events are written once and read forever. Strategies, in order of preference:
OrderPlacedV2 alongside V1, both handled.Never rename event types casually: the type name is stored with each event.
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.
| 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 |
Eventuous.KurrentDB (the old EventStore package names remain as obsolete aliases for a transition period).Events table with a unique (StreamId, Version) key works for modest volumes, but you then own subscriptions, checkpoints and projections.Account aggregate with Decide and Evolve and write given-when-then tests.(StreamId, Version) index and trigger a concurrency conflict with two parallel appends.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);
}
OrderUpdated). Why it is wrong: they lose intent, which is the main benefit. Instead: business-named facts (DeliveryAddressChanged).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.
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.
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.
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.
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.
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.
Last updated 23 Nov 2026.