What Is Event Sourcing - and When a Plain CRUD Table Is the Right Answer

Event sourcing is a persistence pattern where the record of truth is an append-only log of everything that happened, not a table of how things currently are. When someone asks what is event sourcing, the short answer is: you store the facts and compute the state, instead of storing the state and throwing the facts away.

The problem it exists to solve is information loss on update. UPDATE accounts SET balance = 400 WHERE id = 7 tells you the balance is 400. It does not tell you that it was 500, that a withdrawal of 100 was authorised by a batch job at 03:12, and that a second attempt was rejected. In most systems that history is interesting right up until an auditor, a customer dispute, or a corrupted-data incident makes it essential - and by then it is gone.

This page covers the mechanism, the situations where the tradeoff is clearly worth it, and - at length - the much larger set of situations where a normal table with an updated_at column is the correct engineering decision. Two architects in hard hats working on a blueprint indoors, highlighting teamwork.

ConceptEvent Sourcing (ES)
Where it sitsPersistence and domain modelling - sits underneath your domain layer, replacing the write side of your data store
In one sentenceInstead of storing current state and overwriting it, you store an immutable, ordered log of the events that happened and derive current state by replaying them.

The 60-Second Answer

What it does: stores each change as an immutable event appended to a per-entity stream. Current state is a fold over that stream; query-shaped tables are projections built by reading it.

The one problem it solves: your write model stops destroying information. Any question about how a value got the way it is, or what it looked like at some past moment, becomes answerable from the data you already have.

The one cost it adds: you now maintain two models (the event log and every read model), and the log is a permanent contract. Fixing a badly designed event is not a migration - it is a versioning exercise you live with for the lifetime of the system.

Event sourcing vs CRUD in one line: CRUD optimises for the question "what is true now", event sourcing optimises for "how did this become true". Pick based on which question your business actually asks.

How It Actually Works

1. The append-only log is the system of record

Facts in, nothing overwritten

Every change is written as an event - a past-tense fact with a payload: MoneyDeposited, OrderShipped, AddressCorrected. Events are grouped into streams, usually one stream per entity instance (account-7, order-91f3), and each event gets a monotonic position within its stream.

Nothing in the log is ever updated or deleted in normal operation. The store only supports append and read-forward. That single constraint is what gives you the audit trail, the time travel, and the ability to build a read model you did not think of two years ago.

⚠️ In production — The stream is a storage boundary and a consistency boundary at the same time. If you pick streams that are too coarse (all-orders) you serialise every write in the system; too fine (order-line-4) and you can no longer enforce an invariant that spans the lines. Getting stream granularity wrong is the mistake that is most expensive to undo, because it is baked into every event you have already written.


2. A write is a command that gets validated, then produces events

Commands decide, events record

The write path is: load the entity's events, fold them into state, validate the incoming command against that state, and emit zero or more events. WithdrawMoney is a request that can be rejected; MoneyWithdrawn is a fact that cannot.

This split matters because validation is the only place where business rules live. Once an event is appended, every downstream consumer treats it as true without re-checking it.

⚠️ In production — Decision logic must be pure and must depend only on folded state, never on the clock, a random number, or a call to another service. The moment a handler reads now() or a current exchange rate, replaying the stream produces a different answer than the original run - and you have lost the one property you paid for.


3. Current state is a fold over the stream

Replay the facts, compute the answer

There is no row holding the balance. You get it by reducing the event list through an apply function - the same function used on the write path and in tests.

const state = events.reduce(apply, { open: false, balance: 0 });

function apply(state, event) {
  switch (event.type) {
    case 'AccountOpened':   return { ...state, open: true };
    case 'MoneyDeposited':  return { ...state, balance: state.balance + event.amount };
    case 'MoneyWithdrawn':  return { ...state, balance: state.balance - event.amount };
    case 'AccountClosed':   return { ...state, open: false };
    default:                return state;
  }
}

The default: return state case is load-bearing: it is what lets an old version of the code tolerate events it has never seen.

