Back to all terms
E1eventE2eventE3eventE4eventE5eventCurrent State
State & Archadvanced

Event Sourcing

A persistence pattern where state changes are stored as an immutable, append-only sequence of domain events rather than overwriting the current state in place.

Also known as: Event Store Pattern, Event Log Pattern, Append-Only Event Log

Description

Event sourcing is a persistence pattern where the source of truth for an entity's state is not a mutable row in a database, but an immutable, append-only sequence of events that describe everything that has ever happened to that entity. To determine the current state, you replay the event sequence from the beginning (or from a snapshot) and apply each event's transformation. An order's state, for example, is derived by replaying: OrderCreated -> ItemAdded -> ItemAdded -> CouponApplied -> OrderSubmitted -> PaymentProcessed -> OrderShipped.

Event sourcing provides several powerful capabilities that traditional CRUD persistence cannot match. Complete audit trail: every state change is preserved and can be examined for debugging, compliance, or analytics. Temporal queries: you can reconstruct the state at any point in the past by replaying events up to that timestamp. Event replay: you can build entirely new read models by replaying historical events through new projections. Bug investigation: you can replay the exact sequence of events that led to a bug in a development environment.

The challenges of event sourcing are substantial. Event schemas must evolve without breaking replay (upcasting strategies are essential). Long event streams require snapshots to avoid slow reconstruction. Deleting data for GDPR compliance conflicts with immutability (crypto-shredding or tombstone events are common solutions). The eventual consistency between the event log and read projections requires careful UX design. Event sourcing is best suited for domains with complex business logic, audit requirements, or where the history of changes is inherently valuable—financial systems, healthcare records, legal document management, and collaborative editing.

Prompt Snippet

Implement event sourcing for the account aggregate using EventStoreDB as the event store with events serialized as JSON. Define a strict event schema per aggregate (AccountOpened, FundsDeposited, FundsWithdrawn, AccountFrozen) using TypeScript discriminated unions validated by Zod. Implement aggregate reconstruction via a fold function that replays events into current state, with snapshots stored every 100 events in a separate stream to bound reconstruction time. Handle schema evolution with an upcaster pipeline that transforms v1 events to v2 format during replay. For GDPR, implement crypto-shredding by encrypting PII fields with a per-user key stored in a separate key vault, deleting the key on erasure requests.

Tags

architecturepersistenceevent-drivenauditdistributed-systems