Event Sourcing: Architecture and Design Pattern
Explore Event Sourcing: store state as an immutable sequence of events instead of direct DB updates. Compare CRUD vs Event Sourcing, CQRS, and code.
In traditional software development, most applications rely on the CRUD model (Create, Read, Update, Delete). Whenever application state changes—such as updating a customer’s address or adjusting a bank balance—we execute an UPDATE statement that overwrites the existing row in a database table.
However, this conventional approach has a major drawback: valuable historical context is lost forever. When a bank database shows an account balance of $5,000, it cannot tell you how that number came to be without relying on external, fragile audit logs.
This is where Event Sourcing comes in. Event Sourcing is a software design pattern where the current state of an application is not stored directly. Instead, the application state is dynamically reconstructed from an append-only stream of immutable business events recorded over time.
1. Explain Like I’m 10 (ELI5)#
Imagine you have a chalkboard and an accounting ledger notebook:
- CRUD is like a chalkboard: You write down that you have
3apples. When your mother gives you 2 more apples, you erase3with an eraser and write5. Anyone walking into the room only sees5. They have no idea how you got those 5 apples—did you buy them, receive them as gifts, or eat 1 from a previous batch of 6? - Event Sourcing is like an accounting ledger: You never use an eraser. Every time something happens in the real world, you write down a new immutable line:
- Day 1: Received 3 apples from mom (+3)
- Day 2: Ate 1 apple (-1)
- Day 3: Friend gave 3 apples (+3)
When you need to know how many apples you currently have, you calculate from the beginning: 3 - 1 + 3 = 5 apples! If on Day 2 you mistakenly recorded eating 2 apples instead of 1, you do not tear out the page. Instead, you record a corrective entry on the next line: “Adjustment: Returned 1 mistakenly deducted apple (+1)”.
[!NOTE] Instead of storing only the final result (Current State), Event Sourcing records all the individual steps that produced that result (Events).
2. CRUD vs. Event Sourcing: A Side-by-Side Comparison#
To illustrate the difference, consider how a bank account is managed in both architectures:
| Dimension | Traditional CRUD Model | Event Sourcing Model |
|---|---|---|
| Storage Strategy | Stores only a snapshot of the current state (Current State). | Stores the full chronological stream of business facts (Event Stream). |
| Database Operations | CREATE, READ, UPDATE, DELETE. Overwrites historical values. | Append-only: Only INSERT and SELECT. No destructive UPDATE or DELETE. |
| Data Stored in DB | Balance: $5,000 | 1. AccountOpened (+$0)2. MoneyDeposited (+$10,000)3. MoneyWithdrawn (-$3,000)4. MoneyWithdrawn (-$2,000) |
| Error Handling | Executes an UPDATE directly over the old balance. | Appends a compensating event (e.g., TransactionReversed). |
| Information Loss | High. Historical context is erased unless external audit tables are maintained. | Zero. Full, auditable system history is preserved permanently. |
3. Core Components of Event Sourcing#
A production-grade Event Sourcing architecture comprises the following foundational elements:
- Event:
- Represents an immutable fact that took place in the domain in the past.
- Named using past-tense verbs:
AccountOpened,MoneyDeposited,OrderPlaced,ItemShipped.
- Event Store:
- A dedicated database or append-only log optimized for sequential event writes.
- Serves as the authoritative Single Source of Truth (SSOT) for the entire system.
- Aggregate:
- The domain entity responsible for enforcing business rules and invariants.
- Its internal state is rehydrated by loading its historical events and running an
apply(event)reducer function.
- Projection (Read Model):
- Replaying thousands of events for every read query would degrade performance.
- Projections asynchronously listen to committed events and project pre-aggregated, read-optimized views into secondary databases (e.g., PostgreSQL, Elasticsearch, or Redis).
[!TIP] Snapshots for Fast Rehydration: For long-lived aggregates with thousands of events, you can periodically take a snapshot (e.g., every 100 events). When loading the aggregate, the system loads the latest snapshot and replays only subsequent events.
4. Why Event Sourcing Pairs with CQRS#
Event Sourcing is commonly implemented alongside CQRS (Command Query Responsibility Segregation):
- Write Side (Commands): Validates business logic against the aggregate and appends events to the Event Store. Write operations are blazing fast because they are simple sequential appends without heavy cross-table locking.
- Read Side (Queries): Decoupled from the write model. Projections denormalize events into query-friendly schemas tailored for specific user interfaces and search APIs.
5. Practical Implementation in TypeScript#
Here is an end-to-end runnable example demonstrating a bank account aggregate powered by Event Sourcing:
// 1. Define Domain Events
type AccountOpenedEvent = {
type: 'AccountOpened';
accountId: string;
owner: string;
timestamp: string;
};
type MoneyDepositedEvent = {
type: 'MoneyDeposited';
accountId: string;
amount: number;
timestamp: string;
};
type MoneyWithdrawnEvent = {
type: 'MoneyWithdrawn';
accountId: string;
amount: number;
timestamp: string;
};
type BankAccountEvent = AccountOpenedEvent | MoneyDepositedEvent | MoneyWithdrawnEvent;
// 2. Aggregate Root: Rehydrates state from event history
class BankAccount {
public id: string = '';
public balance: number = 0;
public owner: string = '';
// Rebuild state by replaying past events
public applyEvents(events: BankAccountEvent[]): void {
for (const event of events) {
this.mutate(event);
}
}
// Pure state transition function
private mutate(event: BankAccountEvent): void {
switch (event.type) {
case 'AccountOpened':
this.id = event.accountId;
this.owner = event.owner;
this.balance = 0;
break;
case 'MoneyDeposited':
this.balance += event.amount;
break;
case 'MoneyWithdrawn':
this.balance -= event.amount;
break;
}
}
// Execute command: validate invariant and produce new event
public withdraw(amount: number): MoneyWithdrawnEvent {
if (amount <= 0) {
throw new Error('Withdrawal amount must be greater than zero');
}
if (this.balance < amount) {
throw new Error(`Insufficient funds: Current balance is $${this.balance}, requested $${amount}`);
}
const event: MoneyWithdrawnEvent = {
type: 'MoneyWithdrawn',
accountId: this.id,
amount,
timestamp: new Date().toISOString()
};
this.mutate(event);
return event;
}
}
// 3. Simulate Event Store replay and balance verification
const eventHistory: BankAccountEvent[] = [
{ type: 'AccountOpened', accountId: 'ACC-001', owner: 'Alice', timestamp: '2026-09-01T08:00:00Z' },
{ type: 'MoneyDeposited', accountId: 'ACC-001', amount: 10_000, timestamp: '2026-09-01T09:00:00Z' },
{ type: 'MoneyWithdrawn', accountId: 'ACC-001', amount: 3_000, timestamp: '2026-09-02T10:00:00Z' },
{ type: 'MoneyWithdrawn', accountId: 'ACC-001', amount: 2_000, timestamp: '2026-09-03T11:00:00Z' }
];
const account = new BankAccount();
account.applyEvents(eventHistory);
console.log(`Account Owner: ${account.owner}`);
console.log(`Current Balance: $${account.balance.toLocaleString('en-US')}`); // $5,000typescript6. Trade-offs: Pros and Cons#
Advantages#
- Complete Audit Trail: Every business decision and data mutation is preserved with high fidelity. You can perform time-travel queries to view system state at any exact second in the past.
- High Write Performance: Since the database only performs sequential inserts (
append-only), write operations avoid complex locking and table joins. - Behavioral Analytics: By preserving every intermediate action (such as items added to and removed from a shopping cart), data teams can extract deep user intent and conversion funnels.
- Resilient Data Modeling: You can introduce entirely new projections years later and re-stream historic events to backfill historical analytics.
Disadvantages#
- Architectural Complexity: Requires a fundamental shift from state-oriented thinking to event-driven modeling.
- Eventual Consistency: Projections update asynchronously, meaning read queries might observe a momentary lag behind committed writes.
- Event Schema Evolution: As business requirements shift, handling schema updates across millions of historical events requires techniques like Upcasting or Event Versioning.
[!WARNING] Do not use Event Sourcing for simple CRUD apps or static content platforms. The architectural overhead and eventual consistency challenges are only justified when strict auditing, complex workflows, or temporal analysis are core requirements.
7. References#
- Event Sourcing: Event-Driven Architecture Under 5 Minutes ↗
- Event-Driven Architecture cho hệ thống sản xuất phản ứng ↗
- Event Sourcing là gì? - Viblo ↗
- Giải thích về Event Sourcing - Viblo ↗
- CQRS và Event Sourcing: Tách biệt đọc ghi và lưu trữ lịch sử sự kiện - FIT NEU ↗
- Domain-Driven Design with CQRS & Event Sourcing - VOZ ↗
- Event Sourcing vs Event Streams - Reddit Software Architecture ↗