Event Sourcing

Store all changes as events

❌ Traditional:
balance: $100
History lost
✅ Event Store:
+$50 • -$20 • +$70
Full history!
How:
Store every change → Rebuild state by replay
Benefits:
Audit trail • Undo/replay • Time travel • Debugging
When to Use:
Financial transactions, audit requirements, undo/replay features
"Implement event sourcing to store all state changes as events for complete audit trail and time travel"

What is Event Sourcing?

Event Sourcing stores every change to application state as a sequence of events, never updating records. Traditional: User balance = $100. Event Sourcing: [Deposited $50, Withdrew $20, Deposited $70] → current balance derived from events. Benefits: full audit trail, time travel (replay to any point), easy debugging. Costs: complexity, eventual consistency, more storage. Useful for finance, compliance, complex domains.

When Should You Use This?

Use Event Sourcing when you need full audit trails (finance, healthcare, legal compliance), when you need to rebuild state at any point in time, or when business logic is complex and benefits from event replay. Don't use for simple CRUD apps—it adds significant complexity. Most apps don't need event sourcing, an audit log table is simpler.

Common Mistakes to Avoid

  • Using everywhere—event sourcing for todo list is overkill
  • No snapshots—replaying 1M events to get current state is slow, snapshot periodically
  • Mutable events—once written, events should never change
  • No versioning—event schema changes break replay
  • Confusing with event-driven—event sourcing is a storage pattern, event-driven is communication pattern

Real-World Examples

  • Banking systems—Every transaction stored as event for compliance
  • Git—Event sourcing for code changes, can replay to any commit
  • Trading platforms—Event sourcing for audit trail of all trades
  • Healthcare—Patient records as events for compliance and audit

Category

System Design Patterns

Tags

event-sourcingarchitectureaudit-trailcqrssystem-design

Permalink