Event sourcing

On this page 7

Event sourcing is a pattern in software architecture in which an application stores every change to its state as an immutable event in an append-only log, instead of overwriting rows with the latest values. The current state of any business object is derived by replaying its events in order, so the event log, not a table of current values, becomes the authoritative source of truth.

The pattern is common in domains where history matters as much as the present: accounting, order management, logistics, insurance and regulated systems. It pairs naturally with CQRS and with event-driven architecture, but it is a distinct decision about how data is persisted, and it brings real costs in complexity, schema evolution and operational discipline.

How event sourcing records and rebuilds state

An event-sourced system persists facts about what happened rather than snapshots of what is. Each event is a past-tense business fact, such as OrderPlaced, ItemAdded or PaymentCaptured, carrying the data needed to apply it and metadata such as a timestamp, an event type and a sequence number within its stream.

Events are grouped into streams, usually one stream per aggregate, the consistency boundary taken from domain-driven design. To process a command, the application loads the aggregate’s stream, folds the events into an in-memory state, validates the command against that state and appends new events. Optimistic concurrency protects the stream: the append succeeds only if the stream is still at the expected version, otherwise the command is retried or rejected.

The following table lists the core building blocks and the role each one plays.

ComponentRoleTypical implementation
EventImmutable record of one business factSerialized JSON, Avro or Protobuf payload
Event streamOrdered sequence of events for one aggregateStream identified by aggregate ID
Event storeAppend-only persistence with versioned streamsDedicated event database or relational table
AggregateEnforces business rules and emits new eventsDomain object with apply and handle methods
ProjectionBuilds a read model from eventsSubscriber that updates tables or indexes
SnapshotCached state at a given versionSerialized state stored every N events
Core components of an event-sourced system

Because events are never updated or deleted in normal operation, the log behaves like an accounting ledger: corrections are made by appending a compensating event, such as PaymentRefunded, rather than by editing an earlier entry.

Projections, snapshots and read models

Replaying a stream answers questions about one aggregate, but it is a poor way to answer queries across many of them. Event-sourced systems therefore build projections, also called read models, that subscribe to the event log and maintain query-optimized views in a relational database, a search index or a cache.

Projections are typically updated asynchronously, which means reads are eventually consistent with writes, often lagging by milliseconds to seconds. A major advantage is that projections are disposable: a new report or a fixed bug can be handled by rebuilding a projection from the full history, something a state-based database cannot do once old values are overwritten.

Long-lived aggregates with thousands of events can become slow to load. Snapshots store the folded state at a known version, so loading starts from the latest snapshot and replays only the newer events. Snapshots are an optimization, not a source of truth, and they should be safe to discard and regenerate.

Event sourcing is often confused with neighboring architectural ideas because they share the same vocabulary. The table below separates the concepts by what each one actually decides.

ConceptWhat it decidesRelationship to event sourcing
State-based persistenceStore only the current valuesThe conventional alternative it replaces
CQRSSeparate write and read modelsFrequent companion, but each works alone
Event-driven architectureServices communicate through eventsIntegration style, not a storage model
Change data captureStream row changes from a database logCaptures technical changes, not domain intent
Audit log tableRecord changes beside current stateSecondary record that can drift from truth
Event sourcing compared with related concepts

A key distinction is between domain events stored inside a service and integration events published to other services. Exposing the internal event store directly to other teams couples them to private schemas, so mature designs publish a curated set of integration events and keep internal events free to evolve.

When event sourcing is a good fit

Event sourcing pays off when the history of changes carries business value, when auditability is mandatory or when the team needs to answer questions that were not anticipated at design time. It is rarely justified for simple data entry applications where CRUD persistence is adequate.

SituationRecommendationReason
Regulated financial ledgerStrong fitFull, tamper-evident history is required
Complex workflow with many statesGood fitEvents model transitions explicitly
Analytics on past behaviorGood fitHistory can be reprojected at any time
Simple content or settings managementUsually avoidOverhead exceeds the benefit
Team new to domain modelingAvoid initiallyPoor event design is costly to undo
Decision guide for adopting event sourcing

Many organizations apply the pattern selectively, using event sourcing for one or two core bounded contexts and conventional persistence elsewhere. This limits the learning curve while keeping the benefits where they matter most.

Limitations and common mistakes

The immutability that makes event sourcing powerful also makes mistakes durable. Event schema evolution is the most persistent challenge: old events must remain readable for as long as they are stored, which requires upcasting, versioned event types or weak-schema serialization.

ProblemCauseRemedy
Events named like database operationsCRUD thinking such as OrderUpdatedName events after business facts
Unreadable historical eventsBreaking payload changesUse upcasters and version event types
Slow aggregate loadingVery long streamsAdd snapshots or split the aggregate
Stale screens confuse usersAsynchronous projectionsDesign the UI for eventual consistency
Personal data cannot be erasedImmutable logApply crypto-shredding or store data outside events
Frequent problems and their remedies

Privacy law adds another constraint. A right-to-erasure request conflicts with an immutable log, so teams commonly encrypt personal fields with per-subject keys and delete the key when erasure is required, a technique known as crypto-shredding. Operational tooling for replay, monitoring projection lag and debugging is also less mature than for relational databases, which raises the total cost of ownership.

Explained without jargon

Most programs keep only the latest version of their data, like a whiteboard that is wiped and rewritten every time something changes. Event sourcing works more like a bank statement. Instead of storing only your balance, it stores every deposit and every withdrawal, in order.

If you want the current balance, you add up the entries. If you want to know what the balance was last March, you add up the entries until last March. Nothing is ever erased, and a mistake is fixed by writing a new correcting entry. The main idea is simple: keep the full story, and calculate the present from it.

A typical use case

A mid-sized online retailer rebuilds its order service with event sourcing. Each order becomes a stream of events such as OrderPlaced, ItemRemoved, PaymentCaptured, ParcelShipped and ReturnRequested. A projection keeps a fast order-status table for the customer website, while another feeds the warehouse dashboard.

Six months later, the finance team asks how often customers remove items after applying a discount code. In the old system that information was overwritten and lost. With the event log, a developer writes a new projection, replays roughly two million historical events overnight and delivers the report the next morning. When a customer disputes a refund, support staff can see exactly what happened and when, step by step, which shortens the investigation from hours to minutes.