Design Patterns

Event Sourcing

Understanding event sourcing for storing application state.

2 min readConcepts · System Design

What is Event Sourcing?

Event Sourcing stores state changes as a sequence of events rather than storing current state. The current state is derived by replaying all events.


Traditional vs Event Sourcing

Traditional vs Event SourcingFlowchart

Core Concepts

ConceptDescription
EventImmutable record of something that happened
Event StoreAppend-only log of events
AggregateDomain object rebuilt from events
ProjectionRead model derived from events
SnapshotCached state to avoid replaying all events

How It Works

How It WorksSequence diagram

Event Structure

{
  "eventId": "uuid-123",
  "eventType": "OrderPlaced",
  "aggregateId": "order-456",
  "timestamp": "2024-01-15T10:30:00Z",
  "version": 1,
  "data": {
    "customerId": "cust-789",
    "items": [...],
    "total": 99.99
  },
  "metadata": {
    "userId": "user-123",
    "correlationId": "req-abc"
  }
}

Benefits

BenefitDescription
Complete audit trailEvery change is recorded
Temporal queriesQuery state at any point in time
Debug and replayReproduce issues by replaying events
Event-drivenNatural fit for event-driven architecture
Undo/redoCan reverse by applying compensating events

Challenges

ChallengeMitigation
Event schema evolutionVersioning, upcasters
Performance (replay)Snapshots
Eventual consistencyAccept or design around
ComplexityOnly use when benefits outweigh

Snapshots

Avoid replaying all events by periodically saving state:

SnapshotsFlowchart

Event Sourcing + CQRS

Often used together:

Event Sourcing + CQRSFlowchart
  • Events are the source of truth
  • Projections create optimized read models
  • Different projections for different query needs

Interview Tips

  • Explain events as source of truth
  • Discuss rebuild from events
  • Know when to use snapshots
  • Mention schema evolution challenges
  • Compare with traditional CRUD
  • Give use cases: banking, audit systems

Finished reading?

Mark it done to track your progress in Concepts.