Mastering Async Event Sourcing
In this lesson, you will learn how to treat your system's history as the primary source of truth by deriving current state from an asynchronous, append-only event log.
The Problem with "Final State"
In traditional applications, we often save the current state of an object (e.g., user.balance = 50) directly to a database. If something goes wrong or we need to know why the balance changed, we lose that context. Async Event Sourcing flips this: instead of saving the state, we save the events that lead to the state (e.g., MoneyDeposited, MoneyWithdrawn).
Building an Append-Only Log
Imagine an array that only grows. In an asynchronous environment, we treat every action as a message that we append to a database. To find out the current balance, we "rehydrate" the state by replaying every event in order.
// A simple event log representation
const eventLog = [
{ type: 'DEPOSIT', amount: 100 },
{ type: 'WITHDRAW', amount: 20 },
{ type: 'DEPOSIT', amount: 50 }
];
async function calculateBalance(events) {
let balance = 0;
for (const event of events) {
// We simulate async processing of each event
await new Promise(resolve => setTimeout(resolve, 10));
if (event.type === 'DEPOSIT') balance += event.amount;
if (event.type === 'WITHDRAW') balance -= event.amount;
}
return balance;
}
// Result: 130
Why Do This?
Because the event log is append-only, it is naturally idempotent and safe from overwriting errors. You can audit every action taken in the system by looking at the log. Even if the application crashes, your system state is simply the result of re-processing that immutable history. You aren't just storing data; you are storing the intent of your users over time.
By keeping the log as your source of truth, you gain a perfect audit trail and the ability to travel back in time to inspect exactly what the system looked like at any point in its lifespan.
Key Takeaway: Rather than storing the current state, store the sequence of asynchronous events that created it; the state is simply the byproduct of replaying that history.