Event Sourcing
Event Sourcing persists the history of what happened to a domain object rather than just its current state, making every change first-class and queryable.
Overview
Instead of storing the current row in a database table, an event-sourced system appends a new immutable event every time something meaningful happens to an aggregate. Current state is derived by replaying those events in order. This gives a complete audit trail for free, enables temporal queries, supports event replay into new projections, and makes debugging production incidents far easier. The trade-offs are query complexity, event versioning discipline, and the need for snapshot strategies when event streams grow long.
What you will learn
- Treat streams as source of truth.
- Rehydrate deterministically.
- Append with expected-version concurrency.
- Build idempotent projections.
- Evolve immutable schemas.
- Operate snapshots, replay, privacy, backup, and recovery.
Prerequisites
- DDD, CQRS, serialization, and concurrency.
- Eventual consistency and projections.
- A concrete historical business need.
When to use Event Sourcing
Good fit
- History and temporal decisions have value.
- Replayable projections are required.
- The domain is behavior-rich.
Choose another approach when
- Current CRUD state is enough.
- Privacy requirements are unresolved.
- Schema evolution and rebuild operations are unavailable.
Key concepts
Ordered append-only aggregate facts.
Replay reconstructs state.
Optimistic concurrency rejects stale appends.
Decisions produce events before persistence.
Subscribers build query models.
Measured checkpoints reduce replay.
Upcasters translate history.
Global positions track projection progress.
Architecture
Commands produce domain events appended to an event store; projections subscribe to the store and populate read models that queries use.
Conceptual architecture · Adapt to your system context
Implementation walkthrough
The account sample emits decisions, replays history, tracks changes, and rejects stale versions.
- 01Choose aggregates
Use sourcing where history matters.
- 02Design events
Record complete immutable facts.
- 03Implement apply
Keep replay deterministic.
- 04Append safely
Use expected versions.
- 05Build projections
Checkpoint idempotently.
- 06Evolve schemas
Upcast and compatibility-test.
- 07Operate replay
Snapshot, rebuild, back up, and restore.
Code example
The aggregate applies events to change its own state; the command handler appends those events to the store rather than saving a mutated entity.
public sealed class Order
{
public Guid Id { get; private set; }
public OrderStatus Status { get; private set; }
public decimal Total { get; private set; }
public static (Order, IReadOnlyList<object>) Place(
Guid id, CustomerId customerId, IEnumerable<OrderLine> lines)
{
var order = new Order();
var events = new List<object>
{
new OrderPlaced(id, customerId, lines.ToList(), DateTime.UtcNow)
};
foreach (var e in events) order.Apply(e);
return (order, events);
}
public (IReadOnlyList<object> Events) Cancel(string reason)
{
if (Status != OrderStatus.Pending)
throw new DomainException("Only pending orders can be cancelled.");
var events = new List<object> { new OrderCancelled(Id, reason, DateTime.UtcNow) };
foreach (var e in events) Apply(e);
return (events);
}
private void Apply(object @event)
{
switch (@event)
{
case OrderPlaced e:
Id = e.OrderId;
Status = OrderStatus.Pending;
Total = e.Lines.Sum(l => l.Subtotal);
break;
case OrderCancelled:
Status = OrderStatus.Cancelled;
break;
}
}
// Reconstitution: load from event stream
public static Order Rehydrate(IEnumerable<object> events)
{
var order = new Order();
foreach (var e in events) order.Apply(e);
return order;
}
}
public sealed record OrderPlaced(
Guid OrderId, CustomerId CustomerId,
IReadOnlyList<OrderLine> Lines, DateTime OccurredAt);
public sealed record OrderCancelled(
Guid OrderId, string Reason, DateTime OccurredAt);Testing strategy
Test decisions and replay separately.
- Assert events from history.
- Replay and assert state.
- Reject stale versions.
- Replay projections twice.
- Test upcasters.
- Rebuild from backup.
Security considerations
Immutable history complicates data lifecycle.
- Minimize sensitive data.
- Design encryption keys.
- Authorize stream access.
- Protect projections.
- Audit replay and export.
Performance and scalability
Stream length and projection throughput shape cost.
- Bound event size.
- Snapshot from evidence.
- Batch projection reads.
- Partition subscriptions.
- Track lag and replay rate.
Deployment and operations
Events outlive code versions.
- Deploy upcasters.
- Use additive evolution.
- Version projections.
- Preserve checkpoints.
- Rehearse restore and rebuild.
Common problems and fixes
Replay state differs.
Likely cause: Apply is nondeterministic.
Fix: Remove time and I/O.
Concurrent writes overwrite.
Likely cause: Expected version is absent.
Fix: Use optimistic append.
Projection duplicates.
Likely cause: Updates are not idempotent.
Fix: Store positions with effects.
Old events fail.
Likely cause: Schema is incompatible.
Fix: Add upcasters.
Load is slow.
Likely cause: Streams are long.
Fix: Measure and snapshot.
Deletion conflicts with history.
Likely cause: Privacy design is missing.
Fix: Minimize and crypto-shred where appropriate.
Best practices
- Use past-tense facts.
- Keep streams aggregate-scoped.
- Append with expected versions.
- Keep apply pure.
- Make projections idempotent.
- Upcast history.
- Snapshot only from evidence.
- Rehearse rebuilds.
Production checklist
- Business value is explicit.
- Events are immutable facts.
- Apply is deterministic.
- Expected-version append is atomic.
- Projections rebuild idempotently.
- Evolution is tested.
- Privacy lifecycle is resolved.
- Restore and reconciliation are rehearsed.
Common interview questions
Event sourcing versus audit log?
Events are the source of truth.
Relation to CQRS?
Independent but often combined.
How evolve events?
Compatible schemas and upcasters.
Why expected version?
To detect concurrency.
What is a projection?
A derived query model.
When snapshots?
When measured replay cost requires them.
How handle deletion?
Minimize data and design key or retention policy.
Dedicated GitHub sample
Clone, run, test, and modify the focused implementation created for this guide.
Event-Sourced Account
A .NET 10 bank-account aggregate demonstrating decision-time events, ordered replay, uncommitted changes, stream versions, and optimistic concurrency.
- Run
dotnet run --project src/EventSourcedAccount- Test
dotnet test EventSourcedAccount.slnx