⚠️ In production — Replay cost is linear in stream length, and some streams grow without bound - a long-lived account, a chat room, a device. A system that is fast in staging with 20 events per stream can fall over in year three with 400,000. You need a plan for long streams before you ship, not after.


4. Snapshots bound the replay cost

A cached fold with a version number

A snapshot is the folded state stored alongside the version it was computed at. Loading becomes: read the snapshot, then read only the events after that version and fold those.

Snapshots are strictly a cache. Deleting all of them must leave the system correct, only slower. If a snapshot is ever the only place a piece of state exists, you are no longer event sourced - you are running a CRUD store with extra steps.

⚠️ In production — Snapshots are serialised state, which means they are coupled to your state shape, not your event shape. Change a field on the state object and every stored snapshot is now subtly wrong unless you invalidate the whole set. The safe operational rule is to tag snapshots with a schema identifier and discard them wholesale on deploy rather than trying to migrate them.


5. Reads come from projections, not from the log

Queries never touch the stream

Nobody runs reporting queries over an event log. You subscribe to the stream and write projections - ordinary tables, documents, or search indexes shaped exactly like the queries you need.

-- read model: one row per order, maintained by a projector
UPDATE order_summary
   SET status = 'shipped', shipped_at = $1
 WHERE order_id = $2;

Because projections are derived, they are disposable: drop the table, replay from position zero, and you have a new read model with full history. That is the capability people actually buy event sourcing for.

⚠️ In production — Projections are asynchronous, so the read model lags the write. Your UI will do a POST then an immediate GET and see stale data - every event-sourced system hits this in the first week. The fixes (return the new state from the command, poll until the projection catches up, or pin the user to a version) are all work you must budget for. Also: each projector needs its own stored position, and rebuilds need to be runnable without downtime, which usually means building into a second table and swapping.


6. Concurrency is handled by expected stream version

The append fails if someone else wrote

Two concurrent withdrawals must not both pass a balance check. The mechanism is optimistic concurrency on the stream: you remember the version you folded from and tell the store to reject the append if the stream has moved on.

// shape common to event stores, whatever each one names the argument
const { version, state } = await load('account-7');   // version = 41
const events = decide(state, command);
await append('account-7', events, { expectedVersion: version });
// conflict -> reload, re-decide, retry

This gives you serialisability per stream without a lock, which is why stream granularity and invariant granularity have to match.

⚠️ In production — Retry-on-conflict is only safe if decide is pure and the command is idempotent at the edge. Include a client-supplied command id in event metadata and check it on replay, otherwise a retried HTTP request after a timeout appends the same withdrawal twice - and unlike a CRUD bug, you cannot delete the row afterwards.


7. Events are immutable, so evolution means versioning

You can never fix an old event

Events written last year were written by last year's code and are still in the log. So the schema rule is: add optional fields, never repurpose a field, never change the meaning of an existing one. Breaking changes become a new event type or an explicit version marker.

{ "type": "OrderPlaced", "v": 2, "orderId": "91f3", "currency": "EUR", "lines": [] }

The usual handling is an upcaster at the read boundary: a function that takes a v1 event and returns the v2 shape (filling the currency that v1 did not record), so the rest of the code only ever sees the current version.

⚠️ In production — Your upcasters never go away. Five years in, the deserialisation path is a chain of translations nobody remembers the reason for, and each one encodes an assumption about old data that can be wrong. Write the upcaster and the comment explaining the original defect in the same commit, with a test that pins a real archived payload.


8. Correction and deletion are events too

Compensate, don't erase

A wrong event is not edited. You append a compensating event - PaymentReversed, AddressCorrectionApplied - and the fold produces the right state. This matches how accounting has always worked, and it means the log explains the mistake as well as the fix.

The exception is legally mandated erasure. The common pattern is to keep personal data out of events entirely and reference it by key, or to encrypt per-subject payloads with a key you can destroy, which makes those events permanently unreadable while leaving the stream structurally intact.

