API / Microservices Design Patterns Interview Questions
What is Event Sourcing and how does it complement CQRS?
Event Sourcing stores the state of a domain entity not as its current snapshot in a row, but as an append-only log of every domain event that has ever happened to it. The current state is derived on demand by replaying all events for that entity from the beginning (or from the most recent snapshot). Nothing is ever deleted or updated in place — the event log is immutable.
// Event store: append-only events for Order#42: [1] OrderPlaced { customerId: C1, items: [...] } t=09:00 [2] AddressUpdated { newAddress: "123 Main St" } t=09:05 [3] PaymentReceived { amount: 59.99, txnId: T77 } t=09:07 [4] OrderShipped { carrier: "UPS", trackingId: U99 } t=09:30 // Replay to derive current state Order order = new Order(); events.forEach(e -> order.apply(e)); // order.status == SHIPPED
Key properties:
- Full audit trail — every state transition is recorded with its timestamp and actor. No separate audit log needed.
- Temporal queries — you can reconstruct the state of any entity at any point in time by replaying up to a given event position.
- Event replay — if a bug introduced wrong state, replay events through the fixed logic to regenerate correct state.
- Snapshots — for entities with thousands of events, periodic snapshots cache the state at a point in time, allowing replay to start from the snapshot rather than event zero.
Complementing CQRS: Event Sourcing and CQRS are a natural pairing. Every event written to the write-side event store is also published to subscribers that update one or more denormalised read projections (the CQRS query side). Each projection can be an independent view optimised for a specific consumer: a mobile summary, a warehouse pick list, an analytics fact table. When a projection's logic changes, it can be rebuilt by replaying the complete event history.
More Related questions...