A customer opens a banking app and sees a balance that looks wrong. A support engineer can see the current total, but cannot immediately answer the harder question: which deposits, withdrawals, fees, and corrections produced it?
Or consider an online order that appears to have skipped from “paid” to “shipped.” Was it cancelled and reinstated? Did a warehouse rule change? Did a message arrive twice? A database row containing only the latest status cannot tell the whole story.
Most applications are built to store current facts: a user’s current address, a cart’s current contents, an account’s current balance. That model is simple and often exactly right. Yet some systems need to retain the sequence of decisions and changes that led to those facts.
Event sourcing is an architectural approach built around that sequence. Rather than treating history as an optional audit log, it makes a durable record of domain events the primary source of truth.
🧾 The familiar “current state” model
In a conventional application, a database table commonly holds one row per entity. Updating an order might replace status = paid with status = shipped. The old value is gone unless another feature preserved it.
This is often called state-based persistence. The database answers questions such as “What is the order status now?” efficiently, which suits many business systems.
🎞️ Event sourcing stores the story
With event sourcing, the application records facts that happened: OrderPlaced, PaymentAuthorized, and OrderShipped. Each event is appended to an ordered stream associated with an order.
The present state is then derived by replaying those events in order. An order is shipped not because a field happens to say so, but because its recorded history includes an OrderShipped event after the relevant earlier events.
🧠 An event is a business fact
An event describes something meaningful in the problem domain that has already occurred. Good event names are usually written in the past tense because they represent facts, not instructions.
ItemAddedToCart is an event. AddItemToCart is usually a command: a request asking the system to attempt an action. That distinction prevents a great deal of confusion.
📬 Commands, decisions, and events
A typical flow has three stages. A command arrives, domain rules decide whether it is valid, and one or more events are recorded if the decision succeeds.
- Command: “Withdraw $50 from this account.”
- Decision: Check authorization, account status, and available funds.
- Event: “$50 was withdrawn from this account.”
A rejected command normally produces no business event. It may be logged separately for operational diagnostics, but it is not a fact that changed the domain state.
🏦 A small bank-account example
Imagine a hypothetical account stream containing AccountOpened, MoneyDeposited, MoneyWithdrawn, and MonthlyFeeCharged. Replaying the amounts produces the balance.
This resembles a ledger. The balance is useful, but it is a result derived from entries. If a customer disputes a fee, the system can inspect the event that recorded it and the context captured with it.
🧮 Rehydrating an aggregate
An aggregate is a domain object that protects a set of related business rules. In event-sourced systems, an aggregate is rebuilt, or rehydrated, by applying its past events.
For example, an order aggregate applies OrderPlaced to establish its items, then PaymentCaptured to mark payment complete. It uses that reconstructed state to decide whether a new command, such as shipping the order, is allowed.
🔒 Why business invariants matter
An invariant is a rule that must remain true, such as “an order cannot ship before payment is accepted” or “a seat cannot be sold twice.” Event sourcing does not remove these rules; it makes their decision point explicit.
The aggregate checks the proposed command against its event-derived state and emits new events only when the rule holds. This is why event streams should not be treated as an unrestricted list that any service can append to.
➕ Appending is different from updating
Traditional persistence changes existing records. Event sourcing normally appends new records and avoids changing old ones. If an error must be corrected, the system usually records a compensating event rather than silently rewriting history.
For instance, PaymentRefunded is more informative than editing an old payment amount. The history then shows both the original business action and the corrective action.
⏱️ Order gives events meaning
The sequence matters. SubscriptionCancelled before SubscriptionActivated means something different from the reverse. Event stores commonly guarantee ordering within one stream, such as one order or one account.
Ordering across unrelated streams is more complicated in distributed systems. A global timestamp alone is not a perfect proof of causal order because machines, networks, and clocks do not behave perfectly.
🧷 Versions prevent lost updates
Two users may issue valid-looking commands based on the same earlier state. For example, two ticket requests may both see one remaining seat. The application must ensure only one can reserve it.
Event stores typically support optimistic concurrency: append events only if the stream is still at the version the writer read. If another writer appended first, the second attempt fails and must reload, reconsider, or report a conflict.
📖 Replay turns history into state
Replaying means reading a stream from its beginning and applying every event. This can recreate state after a restart, investigate a defect, or calculate a newly needed view of past activity.
Replay works best when event handlers are deterministic: given the same ordered events, they produce the same result. Avoid making the result depend on the current time, random values, or remote calls unless those inputs were captured deliberately.
⚡ Snapshots reduce replay cost
A stream with a long history may take noticeable time to replay. A snapshot stores a derived state at a known event version, allowing the application to load the snapshot and apply only newer events.
A snapshot is a performance optimization, not the authoritative history. It can be rebuilt from events, so its format may be changed or discarded more safely than the event stream itself.
📊 Projections create useful read models
Users rarely need raw event streams. They need screens and reports: current account balances, orders awaiting shipment, daily sales totals, or a customer timeline. A projection consumes events and builds a query-friendly read model.
One event stream can support many projections. The same order events might feed a customer-facing order page, a warehouse picking queue, and an internal revenue report without forcing one database table to serve all purposes.
🔀 CQRS is related, not required
Command Query Responsibility Segregation, usually shortened to CQRS, separates the model used to make decisions from the model used to answer queries. Event sourcing often pairs naturally with it because projections make specialized read models easy to build.
But the terms are not synonyms. A system can use event sourcing with a simple query model, and a system can use CQRS without storing events as its source of truth.
🕒 Eventual consistency changes the user experience
When a projection is updated asynchronously, a command may succeed before the read model reflects it. A customer might submit an order and briefly see an older order list.
This is eventual consistency. It is manageable when the product communicates progress clearly, but it can be unacceptable for interactions requiring immediate confirmation from the same view. Designers must decide where a short delay is tolerable rather than treating it as an invisible infrastructure detail.
🔍 Auditability is a practical advantage
A detailed history can make support, reconciliation, and investigation easier. Rather than inferring why a value changed from database backups or application logs, teams can inspect the recorded domain facts.
That does not automatically satisfy regulatory, legal, or compliance requirements. Those requirements vary by context and may demand retention controls, access restrictions, signatures, or other evidence beyond an event stream.
🔄 Rebuilding views enables change
Requirements evolve. A team may later need a report grouping orders by the first shipping region selected, or a fraud-monitoring view that did not exist when the system launched.
If the required facts exist in historical events, a new projection can often be built by replaying them. This is powerful, but only if events contain stable business information rather than vague technical messages with missing context.
📨 Events can integrate services
Published domain events can tell other parts of a system that something happened. An OrderShipped event may trigger customer notification, inventory updates, or analytics processing.
Integration requires care. A consumer may receive a message more than once, receive it later than expected, or fail temporarily. Consumers should therefore be idempotent: processing the same event again should not create a duplicate shipment email or duplicate charge.
🧰 The outbox solves a common publication gap
A dangerous failure mode occurs when an application saves a business change but crashes before publishing the corresponding message. The database says the order shipped, while downstream services never learn about it.
An outbox pattern records the outgoing message durably in the same transaction as the business change, then a separate process publishes it reliably. Event-sourced systems may still need this pattern when sending events to external brokers or services.
🧬 Event schemas must evolve carefully
Events may outlive the code that created them. Renaming a field, changing a meaning, or removing a value can break old streams and projections during replay.
Prefer additive changes when possible. Consumers can tolerate an optional new field more easily than a removed or reinterpreted old field. When a major change is unavoidable, teams may use versioned event types, translation during reading, or migration strategies suited to their storage and retention needs.
✍️ Name events for the domain, not the database
CustomerEmailUpdated may be meaningful if email changes are a business event. CustomerRowUpdated is not: it describes a storage operation without explaining what occurred.
Good events communicate intent to future developers and nontechnical stakeholders. Capture relevant facts at the time of occurrence, such as the item, quantity, currency, actor, or reason code, while avoiding unnecessary copies of sensitive information.
🛡️ Immutability does not mean no privacy work
Appending history creates tension with data deletion and correction obligations. Storing personal data directly inside immutable events can make later removal difficult or inappropriate.
Common approaches include keeping sensitive data in separate systems, storing references rather than full values, encrypting selected fields with carefully managed keys, and designing retention policies early. The right approach depends on the data, jurisdiction, threat model, and organizational obligations; event sourcing is not a shortcut around them.
📦 Event stores are not ordinary logs
Application logs are primarily diagnostic records for operators. They may be sampled, unstructured, short-lived, and full of technical detail. Domain events are business records that application behavior relies upon.
Likewise, a message queue is not automatically an event store. Many queues retain messages only temporarily, while an event store must preserve ordered streams, support expected-version writes, and provide durable reads appropriate to the domain.
🧪 Testing becomes more direct
Event-sourced domain tests can state a useful business narrative: given these past events, when this command arrives, expect these new events. This focuses tests on rules and observable outcomes rather than private implementation details.
Given: AccountOpened, MoneyDeposited(100) When: WithdrawMoney(30) Then: MoneyWithdrawn(30)
Also test invalid commands, concurrency conflicts, projection replay, and duplicate delivery. A happy-path event test alone does not prove that a distributed workflow behaves safely.
🧯 Failure recovery needs operational discipline
Projections can fail because of bad data, a software bug, or an unavailable dependency. Teams need a way to pause consumers, inspect the failing event, fix the issue, and resume or rebuild safely.
Monitor projection lag, failed messages, stream append conflicts, and replay duration. A system that can theoretically rebuild a view is not operationally resilient if rebuilding takes too long or its operators cannot determine what went wrong.
💸 Storage and complexity are real costs
Keeping every meaningful change consumes storage and demands retention planning. More significantly, event sourcing introduces schema evolution, projection management, asynchronous behavior, and unfamiliar debugging workflows.
It can also make simple questions harder when a projection is missing or stale. The answer is not to avoid projections, but to recognize that the architecture exchanges some write-side simplicity for history and flexible read models.
🚫 When a normal database is the better choice
Many applications do not need an event stream as their source of truth. A profile page, internal content editor, configuration screen, or simple inventory catalogue may be clearer and cheaper to maintain with conventional state updates plus an audit trail where needed.
Choose event sourcing because the business benefits from reconstructable history, rich domain behavior, and independently evolving views—not because it is fashionable or because every update sounds like an event.
🧭 Good candidates have meaningful history
Event sourcing is worth considering when the sequence of changes affects business meaning. Financial ledgers, reservations, workflows with approvals, logistics tracking, insurance claims, and complex subscriptions are common examples.
Look for questions like “How did we get here?”, “What was known at that point?”, or “Can we derive a new view from past decisions?” Repeatedly needing trustworthy answers is a stronger signal than raw transaction volume.
🪜 Start with one bounded problem
A bounded context is a part of the business with a clear vocabulary and rules. Starting event sourcing inside one such area limits the impact of new concepts and lets the team learn from a real use case.
Define commands, invariants, event names, stream boundaries, projections, and failure handling before expanding. Avoid converting an entire existing database into events merely to adopt the pattern; historical imports often contain ambiguous state with no reliable explanation of past intent.
🗺️ A practical design checklist
Before committing, ask concrete questions about the domain and operations:
- Which decisions require a complete, trustworthy sequence of facts?
- What is the aggregate boundary that enforces each critical rule?
- Which read models do users need immediately, and which may lag?
- How will events evolve, be secured, and be retained?
- How will consumers handle duplicates, failures, and replays?
- Who can inspect or append to each stream?
If these questions have vague answers, a smaller prototype or a simpler persistence model may be the safer next step.
🎯 The core principle: preserve decisions, derive views
Event sourcing treats the sequence of business facts as durable knowledge. Current state remains valuable, but it becomes a view that can be calculated from the recorded events rather than the only surviving representation of reality.
That shift is most useful where history explains present decisions, where new perspectives are likely, and where rules must be enforced against a well-defined past. It is not free: success depends on careful boundaries, clear event design, resilient projections, and honest treatment of consistency and privacy trade-offs.
Store every change when the story of those changes is itself part of what your software must know. Used selectively, event sourcing turns history from an afterthought into a dependable part of the model. ⚙️📚
