Event Sourcing — pattern where current state is derived from a sequence of immutable events stored in an event log. Instead of UPDATE user SET balance = 100, write BalanceCredited {amount: 100}. Benefits: full audit trail, time-travel queries, state rebuild. Costs: tricky schema migrations, eventual consistency, "upcasting" old events as schemas evolve.
Below: details, example, related terms, FAQ.
Free online tool — HTTP header checker: instant results, no signup.
// Events append
EventStore.append('order-123', [
OrderCreated { customerId, items }
OrderConfirmed { timestamp }
OrderShipped { trackingNumber }
])
// Rebuild state by replaying events
state = fold(events, initialState, applyEvent)Event Sourcing is a design pattern that revolves around the idea of persisting the state of a system as a series of events. Each event represents a state change, and rather than storing the current state directly, you store a log of these events. This approach offers several advantages:
However, Event Sourcing also introduces complexities, such as managing schema evolution and ensuring eventual consistency. It is essential to understand these aspects to effectively implement Event Sourcing in your applications.
Implementing Event Sourcing requires a clear understanding of how to capture and store events. Below is a practical example illustrating how to use Event Sourcing in a simple banking application:
class Account {
private List events = new ArrayList<>();
public void credit(int amount) {
events.add(new BalanceCredited(amount));
}
public void debit(int amount) {
events.add(new BalanceDebited(amount));
}
public int getBalance() {
int balance = 0;
for (Event event : events) {
if (event instanceof BalanceCredited) {
balance += ((BalanceCredited) event).amount;
} else if (event instanceof BalanceDebited) {
balance -= ((BalanceDebited) event).amount;
}
}
return balance;
}
} In this example, the Account class maintains a list of events and uses them to compute the current balance. Each time a credit or debit occurs, an event is created and added to the log. This allows you to reconstruct the account's state at any point by iterating through the events.
While Event Sourcing provides significant benefits, it also comes with its share of challenges that developers must navigate:
Addressing these challenges requires careful planning and a robust architecture to ensure that the advantages of Event Sourcing are realized without compromising system integrity.
No, but often combined. ES gives write-side, CQRS separates read and write models.
Upcasters: at read time, transform old event versions to new schema. Or versioned event types (OrderCreated_V1, V2).
Events grow linearly. For long-lived streams — snapshots every N events. Or archive old events to cold storage.
Free plan — 10 monitors, checks every 5 min, no card required. Upgrade for 1-minute interval and multi-region monitoring.