Course contentsShow
← Node.js
Lesson 871 of 1,9808. Data Persistence and ORM IntegrationFree lesson

Event Sourcing Patterns

You will store the history of state changes as a sequence of events instead of current state.

In this lesson, you will learn how to shift your data strategy from storing only the "current state" to preserving the complete history of changes as an immutable stream of events.

Moving Beyond the "Current State"

In typical Node.js applications, we often save the final state of an object. If a user changes their email, we UPDATE the document in the database. With Event Sourcing, we never UPDATE or DELETE existing data. Instead, we append new "facts" to an append-only log.

Imagine a bank account. Instead of storing a balance: 100 field, we store a list of events:

  1. AccountCreated
  2. MoneyDeposited { amount: 150 }
  3. MoneyWithdrawn { amount: 50 }

The "current state" is simply the result of replaying these events in order. If you need to know the balance, you calculate it by starting at zero and applying the logic from each event.

Implementation in Node.js

In a NoSQL environment, your event collection might look like this:

// Event store schema (The Source of Truth)
const event = {
  aggregateId: 'user-123',
  type: 'EMAIL_UPDATED',
  data: { newEmail: 'new@example.com' },
  timestamp: new Date().toISOString()
};

db.collection('events').insertOne(event);

By storing these events, you gain a perfect audit trail for free. If you ever find a bug in your logic, you can "replay" the events through the fixed code to correct the historical state.

Why use this?

While it requires more computation to reconstruct state (which you can optimize using Database Projections), it provides an unassailable history of every action taken in your system. This makes debugging complex business processes much easier because you can see exactly why a document ended up in its current state, rather than just seeing the final result.

Key Takeaway: Event Sourcing transforms your database into a chronological ledger of events, where the current state is merely a projection derived from replaying the history of changes.