What is Event Sourcing?

Topic: microservices, Data Management. Level: Hard.

Answer

Instead of storing current state, Event Sourcing stores the full, immutable, ordered sequence of state-changing **events**. Current state is derived by replaying events. Benefits: a complete audit log, time-travel/debugging, natural fit for EDA, and the ability to build new projections retroactively. Costs: querying current state requires folding events (mitigated by snapshots and CQRS read models), schema/versioning of old events, and eventual consistency. The event store is append-only; events are never mutated or deleted. ```java // State is a fold over past events, not a stored row class Account { long balance; void apply(Event e) { if (e instanceof Deposited d) balance += d.amount(); if (e instanceof Withdrawn w) balance -= w.amount(); } static Account rehydrate(List<Event> history) { Account a = new Account(); history.forEach(a::apply); // replay to rebuild current balance return a; } } ```