Event Sourcing
Storing state changes as immutable events. Event store implementation, event replay, schema evolution, and comparison with traditional CRUD approaches.
Event sourcing stores domain changes as an ordered event stream and derives current state by replaying those events. It can support historical queries and projection rebuilds, but retention, privacy, schema evolution, and replay costs need deliberate design. This guide covers aggregate streams, event stores, snapshots, and when CRUD is a simpler fit.
Event sourcing
Introduction
Most applications store current state and treat history as an afterthought. Event sourcing makes an ordered event stream the source of truth; current state is derived by applying those events. That history can support audits and point-in-time reconstruction only when event capture, access, retention, and privacy rules cover those needs. Keeping and operating the history has a cost.
This guide focuses on event stores, aggregate streams, replay, projections, and the operational costs of keeping an event history. For the broader choice between event-driven architecture and request-response, see Event-Driven Architecture.
The core idea
In event sourcing, you store events, not state. An event represents something that happened:
- OrderPlaced
- PaymentReceived
- OrderShipped
- OrderDelivered
To find the current state of an order, replay all its events in order. To find history, read the events directly.
# Events
class OrderPlaced:
order_id: str
customer_id: str
items: list
timestamp: datetime
class PaymentReceived:
order_id: str
amount: decimal
timestamp: datetime
class OrderShipped:
order_id: str
tracking_number: str
timestamp: datetime
# Event store appends events
event_store.append(OrderPlaced(order_id="123", ...))
event_store.append(PaymentReceived(order_id="123", ...))
event_store.append(OrderShipped(order_id="123", ...))
# To get current state, replay events
def get_order_state(order_id):
events = event_store.get_events_for(order_id)
state = Order()
for event in events:
state = apply_event(state, event)
return state
Real implementations handle concurrency, snapshots, and versioning. The principle holds.
flowchart LR
Command[("Command<br/>PlaceOrder")] --> Append[("Event Store<br/>Append-only")]
Append --> Stream[("Event Stream<br/>Order-123")]
Stream --> Proj1[("Projection<br/>Order State")]
Stream --> Proj2[("Projection<br/>Customer History")]
Stream --> Proj3[("Projection<br/>Analytics Events")]
Proj1 -.->|periodic| Snapshot[("Snapshot<br/>Version N")]
Snapshot -->|faster rebuild| Proj1
ReadModel1[("Read Model<br/>Order Detail")] <--> Proj1
ReadModel2[("Read Model<br/>Customer View")] <--> Proj2
ReadModel3[("Read Model<br/>Dashboard")] <--> Proj3
Event store implementation
An event store is an append-only log of events. Properties:
- Events are immutable once written
- Events are organized into streams, often one per aggregate
- Events are ordered within a stream by a revision or sequence number; timestamps describe when something happened but do not establish order
- Events include metadata: timestamp, user, correlation ID
Simple implementations use a relational table:
CREATE TABLE events (
event_id BIGINT PRIMARY KEY AUTO_INCREMENT,
aggregate_id VARCHAR(100) NOT NULL,
aggregate_type VARCHAR(50) NOT NULL,
stream_version BIGINT NOT NULL,
event_type VARCHAR(100) NOT NULL,
event_data JSON NOT NULL,
metadata JSON,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY uq_aggregate_version (aggregate_id, stream_version)
);
Production event stores like EventStoreDB, Axon, and Marten provide stream management, snapshots for performance, projections for building read models, and subscriptions for reacting to new events. The uniqueness constraint also shows the ordering boundary: one aggregate stream has its own sequence, not a global order across the store.
Retention, privacy, and replay safety
An append-only history does not automatically make a complete or compliant audit record. Define which changes must be emitted, who may read or replay them, and how long each event is retained. Keep personal data out of events when an identifier or a reference will do. If a deletion request applies, the plan may need to cover the event store, backups, snapshots, projections, retry queues, exports, and logs; event immutability alone does not resolve that obligation. See Event Security and Sensitive Data for a lifecycle review.
Replay also has a cost. Rebuilding a projection can consume substantial storage and compute, and replaying command handlers may repeat external effects such as emails or payments. Use deterministic projection handlers, isolate replay from live side effects, and measure rebuild time before relying on it for recovery. Snapshots shorten replay; they do not replace retention decisions or the event history.
Event replay for state reconstruction
Given retained events for an aggregate, you can reconstruct state at a specific stream revision. For a wall-clock query, define how the store maps time to a revision. For example, if each revision has a store-assigned commit time, select the last revision committed by 3:00pm on March 15, then replay through that revision in stream order. Producer-supplied occurrence times do not establish that boundary.
To investigate why an order was cancelled, read its events in revision order and inspect the retained context for the relevant change.
Bug in projection logic? Rebuild the read model from scratch by replaying all events.
Snapshots improve performance for long-lived aggregates. Store periodic snapshots and replay only events since the last snapshot instead of replaying everything from the beginning.
# Resolve any wall-clock query to a stream revision before calling this function.
def get_order_state(order_id, target_revision):
snapshot = event_store.get_snapshot_at_or_before(order_id, target_revision)
events = event_store.get_events_since(
order_id, snapshot.version, until_revision=target_revision
)
state = snapshot.data
for event in events:
state = apply_event(state, event)
return state
Eventual consistency and read model rebuilding
Event sourcing typically uses CQRS. Commands produce events. Events are stored. Separate read models consume events and build query-optimized views.
The read model is eventually consistent. Events are written, then published to consumers who update read models. There is a delay between a command succeeding and the read model reflecting that change.
This delay is typically milliseconds in normal operation but can stretch under load or during rebuilding.
Read model rebuilding is useful. You can add new projections to existing data, rebuild after fixing bugs, create new read models for new features from historical data, and test projections against the same events.
# Rebuild a read model from scratch
def rebuild_read_model(projection, from_version=0):
events = event_store.get_all_events(from_version=from_version)
for event in events:
projection.handle(event)
projection.persist()
Comparing with traditional CRUD
Traditional CRUD stores current state directly. Update overwrites previous state.
| Aspect | CRUD | Event Sourcing |
|---|---|---|
| Data stored | Current state | History of changes |
| Update behavior | Overwrite | Append |
| History | Optional, must be designed | Retained event history |
| Debugging | Limited visibility | Inspect retained events |
| Read models | Direct from primary store | Built from events |
| Storage | Typically less | Typically more |
| Complexity | Simpler | More complex |
CRUD works for simple domains where current state is enough. Event sourcing may fit when the domain needs historical reconstruction or multiple projections and the team can operate the event store, replay path, and retention policy. For audit requirements, verify that the events capture the required facts and that retention and access controls meet the policy.
Event sourcing storage grows with the retained history. Snapshots reduce reconstruction time but do not reduce the history itself. Archive or delete events only under a documented retention policy that accounts for audit, recovery, and privacy requirements.
Handling event schema evolution
Events are immutable but schemas change. A ProductCreated event from three years ago might have different fields than one created today.
Versioning approaches:
Upcasting: write an upcaster that transforms old event versions to new versions during replay.
Event versioning: include version numbers in events and handle different versions in projection logic.
Schema migration: migrate old event data to new schema when reading.
# Upcaster example
class OrderPlacedUpcaster:
def can_upcast(self, event_data):
return event_data.get('version', 0) < 2
def upcast(self, event_data):
if event_data.get('version', 0) < 1:
event_data['customer_email'] = None
if event_data.get('version', 0) < 2:
event_data['customer_id'] = str(event_data['customer_id'])
event_data['version'] = 2
return event_data
Most teams add versioning when needed. Over-engineering upfront costs more than dealing with old events later.
When to use / when not to use event sourcing
Consider event sourcing when:
- The domain needs a durable history and the required retention and deletion policy is feasible
- You need to reconstruct state at any point in time
- Debugging requires understanding how state evolved
- Read models may need to be rebuilt from scratch
- Read and write models have different needs, and the team can operate both
- Your domain involves long-running processes with multiple steps
Do not use event sourcing when:
- CRUD is simpler and history is not important
- Your team lacks experience with distributed systems patterns
- Storage, retention, or deletion requirements cannot be met by an append-only history
- You need strong consistency within milliseconds
- Schema changes are frequent and upfront versioning overhead is too high
Event sourcing vs CRUD vs state storage trade-offs
| Dimension | CRUD (State Storage) | Event Sourcing | State + Events Hybrid |
|---|---|---|---|
| Storage model | Current state | Immutable events | Both |
| History preserved | None (overwrites) | Retained event history | Limited event log |
| Update behavior | Overwrite | Append-only | Append events |
| Debugging visibility | Current state only | Full replay | Recent events + snapshots |
| Read model rebuild | N/A | Full from scratch | From last snapshot |
| Storage growth | Controlled | Grows with retained events | Managed with TTL |
| Schema evolution | Migrate existing rows | Upcasters on replay | Versioned events |
| Complexity | Low | High | Medium |
| Best for | Simple CRUD apps | Audit-critical domains | Most event-driven systems |
Production failure scenarios
| Failure | Impact | Mitigation |
|---|---|---|
| Event replay explosion | Long aggregates take minutes to rebuild | Use snapshots, limit aggregate size, archive old events |
| Schema evolution gaps | Old events fail to deserialize | Upcasters, version numbers in events, backward-compatible schemas |
| Eventual consistency lag | Read models stale after writes | Monitor projection lag, set SLA alerts, design UI for async updates |
| Eventual consistency in multi-aggregate queries | Cross-aggregate reads return inconsistent state | Design aggregates to be consistency boundaries, compensate with sagas |
| Event store write throughput | Single stream becomes bottleneck | Partition by aggregate type, use event store clustering |
| Snapshot corruption | Rebuilds produce wrong state | Verify snapshots, maintain event replay as source of truth |
Capacity estimation: event store growth and snapshot frequency
Event stores grow indefinitely unless you manage them. Understanding growth rates and snapshot frequency is essential for operational planning.
Event store growth formula:
events_per_day = commands_per_day × events_per_command
storage_per_day = events_per_day × avg_event_size
storage_per_year = storage_per_day × 365
For an order processing system handling 100,000 orders per day with 5 events per order on average and 400 bytes per event:
- Events per day: 500,000
- Storage per day: 500,000 × 400 = 200MB
- Storage per year: 200MB × 365 = 73GB
- With snapshots (1 snapshot per aggregate per week): add ~20% overhead → ~88GB per year
Snapshot frequency planning:
events_between_snapshots = desired_rebuild_time_ms / avg_event_process_time_ms
snapshot_frequency_days = events_between_snapshots / events_per_day_per_aggregate
If rebuilding an aggregate from scratch takes 30 seconds (30,000ms) and each event takes 1ms to process, you need a snapshot every 30,000 events. With an aggregate receiving 100 events per day, that is one snapshot every 300 days, roughly yearly. For aggregates receiving 1,000 events per day (an active user account), you need snapshots every 30 days.
The practical approach: snapshot when the aggregate crosses a fixed event count threshold (every 100 or 1000 events) rather than on a time schedule. This keeps rebuild time bounded regardless of aggregate activity level.
Snapshot storage formula:
snapshot_size = aggregate_state_serialized_bytes
total_snapshot_storage = snapshot_size × number_of_aggregates × snapshots_per_aggregate_kept
For 1M aggregates, each snapshot averaging 10KB, keeping 2 snapshots per aggregate (current + previous for safety): 1M × 10KB × 2 = 20GB. For 100M aggregates at the same rate, snapshots use 2TB before indexes or storage overhead.
Observability hooks: monitoring event processing health
Key metrics for event sourcing systems: projection lag, event processing latency, and event store append latency.
-- PostgreSQL: check event stream staleness (for tracked consumer groups)
SELECT
consumer_id,
last_processed_event_id,
last_processed_timestamp,
EXTRACT(EPOCH FROM (now() - last_processed_timestamp)) AS lag_seconds
FROM projection_consumers
WHERE is_active = true
ORDER BY lag_seconds DESC;
Key alerts:
# Projection lag alert
- alert: EventSourcingProjectionLag
expr: event_projection_lag_seconds > 300
for: 5m
labels:
severity: warning
annotations:
summary: "Projection {{ $labels.projection }} lag exceeds 5 minutes"
# Event store append latency
- alert: EventStoreAppendLatencyHigh
expr: histogram_quantile(0.95, event_append_duration_seconds) > 0.1
for: 5m
labels:
severity: warning
annotations:
summary: "Event store append P95 latency above 100ms"
# Snapshot age alert (detect aggregates not being snapshotted)
- alert: SnapshotAgeExceedsThreshold
expr: max(event_count_since_last_snapshot) BY (aggregate_type) > 50000
for: 1h
labels:
severity: warning
annotations:
summary: "Aggregate type {{ $labels.aggregate_type }} has aggregates without recent snapshots"
Illustrative example: trading history
A trading system may choose event sourcing when its rules require reconstruction of a position at a historical point in time. The event stream might record trades, approvals, and risk decisions, while a projection calculates current positions. That history is useful only for events the system captures and retains. Access, retention, privacy, and rebuild cost still need explicit policies.
See also
- Microservices Roadmap - Event sourcing and CQRS are foundational patterns for event-driven microservice architectures, where services communicate through immutable event logs rather than direct database calls
Related posts
- CQRS Pattern: separating command and query models
- CQRS and Event Sourcing: combining the patterns
- Event-Driven Architecture: asynchronous messaging foundations
- Exactly-Once Delivery: broker delivery boundaries and duplicate handling
- Saga Pattern: coordinating long-running workflows across services
- Event Security and Sensitive Data: access, retention, and deletion across event copies
Interview questions
First define what the new projection needs. An aggregate snapshot helps rebuild aggregate state, but it usually cannot initialize an unrelated projection. Replay the required retained events, including archived data if policy permits, and estimate the storage and compute cost. If full replay is too expensive, maintain a projection-specific checkpoint or export designed for that query. Keep a separate recovery and retention plan for archived events.
Each aggregate is a consistency boundary: its invariants are protected within its own stream, while cross-aggregate consistency is handled through sagas or workflows. If two pieces of state must change atomically, consider whether they belong in one aggregate. If they remain separate, use a saga and handle eventual consistency explicitly. A saga coordinates local transactions; it does not provide a global atomic transaction.
Stored events should remain readable by new code. Use upcasters to transform older event schemas during reads, and version event formats explicitly. Keep an upcaster while retained events depend on it; test representative historical versions and verify the rebuilt aggregate state. Retention or deletion policy may change which historical formats must remain supported.
Snapshots save aggregate state at a stream revision. Reconstruction loads the latest usable snapshot and applies later events in sequence. They can reduce startup time, but they do not replace history or retention policy. A yearly snapshot bounds replay only when a current snapshot exists and the required events after it are available. Replaying from the beginning should produce the same state when handlers are deterministic and schemas remain readable.
For aggregate reconstruction, load the latest valid snapshot and replay events after its revision. The time required depends on the number of later events and the speed of the handlers. A snapshot does not make older events available for a new projection; that projection may need to read the full retained history. If old events are archived, test the retrieval path and account for its cost. Keep a full-history replay separate from live projection processing when it could overload production.
Append-only logging is the storage mechanism: new entries are added, existing entries are never modified or deleted. Event sourcing is the pattern that uses an append-only log to store state-changing events and derives current state by replaying those events. An append-only log can be used for many things (audit logs, transaction logs, message queues) without deriving state from replay. Event sourcing specifically means: the log IS the source of truth, current state is derived by replay, and read models are built by consuming events. The relationship: event sourcing uses append-only logging as its storage mechanism, but not all append-only logs are used for event sourcing.
Use optimistic concurrency with expected version numbers. When loading an aggregate, track its current version. When emitting events, include the expected version. The aggregate root checks: if current version != expected version, reject the command with ConcurrencyException. This prevents two commands from racing on the same aggregate: one succeeds (version matches), one fails (version changed). The failing client fetches the new aggregate state and retries. This is the standard concurrency model for event sourcing aggregates. Implementation: store version as a column on the aggregate record, increment on each event append, check version in the aggregate's command handler before emitting.
Common anti-patterns: using commands as event names (imperative "PlaceOrder" vs past tense "OrderPlaced"), storing too much data in event payloads (include what changed, not entire aggregate state), and not versioning events (breaking changes when schema evolves). Another anti-pattern: creating a separate event for every field change on every aggregate, leading to hundreds of event types that make projections complex. Instead, use coarse-grained events (OrderPlaced with full order snapshot) and let projections extract what they need. Also avoid: rebuilding read models from scratch frequently (use snapshots), storing encrypted binary event data without metadata that enables upcasting (event data should be readable and upcastable, not opaque blobs), and using event sourcing for aggregates that change frequently (event store grows rapidly, rebuild times increase).
Save aggregate state at a chosen stream revision, then load the latest snapshot at or before the target revision and apply later events. More frequent snapshots use more storage; less frequent snapshots take longer to rebuild. Choose a threshold from measured event handling time and recovery targets, then test snapshot restoration across code versions.
Event stores are usually optimized for appending and reading streams, not for ad hoc analytics across aggregates. Build projections for reporting queries, or stream retained events to an analytics store. Some event-store products provide category projections or parallel reads. Choose the option that matches query needs and the cost of maintaining each projection.
When projections consume events asynchronously, a command can succeed before the read model reflects it. The lag depends on load and processing capacity. For a user who reads immediately after writing, show a pending state, wait for the projection to reach the relevant stream revision, or use a synchronous read path where the domain requires it. Event sourcing can exist without asynchronous projections, and CQRS does not require event sourcing.
Each aggregate is a consistency boundary, so its invariants are protected within its own stream. Cross-aggregate consistency is usually eventual and may be coordinated by a saga. Choose boundaries from business invariants and expected concurrency. Large aggregates can become contention points; very small ones can require more workflow coordination.
An event store is an application-managed source of truth organized by aggregate stream. A broker such as Kafka may retain and replay records according to topic retention and consumer offsets; some queues remove acknowledged messages. Broker retention alone does not make a stream the domain source of truth. An event store and broker can work together, but only retained data that the application can read supports a rebuild.
Use upcasters to transform retained old event versions when code reads them. Deploy support for old formats before writing a new format, then test both versions through the relevant handlers. Upcasters avoid rewriting events during ordinary schema changes, but retention or deletion obligations may require an explicit data migration or erasure process.
Correlation ID links related events across aggregates: if a PlaceOrder command triggers an OrderPlaced event, and that triggers a PaymentRequested event, all three share the same correlation ID so you can trace the flow. Causation ID links an event to its immediate cause: the PaymentRequested event has causation ID = the OrderPlaced event ID that caused it. Correlation IDs connect spans of related work across service boundaries; causation IDs describe the direct chain of events within a single workflow. Both matter for debugging: given a PaymentFailed event, you can use correlation ID to find all related events across services, and use causation ID to trace the exact sequence that led to failure. Store both in event metadata: metadata.correlationId = "uuid", metadata.causationId = "previous-event-id".
A stream revision orders events within one aggregate. Events from separate aggregates have no implicit total order. If a workflow needs one event to precede another across streams, coordinate that dependency and record the relevant revisions. Wall-clock timestamps describe event time but do not establish order. If the domain truly needs a global sequence, use an explicit sequencer and account for its throughput and availability limits.
A minimal table needs an aggregate or stream ID, event type, payload, metadata, per-stream revision, and a recorded timestamp. Enforce unique stream revisions and use expected-version checks for concurrent appends. Write the event and advance the stream revision in one transaction. Add snapshots and projection offsets only when the application needs them. Define retention and deletion procedures for stored events and their copies.
For an aggregate receiving 1,000 events per day, a five-year stream contains about 1.83 million events. Measure replay time with the real handler and state size, then choose a snapshot interval that meets the recovery target. Snapshot storage depends on serialized state size, aggregate count, and how many revisions you retain. Keep a previous snapshot only if it helps recovery from a corrupt or incompatible latest snapshot.
Load the latest valid snapshot at or before the target stream revision, then apply later events in revision order. Without a snapshot, replay from the stream's beginning. For a historical query by date, define which recorded or domain timestamp is authoritative, then resolve events in stream order; do not use timestamps as a substitute for sequence. Batch reads when needed and test snapshot compatibility before deploying new aggregate code.
Aggregate code evolves but old events must still deserialize. Strategy: never delete or rename fields from event schemas; only add optional fields. The aggregate event handler must handle old event versions via upcasters. Upcasters are functions registered by source version that transform old event data to current schema. Example: a OrderPlaced event in v1 has customerEmail; in v2 it is renamed to customerId. The upcaster for v1 reads customerEmail, maps it to customerId, and marks version as 2. The aggregate handler always receives the current version. Test by replaying all historical event versions through the aggregate and verifying final state is correct. Maintain a version test suite that runs after every schema change.
Further reading
Core Resources:
- Event Store Documentation: production event store implementation
- Martin Fowler: Event Sourcing: Fowler’s original event sourcing article
- CQRS and Event Sourcing: Microsoft patterns reference
Framework Guides:
- Axon Framework Guide: Java CQRS/ES framework
- Marten Documentation: .NET event sourcing with PostgreSQL
- Event Sourcing in JavaScript: .NET event sourcing basics
Advanced Topics:
- Schema Evolution for Events: upcaster patterns and event versioning
- Snapshots in Event Sourcing: snapshot strategies for aggregate performance
- Event Sourcing: Trade-offs and Gotchas: common pitfalls and mitigation
Related Patterns:
- CQRS Pattern: command and query separation
- Event-Driven Architecture: async messaging and event bus patterns
- Consistency Models: strong vs eventual consistency in distributed systems
Conclusion
Event sourcing can support historical investigation and rebuildable read models when the event stream captures the facts those tasks require. It also adds work: eventual consistency, schema evolution, access control, retention, and event-store operations. CQRS is a related pattern, but neither one is a default fit for every domain.
Consider event sourcing when the domain needs historical reconstruction or rebuildable read models and the team can operate the event store and its retention policy. For audit requirements, verify that event capture, access, and deletion rules meet the policy. Use CRUD when current state is enough and a separate history mechanism is simpler.
Category
Related Posts
CQRS Pattern
Decide whether separate command and query models solve a real problem, how to begin in one store, and when a read model can tolerate lag.
Event Sourcing: Projections, Replay, and Recovery
An operations guide to event streams, idempotent projections, schema changes, snapshots, lag, and safe read-model rebuilds.
Publish/Subscribe Patterns: Topics, Subscriptions, Filtering
Learn publish-subscribe messaging patterns: topic hierarchies, subscription management, message filtering, fan-out, and dead letter queues.