In this lesson, you will learn how to shift from storing the "current state" of an object to storing the history of all changes that led to that state.
Rethinking State Storage
In traditional CRUD applications, we typically update a database row (e.g., SET Balance = 150). When we do this, we lose the information about why the balance changed. Event Sourcing solves this by treating the application state as a derivative of a sequence of immutable events. Instead of saving the state, we append an Event to an append-only store (the "Event Store").
Reconstructing the Domain State
To get the current state of an entity, we replay the sequence of events from the beginning. If an account starts with 0 and we process an AccountOpened event, then a FundsDeposited event, and finally a FundsWithdrawn event, we calculate the current balance by folding these events over an object.
public class BankAccount {
public decimal Balance { get; private set; }
public void Apply(object @event) {
switch (@event) {
case AccountOpened e: Balance = 0; break;
case FundsDeposited e: Balance += e.Amount; break;
case FundsWithdrawn e: Balance -= e.Amount; break;
}
}
}
// Reconstructing state
var history = eventStore.GetEventsFor(accountId);
var account = new BankAccount();
foreach (var e in history) {
account.Apply(e);
}
Why use this with Background Workers?
Because these events are immutable, they serve as a perfect source of truth for background workers. If a worker needs to update a read-model or trigger a notification, it doesn't need to query the state; it simply "watches" the event stream. This ensures that your background services remain decoupled from the primary domain logic while staying perfectly synchronized through the stream of facts.
Since we are capturing "what happened" rather than "what is," we gain a complete audit log by default. You can replay these events to recreate the state at any point in time, which is invaluable for debugging or migrating data models.
Key Takeaway: Event Sourcing shifts the architectural focus from the current state to an immutable, append-only log of domain events that act as the single source of truth.