⚠️ In production — Decide the erasure strategy before the first production write. Retrofitting it means rewriting history - a full stream-by-stream copy with transformation, coordinated with every projection and every downstream consumer. Teams that skip this discover it when the first deletion request arrives, and the only remaining options are all bad.

Spacious modern library archive with rows of wooden drawers for document storage. ## Where You Meet It
  • A payments ledger. Balances are not a stored number but a fold over Authorised, Captured, Refunded, ChargedBack events. When a customer disputes a charge nine months later, support reconstructs exactly what the system knew at each step, and the reversal is an appended event rather than an adjustment that hides the original error. This domain is already event-shaped on paper, which is why it is the least controversial fit.
  • Order fulfilment across warehouse, payment, and shipping. The order's stream records OrderPlaced, StockReserved, ReservationExpired, PartiallyShipped. The operations team's questions are nearly all historical - why did this order sit for two days, which reservation lapsed - and in a CRUD model those answers live only in whatever got logged. Here they are the data.
  • A regulated workflow: insurance underwriting, clinical records, loan decisioning. The regulator does not ask what the policy says today; it asks who changed what, on what basis, and what the decision inputs were at the time. Event sourcing makes that a query instead of a forensics project across application logs with mismatched retention.
  • Behavioural analytics that nobody specified up front. Because CartItemRemoved was recorded as a fact, the growth team can build a projection of removal patterns two years after the code was written - without a migration, and with full history. In a CRUD cart, the row was simply updated and that data never existed.

When You Actually Need It

  • Someone already built a history or audit table beside your main table, and it has drifted - rows that disagree with the entity they describe, or gaps where a code path forgot to write. That drift is the signal that your real record of truth wants to be the log.
  • Domain experts habitually speak in past-tense facts ("the policy was endorsed", "the shipment was short-picked") and your schema has flattened all of them into a status column that loses the distinctions they care about.
  • The business needs backdated correction with recomputation: a rate was wrong for three weeks, and fixing it means re-deriving everything downstream rather than overwriting a total.
  • You are asked temporal questions - "what did we believe was true at month-end" - and currently answer them from warehouse snapshots or, worse, by reasoning about logs.
  • The same writes must feed several genuinely different read shapes (transactional UI, reconciliation report, search, ML features), and keeping them in sync from one mutable table has already caused incidents.
  • You have a hard invariant on a single entity under concurrent writes (no overdraft, no double-booking of one seat) and need conflicting writes rejected with a reason, not last-write-wins.

When You Don't

  • Your application is CRUD and nobody has ever asked how a value got that way. A single table plus updated_at is the correct answer. If you later want history, add a history table written by a trigger, or use your database's temporal/system-versioned table feature - a fraction of the complexity and no eventual consistency.
  • You only want an audit trail. Then build an audit trail: an append-only audit table, or change data capture off the database log into a warehouse. You get the who-changed-what record without splitting your write and read models or signing up for schema versioning forever.
  • The data has no meaningful per-change history: session state, caches, device last-seen timestamps, computed aggregates, latest sensor reading. Each change makes the previous one worthless, so overwrite it. A log here is pure cost - storage, replay time, and a retention policy you will have to invent.
  • Reads must reflect writes immediately and you cannot change the UX. Projection lag is intrinsic, not a tuning problem. If a user must POST then immediately GET authoritative data on a different screen, keep synchronous state - or accept that you will build read-your-own-writes plumbing on every endpoint.
  • Below the point where it carries its own weight: if you cannot name three past-tense events a domain expert would recognise, if one team owns the whole service, and if nobody has ever filed a ticket asking why a field changed - it is premature. Build the CRUD version; the domain will tell you if it needs events.
  • Only part of your system is event-shaped. Do not convert the application. Event source the one aggregate where history is the product (the ledger, the policy, the order) and leave user profiles, settings, and reference data as ordinary tables. Whole-app event sourcing is the single most common way teams end up rewriting back to CRUD. An open ledger book on a dusty floor, evoking a sense of history and abandonment.

