Domain-Driven Design (50 Qs)•Part 3: Advanced Architecture & Production Patterns (Senior / Lead)
What is Event Sourcing and how does it integrate with DDD Aggregates?
senior LevelSystem Design
In Simple Words: In an Event-Sourced aggregate, the state of the entity is reconstructed dynamically by replaying its domain events:
- The database stores an
eventsstream table:(aggregate_id, version, event_type, payload). - When loading an aggregate:
- Fetch all events where
aggregate_id = 'ORD-101'ordered by version. - Instantiate an empty
Orderobject. - Apply each event sequentially (
apply(OrderCreated),apply(ItemAdded)).
- Fetch all events where
- Snapshotting: To prevent replaying 100,000 events, take a state snapshot every 100 events, replaying only events occurring after the snapshot.