Event Sourcing
Persist state as an append-only log of immutable events; current state is derived by replaying events, giving a full audit history and time-travel.
By Ratish Jain · Updated
Definition
Event sourcing stores every change to application state as an immutable event in an append-only log, rather than storing only the latest state. The current state of an entity is reconstructed by replaying its events from the beginning.
The event log becomes the single source of truth. Events like OrderPlaced, ItemAdded, OrderShipped are facts that happened and are never mutated or deleted.
The Problem It Solves
Traditional CRUD stores overwrite state, destroying history — you know an account balance is $50 but not how it got there. Auditing, debugging, and temporal queries become impossible without bolt-on logging.
Event sourcing keeps the full history for free, enables reconstructing state at any past point (time-travel), and provides a reliable event stream for building multiple read models and integrations.
How It Works
- 1A command is validated against the current aggregate state.
- 2If valid, it produces one or more events describing what changed.
- 3Events are appended to the event store; they are never updated or deleted.
- 4Current state is rebuilt by loading and replaying the entity's events in order.
- 5Snapshots periodically capture state so replay doesn't start from zero.
- 6Projections consume the event stream to build denormalized read models.
Schema evolution is hard
Events are stored forever, so old event versions live alongside new ones. You must version event schemas and write upcasters to translate old events, since you can never simply migrate the immutable log.
Tradeoffs
- Complete, immutable audit trail by design.
- Time-travel: reconstruct state at any point.
- Natural fit with CQRS and multiple read models.
- Events double as an integration/notification stream.
- High complexity; unfamiliar to most teams.
- Event schema versioning and upcasting are hard.
- Rebuilding state needs snapshots for performance.
- Queries require projections; no ad-hoc SQL on current state.
Interview Questions
Use snapshots: periodically persist the aggregate's computed state, then on load start from the latest snapshot and replay only the events after it. This bounds replay cost while keeping the full log as the source of truth.
They are independent but synergistic. Event sourcing gives you an event stream that projections turn into denormalized read models — exactly the query side CQRS needs. CQRS defines the read/write split; event sourcing supplies the events that feed the reads.
- →Store immutable events, not just current state.
- →Rebuild state by replaying the event log.
- →Snapshots bound replay cost.
- →Free audit trail and time-travel.
- →Event schema versioning/upcasting is the main pain.
Related
Everything on Archprimer is connected — follow the graph.