What People Get Wrong

"Event sourcing means putting Kafka in front of the database."

A log-structured message broker and an event store solve different problems. An event store needs millions of small independently-addressable streams, optimistic concurrency on append, and the ability to read any single stream from the beginning forever. Brokers are built for a bounded number of high-throughput topics with retention and compaction - both of which actively delete the history replay depends on. A broker is an excellent way to distribute events after the fact; it is a poor system of record on its own, and plain relational tables with an append-only discipline are a perfectly respectable event store.

"You get an audit log for free."

You get a change log for free. An audit log also needs actor, authorisation context, request id, and intent - and those are metadata you have to decide to capture on every event. Domain events are also modelled for business meaning, not for compliance, so an auditor's question can still require inference. Capture the metadata from day one; adding it later means your oldest records are the ones that will be questioned and the ones that lack it.

"If there is a bug, you can just replay and fix it."

Replay rebuilds projections, not events. If the write-side logic was wrong when the event was appended, the wrong fact is in the log permanently, and the fix is a compensating event plus code that tolerates the historical mistake. Replay also does not undo side effects: emails sent, payments taken, webhooks fired. Projectors must be idempotent and must not perform external actions, or a routine rebuild becomes an incident.

"Event sourcing requires CQRS and microservices."

Event sourcing almost forces a separate read model, so you end up with something CQRS-shaped whether you call it that or not - but that can be two modules and two tables inside one service and one database. CQRS without event sourcing is common and often sufficient. Distributed services are an orthogonal decision, and adopting all three at once is how teams conclude the pattern is unworkable when the real problem was the simultaneity.

Why It Was Built This Way

Update-in-place was not chosen because it models the world well. It was chosen because for decades storage was the scarce resource and the only question anyone asked a database was "what is true now". Overwriting a row is the cheapest possible way to answer that question, and the cost - destroying the explanation of how the value got there - was invisible because nobody was billed for it. Event sourcing inverts the assumption: storage is cheap, derived views are cheap to rebuild, and the expensive thing is information you no longer have.

What got traded away is real and it is paid every day, not once at adoption. You lose the single model: current state is no longer queryable in the store that holds the truth, so every question needs a projection somebody built in advance. You lose cheap schema change, because the log is a permanent public contract - in a CRUD system a bad column name is a migration, here it is an upcaster your successors maintain. And you take on eventual consistency between write and read, which leaks into product decisions about what a user sees immediately after acting. That is the honest bill: a permanent increase in moving parts, in exchange for never losing a fact.

The reason the pattern is more than a fashion is that your database already does this internally. The write-ahead log is the authoritative append-only sequence of changes; the heap and the indexes are projections of it; crash recovery is replay; a read replica is a projector subscribing to the stream; a backup plus WAL archive is point-in-time replay. Event sourcing is the decision to stop hiding that structure inside the storage engine and lift it to the domain layer, where the events are named in your business's vocabulary instead of in pages and tuples. That is also the sharpest test of whether you need it: the engine's log is invisible because nobody asks questions of it. If nobody asks historical questions of your domain either, leave the log where it is.

Related Briefs

What to Read Next

  • what is CQRS and do you need it with event sourcing
  • change data capture vs event sourcing for audit trails
  • eventual consistency and read-your-own-writes in read models

Event sourcing is the right call when history is part of the product - when the business routinely asks how a value came to be, and the answer currently lives in application logs or a drifting audit table. It is the wrong call when current state is the whole question, because you are paying for two models, permanent schema contracts, and projection lag to buy an answer nobody needs. If you are genuinely unsure, event source the one aggregate where the history matters and keep everything else in tables; that decision is cheap to extend and cheap to abandon, which is more than can be said for converting the whole system.

댓글

이 블로그의 인기 게시물

What Is a Message Queue - and When You Actually Don't Need One

What Is a Bloom Filter - and When You Actually Don't Need One

When to Use GraphQL Over REST API - and When REST Is Still the Right Call