blog.dopana

Back

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 3 apples. When your mother gives you 2 more apples, you erase 3 with an eraser and write 5. Anyone walking into the room only sees 5. 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:
    1. Day 1: Received 3 apples from mom (+3)
    2. Day 2: Ate 1 apple (-1)
    3. 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:

DimensionTraditional CRUD ModelEvent Sourcing Model
Storage StrategyStores only a snapshot of the current state (Current State).Stores the full chronological stream of business facts (Event Stream).
Database OperationsCREATE, READ, UPDATE, DELETE. Overwrites historical values.Append-only: Only INSERT and SELECT. No destructive UPDATE or DELETE.
Data Stored in DBBalance: $5,0001. AccountOpened (+$0)
2. MoneyDeposited (+$10,000)
3. MoneyWithdrawn (-$3,000)
4. MoneyWithdrawn (-$2,000)
Error HandlingExecutes an UPDATE directly over the old balance.Appends a compensating event (e.g., TransactionReversed).
Information LossHigh. 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:

Read Model (Projections)Event DistributionWrite ModelEmits EventsCommand(Request Action)Command Handler / AggregateEvent StoreAppend-only LogEvent Bus / StreamProjector(Event Listener)Read DatabaseSQL / Elastic / RedisClient Query
  1. Event:
    • Represents an immutable fact that took place in the domain in the past.
    • Named using past-tense verbs: AccountOpened, MoneyDeposited, OrderPlaced, ItemShipped.
  2. 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.
  3. 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.
  4. 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:

6. Trade-offs: Pros and Cons#

Advantages#

  1. 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.
  2. High Write Performance: Since the database only performs sequential inserts (append-only), write operations avoid complex locking and table joins.
  3. 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.
  4. Resilient Data Modeling: You can introduce entirely new projections years later and re-stream historic events to backfill historical analytics.

Disadvantages#

  1. Architectural Complexity: Requires a fundamental shift from state-oriented thinking to event-driven modeling.
  2. Eventual Consistency: Projections update asynchronously, meaning read queries might observe a momentary lag behind committed writes.
  3. 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#