Summary#
Most databases store only the current state: the balance is 120. Event sourcing stores every change instead, as an append-only sequence of events (Deposited 100, Withdrew 30, Deposited 50), and computes current state by replaying them. The event store is the source of truth; state is derived. Replays get slow for long histories, so snapshots save state periodically. Reads are served from projections (also called read models): tables built by consuming the events and shaped for queries. CQRS (Command Query Responsibility Segregation) separates the write model that handles commands from the read models that answer queries, so each can be designed and scaled independently. Event sourcing and CQRS are often combined but are independent ideas. Both add significant complexity; use them where history, audit or very different read and write shapes justify it (ledgers, order history, trading), not for ordinary CRUD.
Why It Exists#
An UPDATE destroys information. When a row's status changes from "paid" to "refunded", you lose when it was paid, by whom and why, unless you also write audit tables, which drift from the real data. For a bank ledger, a trading system or a compliance-heavy workflow, the history is the data: you must answer "what was this account's balance on 3 March?" and "why?".
Separately, the shape that is good for writing (normalised, enforcing rules on one entity) is often bad for reading (dashboards, search, joined views across many entities). One model serving both ends up compromised.
Event sourcing keeps the full history as the primary record. CQRS gives reads and writes their own models. This page builds on Event-Driven Architecture.
How It Works#
State-oriented vs event-oriented storage, in depth#
Most systems are state-oriented: each row holds the latest value, and every update overwrites the previous one. An event-oriented system keeps the sequence of changes and treats the latest value as something computed from them. The difference sounds small, but it changes what questions you can answer.
What an update throws away. Take a shopping cart. A state-oriented table holds cart_id, items. A customer adds a phone, adds a case, removes the phone and checks out with only the case. The final row shows one item. The event log shows that the customer considered a phone and removed it, which is exactly the signal a recommendation or pricing team wants. Nobody thought to record "removed items" when the table was designed, but the event log captured it without anyone planning for it. This is the most practical argument for events: you keep information whose value you have not discovered yet.
The log as the primary record. Jay Kreps' 2013 essay "The Log: What every software engineer should know about real-time data's unifying abstraction" argued that an ordered, append-only log is the core abstraction under databases, replication and data integration. A database's write-ahead log is already an event log, and tables are a cached view of it. Pat Helland makes a similar point in "Immutability Changes Everything" (CIDR 2015): the log is the truth, and the database is a cache of a subset of the log. Event sourcing applies that idea at the application level, with business events instead of page writes.
Events as facts. An event records something that happened: MoneyDeposited {amount: 100}. It is not an instruction and cannot fail. That gives events a useful property: they are immutable and order-dependent, but never contradictory. A later event can reverse the effect of an earlier one (DepositReversed), but it cannot change the fact that the deposit was recorded. Accountants have worked this way for centuries: you never erase a ledger entry, you post a correcting entry.
A banking illustration. In a banking system, deposits, withdrawals and transfers are each recorded as events, and a transfer touches two accounts. With event sourcing, every transaction is stored, can be audited, and can be replayed. The bank can reconstruct any account's balance at any moment by replaying its events up to that moment. It can reverse a mistaken transaction with a compensating event, and it can process the same events in real time for fraud checks. A state-oriented design would need separate audit tables, history tables and change triggers to get partway there, and those side tables tend to drift from the real data.
Where event-oriented storage costs more. Queries across entities become harder (the log is ordered by time, not indexed by attribute), storage grows forever, schemas must be readable forever, and every developer must think in terms of events and projections. That is why the pattern is reserved for parts of a system where history is valuable.
Event store as the source of truth#
Events are grouped into streams, one per aggregate (a consistency boundary such as one account or one order). Each event has a stream ID, a sequence number within the stream, a type, a payload and metadata.
CREATE TABLE events (
stream_id TEXT NOT NULL, -- e.g. 'account-42'
version BIGINT NOT NULL, -- 1, 2, 3 ... per stream
event_type TEXT NOT NULL, -- 'MoneyDeposited'
payload JSONB NOT NULL,
metadata JSONB NOT NULL, -- user, correlation_id, schema_version
global_pos BIGSERIAL, -- order across all streams, for projections
recorded_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (stream_id, version) -- blocks two writers appending the same version
);
-- Append with optimistic concurrency: expect the stream to be at version 7
INSERT INTO events (stream_id, version, event_type, payload, metadata)
VALUES ('account-42', 8, 'MoneyWithdrawn', '{"amount":30}', '{"user":"u1"}');Rules:
- Append only: events are never updated or deleted; a mistake is corrected by a new compensating event (
DepositReversed). - Optimistic concurrency: a writer appends version 8 only if the stream is at version 7. The primary key rejects a concurrent writer, which reloads and retries.
- Events are facts in past tense, named in business language.
Choosing an event store, in depth#
Any store can hold events, but an event store needs four specific capabilities:
- Append to a stream with an expected version, atomically, so two writers cannot both append version 8.
- Read one stream in order quickly, to load an aggregate.
- Read all events in a global order (or per-partition order) with a checkpoint, to feed projections.
- Subscribe to new events with low latency, so projections stay close to live.
How common options meet them:
| Store | Expected-version append | Read one stream | Global order and subscriptions | Notes |
|---|---|---|---|---|
| PostgreSQL events table | Primary key on (stream_id, version) | Index range scan | Global position column, polling or logical decoding | Familiar and transactional; watch commit-order gaps |
| EventStoreDB (Kurrent) | Built in | Built in | $all stream with catch-up and persistent subscriptions | Purpose-built for this pattern |
| DynamoDB | Conditional put with attribute_not_exists on (stream_id, version) | Query by partition key | DynamoDB Streams, ordered per item key | Serverless; hot partitions for busy streams |
| Apache Kafka | Not built in; needs a single writer per key | Must scan a partition and filter by key | Native, per partition | Strong as transport, awkward as the only store |
| Redis Streams | Not built in; XADD with explicit IDs offers partial checks | XRANGE on a stream per aggregate | Consumer groups with XREADGROUP | Fast, but durability depends on persistence settings |
Redis Streams as an event log. Redis streams are append-only logs similar to Kafka topics. Producers append with XADD, consumer groups share the work with XREADGROUP, and each consumer acknowledges with XACK. The group tracks a pending entry list, and every pending entry has an idle time. If a consumer dies mid-task, its entries keep ageing until another consumer takes them with XCLAIM or XAUTOCLAIM. Because Redis cannot tell a slow consumer from a dead one, an entry can be processed twice, so processing must be idempotent. The important caution is durability: a stream entry is only as safe as the Redis persistence configuration. With the default settings (periodic RDB snapshots, or AOF with appendfsync everysec), a crash can lose recent entries. That is acceptable for a work queue or a notification fan-out, but not for the source of truth of a ledger. Use Redis Streams when Redis is already in the design and the log is modest. Use Kafka when you need long retention, replay by many independent consumers, or ordered, durable throughput where loss is unacceptable. See Redis.
Sizing. Suppose a wallet system has 10 million active wallets, each with 30 events a month, at 300 bytes per event including metadata. That is 300 million events and 90 GB a month, or about 1.1 TB a year before indexes. A single well-provisioned Postgres instance can hold a few years of that, with time-partitioned tables (so old partitions can move to cheaper storage). The write rate is about 115 events per second on average, with peaks perhaps 20 times higher, which is easily handled by one primary. Scale-out becomes necessary at much higher rates, typically by sharding on stream_id.
Stream size limits. Keep streams short. A stream per account per month (with an opening-balance event) caps a stream at a few hundred events, makes loading cheap without snapshots, and lets old streams be archived. A stream that grows without bound, such as "all events for a merchant with a million orders", is a sign that the aggregate boundary is wrong.
Handling a command#
- Load the aggregate's events (or its latest snapshot plus later events).
- Replay them through an
applyfunction to rebuild current state in memory. - Validate the command against that state (is the balance enough?).
- If valid, produce new event(s) and append them with the expected version.
withdraw(account_id, amount):
events = store.read_stream("account-" + account_id)
state = fold(events, initial = {balance: 0}, apply)
if state.balance < amount: reject("insufficient funds")
store.append("account-" + account_id,
expected_version = len(events),
[MoneyWithdrawn{amount}])
apply(state, MoneyDeposited e) = {balance: state.balance + e.amount}
apply(state, MoneyWithdrawn e) = {balance: state.balance - e.amount}Command handling, in depth#
The four steps above are usually written as two pure functions plus a thin shell around them:
- decide(command, state) returns events: business rules. It looks at the current state and the command, and returns the events to record, or a rejection.
- evolve(state, event) returns state: state transitions. It applies one event to the state. It must never reject an event, because events are facts that already happened.
The shell loads events, folds them with evolve to get the state, calls decide, and appends the result with the expected version. Keeping decide and evolve pure (no database calls, no clock, no randomness) makes them trivially testable: "given these past events, when this command arrives, then these events are produced". This given-when-then style is the standard way to test event-sourced aggregates.
Concurrency conflicts in numbers. Optimistic concurrency works well when each stream has few concurrent writers. If an account receives one command every few seconds, conflicts are essentially never seen. If a single stream receives 200 commands per second (a popular product's stock counter, say), and each command takes 5 ms from read to append, about one command is in flight at any moment, so a large share of appends conflict and retry, and throughput collapses under retries. The fix is to change the model: split the hot aggregate (stock per warehouse, or per bucket of units), or queue commands for that stream through a single writer.
Idempotent commands. Clients retry commands after timeouts, just as producers retry messages. Store the command ID in each resulting event's metadata, and have decide (or the shell) check whether that command ID has already produced events for the stream. Because a command's effects live in one stream, this check is local and cheap: scan the recent events, or keep a small set of recent command IDs in the aggregate state.
Side effects stay out of evolve. Replaying events must never send emails or charge cards again. Side effects belong in reactions that consume events after they are stored (projections, process managers, integration publishers), and those reactions are idempotent by event ID. A common bug is calling an external service inside evolve, which then fires on every aggregate load.
Commands that need data from other aggregates. decide sees only its own aggregate's state. If a rule needs another aggregate (is this coupon still valid?), either look it up in a read model before calling decide, accepting that it may be slightly stale, or move the rule into a process manager that coordinates both aggregates with events.
Rebuilding state by replay#
Because state is a pure function of the events, you can:
- Rebuild any aggregate from scratch.
- Time travel: replay only up to a date to get historical state.
- Fix bugs retroactively in derived data: correct the projection code and replay to rebuild the read model.
- Create new views later: a new analytics projection can process the whole history on day one.
Replay, in depth#
Replay is the defining capability of event sourcing, and it comes in several forms with different costs.
Aggregate replay happens on every command: load one stream and fold it. With 200 events of 300 bytes, that is 60 KB read in one index scan (about 1 to 3 ms in Postgres) and microseconds of CPU to fold. That is why short streams need no snapshots.
Projection replay rebuilds a whole read model from position 0. Suppose there are 2 billion events and a projection applies 20,000 events per second with batched writes. The rebuild takes about 28 hours. Partitioning the rebuild over 16 workers, each owning a range of stream IDs, brings it to under 2 hours, as long as the projection only needs per-stream order. Plan rebuild time as an operational number: if a bug corrupts a read model, the time to rebuild is your recovery time for that view.
Temporal queries. "What was the balance on 3 March?" is a replay of one stream up to the last event recorded before that date. Two timestamps matter here. Occurred time is when the business event happened, and recorded time is when the system stored it. A payment that occurred on 2 March but was recorded on 5 March (a late bank file) changes the answer to "what was the balance on 3 March?" depending on which time you ask about. Systems that need both answers (accounting, insurance) store both timestamps. This is the essence of bitemporal data: "what did we believe on date X about date Y?".
Debugging by replay. A production bug report on order 881 can be reproduced exactly: copy the order's event stream into a test, replay it through the current code, and step through decide with the failing command. This is one of the most loved properties of event sourcing among teams that use it.
Determinism requirements. Replay works only if evolve is deterministic. Common violations include:
- Reading the current time inside
evolve. Use the event's own timestamp instead. - Looking up reference data (an exchange rate) at replay time. Store the value used in the event itself.
- Relying on iteration order of hash maps, which may differ between runtimes.
- Changing
evolve's logic so that old events produce different state. When business rules change, the new rule should apply to new events, which typically means versioned event types or a rule version in the event.
What replay cannot do. Replaying changes derived state, not the outside world. If a bug caused wrong emails to be sent, replaying events with fixed code rebuilds correct read models but does not unsend the emails. Corrections to the real world are new commands and new events.
Snapshots#
An account with 50,000 events would take too long to replay on every command. A snapshot stores the aggregate's state at a version (account-42 @ v50000: balance 1,204). Loading becomes "latest snapshot + events after it".
- Take snapshots every N events (say 100-1,000) or in the background.
- Snapshots are a cache: you can delete and rebuild them, and they must be versioned with the aggregate code.
- Many aggregates are short-lived (an order has tens of events) and never need snapshots. Long-lived streams can also be split by period (closing the books monthly and starting a new stream with an opening balance).
Snapshots, in depth#
A snapshot is a cached result of folding a stream up to a version. Done well, it is invisible; done badly, it becomes a second source of truth that drifts from the events.
When snapshots pay off. Suppose reading an event costs about 5 microseconds (amortised within one index scan) and folding it costs about 1 microsecond, while reading a snapshot costs about 1 ms (one extra row read and deserialisation). Without snapshots, loading a stream of n events costs about 6n microseconds. With a snapshot every k events, the cost is 1 ms plus on average 6 x k/2 microseconds. For a stream of 200 events, loading without snapshots costs 1.2 ms, so a snapshot saves nothing. For a stream of 50,000 events, it costs 300 ms without snapshots and about 2.5 ms with k = 500. The rule of thumb that follows: snapshot only streams that routinely exceed about 1,000 events, and choose k so the tail replay costs about as much as the snapshot read.
How to take them.
- Inline: after appending, if the version crosses a multiple of k, write a snapshot. Simple, but it adds latency to that command.
- Background: a projection-like process watches streams and writes snapshots for long ones. It is off the command path, and it can be stopped at any time without affecting correctness.
- Store them separately from events (a
snapshotstable keyed bystream_id, with the version and asnapshot_schema_version), and never let a snapshot replace the events.
Versioning snapshots. A snapshot is a serialised in-memory state, so it is tied to the aggregate code that produced it. When the state shape changes, old snapshots become unreadable or, worse, readable but wrong. Store a schema version with each snapshot. When it does not match the current code, ignore the snapshot and fold from the events (or from an older compatible snapshot). Because snapshots are disposable, the safest migration is to delete them all and let them rebuild.
Snapshots in Temporal. Durable workflow engines face the same problem and solve it the same way. Temporal stores each workflow's Event History as the durable record, and alongside it keeps Mutable State: a materialised view of the workflow's current server-side state, such as pending activities, outstanding timers and child workflows. In principle Mutable State could be rebuilt by scanning the history on every change, but that would be needlessly expensive, so it is persisted and updated with each state transition while the history remains the record it can be recovered from. That is exactly the relationship between a snapshot and an event stream. (Temporal's workers also replay the history to rebuild a workflow's in-code state, which is why workflow code must be deterministic; that is the same rule as evolve.) See the deep dive below and Temporal and Workflow Engines.
Alternatives to snapshots. Before adding snapshots, ask whether the stream should be shorter. Closing a period ("books closed for November, opening balance 1,204") and starting a new stream is often cleaner than snapshotting an ever-growing one, and it matches how accounting already works.
Projections and read models#
A projection consumes the event stream (in global_pos order) and maintains a read model: a table, document, search index or cache shaped for one query.
- Each projection tracks the last position it processed (a checkpoint), so it can resume after a restart.
- Projections must be idempotent (upsert by key, or store the last applied version per row), because events may be redelivered. See Delivery Semantics.
- Read models are eventually consistent: typically milliseconds to seconds behind the event store. Expose the lag and design the UI for it.
- Read models are disposable: to change one, build a new version from position 0 alongside the old, then switch over.
Event stores publish events to projections either directly (subscriptions in EventStoreDB/Kurrent, or polling global_pos) or by streaming them to Kafka, often via Change Data Capture.
Projections, in depth#
Projections are where most of the engineering effort in an event-sourced system goes, because they carry all the query load and all the eventual-consistency trade-offs.
Inline vs asynchronous projections.
- An inline projection updates its read model in the same database transaction as the event append. Reads are strongly consistent, but every command pays for every inline projection, and the read model must live in the same database as the events.
- An asynchronous projection runs separately and catches up. It can write to any store (Elasticsearch, Redis, a warehouse) and scale independently, but it lags.
A common split: one or two inline projections for the queries that must be immediately consistent (the current balance shown right after a transfer), and asynchronous projections for everything else.
Exactly-once projections. If the read model lives in a transactional database, store the projection's checkpoint (the last applied global position) in the same transaction as the read-model update. A crash then rolls back both, and the projection resumes from a consistent point. This gives an exactly-once effect without any dedup table. If the read model is in a non-transactional store (Elasticsearch, Redis), make each update idempotent instead: upsert documents keyed by entity ID with the entity's version, and ignore updates with a lower version. See Delivery Semantics.
Parallelism without breaking order. A projection reading one global sequence is single-threaded. To scale it, partition the work by stream ID: each worker handles a hash range of streams and keeps per-stream order. This works when the read model's rows depend on one stream each (an account_balance row per account). Projections that combine streams (a "top merchants by volume" leaderboard) need either a single ordered reader or a commutative update (increment by event amount, deduplicated by event ID).
Catch-up and live phases. A new projection starts with a catch-up phase, reading history as fast as possible, usually in large batches with bulk writes, then switches to a live phase with small, low-latency reads. Event stores expose this as catch-up subscriptions (EventStoreDB) or simply as reading from an offset in Kafka. Measure catch-up speed before you rely on it for incident recovery.
Many consumers, many shapes. Because events stay in the log, several independent consumer groups can read the same stream for different purposes: one updates a live dashboard, another stores events in a warehouse for historical analysis, another feeds a fraud model. Each tracks its own position and cannot slow the others down.
Windowed projections. Some read models aggregate over time rather than per entity: "orders per minute per region", or "mean delivery time per region over the last 24 hours". These group events into windows, by time (tumbling windows of one hour, or sliding windows of 24 hours advancing every minute) or by count. A stream processor such as Apache Flink or Spark Structured Streaming handles windowing, late events and state for you. See Apache Flink and Stream Processing.
Monitoring. For every projection, track the lag in seconds (now() minus the recorded_at of the last applied event), its error count, and its checkpoint position. Alert when lag exceeds what the UI can hide, often 5 to 30 seconds for user-facing views.
CQRS#
CQRS splits the application into:
- Command side: handles intents (
PlaceOrder), enforces invariants, writes to the write model. Optimised for correctness and concurrency. - Query side: serves reads from one or more read models. Optimised for query speed and shape, and scaled separately (often 10-100x more reads than writes).
CQRS comes in degrees:
| Level | What changes | Consistency |
|---|---|---|
| Separate code paths, one database | Different classes or services for commands and queries | Strong |
| Separate read tables in the same database, updated in the same transaction | Denormalised views | Strong |
| Separate read stores (Elasticsearch, Redis, replicas) updated asynchronously | Independent storage and scaling | Eventual |
| Event-sourced write side + projections | Full CQRS with event sourcing | Eventual |
You can use CQRS without event sourcing (a normal Postgres write model, with CDC feeding a search index), and event sourcing without separate read stores (rebuilding the aggregate for every read in a small system). They are often combined because event sourcing makes the write side poor at queries (you cannot efficiently ask "all accounts with balance > 1,000" from a log), and projections solve exactly that.
CQRS, in depth#
Origins. CQRS grew out of Command-Query Separation (CQS), a principle Bertrand Meyer described in Object-Oriented Software Construction (1988): a method should either change state (a command) or return data (a query), but not both. Greg Young and others applied the same split at the level of whole models and services around 2010, and named it CQRS. CQS is about method design. CQRS is about having different models, and possibly different stores, for writing and reading.
Why the two sides differ so much. The write side protects invariants for one aggregate at a time: "an account cannot go below its overdraft limit". It needs transactions, concurrency control and a normalised model. The read side answers questions that span many aggregates, in shapes that suit each screen: "the last 50 transactions across all of a customer's accounts, with merchant names and categories, searchable by text". It needs denormalised data, indexes, full-text search and caching. One model forced to do both ends up either slow to read (normalised joins at query time) or fragile to write (denormalised copies updated in many places within one transaction).
Read and write scaling in numbers. Suppose a banking app has 2,000 writes per second (transactions) and 60,000 reads per second (balance checks, statement views, search). The write side is one sharded Postgres cluster, sized for 2,000 transactional writes per second with strict durability. The read side is a mix of a Redis cache for balances (about 1 ms reads, easily 100,000 per second on a small cluster), and Elasticsearch for statements and search. Each side is scaled, tuned and even replaced on its own schedule.
Task-based commands. CQRS works best when commands express user intent (ChangeShippingAddress, CancelOrder) rather than generic updates (UpdateOrder with a full document). Intent-based commands make rules explicit, produce meaningful events, and avoid lost updates from two clients overwriting different fields of the same document.
What a command returns. Strict CQRS says commands return nothing but success or failure. In practice, returning the new version (and sometimes the new ID) is useful, because the client can pass it to the read side to get read-your-writes ("show me order 42 at version 7 or later"). Returning a full view of the new state from the command side is tempting but couples the two sides again.
When CQRS alone is enough. Many systems benefit from separate read models without event sourcing: a normal Postgres write model, with changes streamed by CDC into Elasticsearch for search and into Redis for hot reads. That gives most of the read-scaling benefit with none of event sourcing's versioning burden. See Change Data Capture and the Outbox Pattern.
Combining both#
The full combination works like this:
- A command arrives at the write side.
- The aggregate is loaded from its snapshot and events, the command is validated, and new events are appended with optimistic concurrency.
- Events flow to projections, which update read models.
- Queries hit the read models.
- Other services subscribe to (usually a curated set of) the same events for integration.
Read-your-own-writes needs care: after a command, the client can wait until the projection reaches the returned version, read from the write side for that one entity, or update the UI optimistically.
The combined flow, in depth#
Putting the pieces together, one command flows through the system like this:
The event store is already an outbox. In a state-oriented service, you need an outbox table to publish events reliably alongside the state change. In an event-sourced service, the events are the state change, stored in one atomic append. A publisher that reads the event store from a checkpoint and forwards events to Kafka gets reliable publishing for free. It is still at-least-once, so integration consumers dedupe by event ID.
Private events vs public events. The aggregate's events are designed for its own needs and change as the model evolves. Exposing them directly to other teams freezes your internal model. The integration publisher above maps private events to a smaller, stable set of public events (as described in Event-Driven Architecture), and it can enrich them with data from projections.
Read-your-writes options, compared.
| Option | How it works | Cost |
|---|---|---|
| Wait for version | Read side blocks briefly until it has applied the returned version | Adds up to the projection lag to that read |
| Read from the write side | For the entity just changed, load it from the event store | Extra load on the write side |
| Inline projection | Update the critical read model in the append transaction | Slower commands; same database |
| Optimistic client | The client applies the change locally and reconciles later | Client complexity |
Failure modes in the combined flow. If the projection worker stops, commands keep succeeding, and reads go stale. If the publisher stops, other services fall behind, but this service stays correct. If the event store is down, nothing can be written, which is the right outcome for a source of truth. This failure isolation is one of the quieter benefits of the architecture: only the event store is on the critical path for writes.
Event versioning in an event-sourced system#
Events are stored forever, so old event shapes must stay readable:
- Additive changes with defaults are safe.
- Upcasting: when loading, transform old event versions into the current shape in code (
MoneyWithdrawn v1with no currency becomes v2 with"currency":"USD"). - Never rewrite history in place, except for legal deletion (below).
Versioning and erasure, in depth#
Events written today must still be readable in ten years, by code that has been rewritten several times. Greg Young's book Versioning in an Event Sourced System (2017) is the standard reference on this problem. The main techniques, from least to most invasive:
- Weak schema. Deserialise events tolerantly: ignore unknown fields, use defaults for missing ones. Many changes (adding a field) then need no code at all. JSON with tolerant readers and Avro or Protobuf with defaults all support this.
- New event type. When meaning changes, introduce a new event (
MoneyWithdrawnWithFee) instead of changing the old one.evolvehandles both. Old events keep their old meaning, which is correct, since they describe what happened under the old rules. - Upcasting. A chain of small functions converts old versions to the current one at read time (v1 to v2 adds a default currency, v2 to v3 splits
nameintofirst_nameandlast_name). Business code only sees the latest version. The chain grows, so keep each upcaster small and tested with stored sample events. - Copy and replace. For deep restructuring (splitting one aggregate into two), run a migration that reads the old store, transforms events, and writes a new store, then switches over. The old store is kept read-only for audit. This is a big operation, done rarely.
Rewriting events in place is the option to avoid. It breaks the audit guarantee, invalidates snapshots and projections, and makes "what did the system know on date X" unanswerable.
Erasure: the GDPR problem. The EU's General Data Protection Regulation gives people a right to have personal data erased. An immutable log seems to conflict with that. Three approaches are used, often together:
- Keep personal data out of events. Events reference a
customer_id; names, addresses and emails live in a separate, mutable personal-data store that can be erased. Events stay immutable and still describe what happened. - Crypto-shredding. Encrypt personal fields in each event with a key specific to the data subject, stored in a key store. To erase, delete the key. The ciphertext remains in the log but is unreadable forever, including in backups. Projections must handle undecryptable fields (show "erased").
- Stream deletion for whole subjects. Some event stores support deleting or truncating a stream. When a whole stream is about one person, deleting it may be acceptable, with a tombstone event recorded elsewhere for audit.
Whatever the approach, remember the copies: projections, search indexes, Kafka topics with retention, caches and the data warehouse. An erasure must reach all of them. That is a strong argument for keeping personal data out of events in the first place.
Streams as the transport for events#
Event sourcing needs a store for each service's own events. Getting those events to projections and other services usually needs a stream: a partitioned, replicated, retained log such as Kafka, Kinesis or Pulsar. Unlike a message queue, which deletes a message once a consumer acknowledges it, a stream keeps data for a configured period (or forever, with compaction or tiered storage). Consumers can read and re-read from any position or from a point in time. That is exactly what projections and rebuilds need.
Three situations where a stream is the right tool:
- High-volume, real-time processing. A social platform showing live engagement analytics (likes, comments and shares per post) ingests millions of events per second from around the world into a stream, and a stream processor such as Flink or Spark Streaming updates the dashboard as events arrive.
- Event sourcing and replay. In the banking example, each transaction is an event in the stream, so it can be processed in real time, audited later, and replayed to reconstruct any account's state at any time.
- Many independent consumers. In a chat application, a message sent to a room is appended to that room's stream, and every participant's connection server consumes it. The stream acts as a central channel with many subscribers, which is the publish-subscribe pattern. See Design a Chat System.
Properties that matter for event-sourced systems.
- Partitioning. A stream scales by splitting into partitions across servers, each consumed by a different consumer. As with database sharding, choose a partition key so related events land together. For event sourcing, the key is the aggregate ID, so all events of one stream stay in order on one partition.
- Consumer groups. Several groups read the same stream independently. One updates a live dashboard, another writes the same events to a database for historical analysis, each at its own pace.
- Replication. Partitions are copied to several brokers, so a broker failure does not lose events. For a source-of-truth log, use the durable settings described in Delivery Semantics:
acks=all, replication factor 3,min.insync.replicas=2. - Windowing. Grouping events by time or count (hourly totals, mean delivery time per region over 24 hours) is a standard stream-processing operation for analytic projections.
Can the stream be the event store? Sometimes. Kafka lacks expected-version appends and fast per-key reads, but if each aggregate has exactly one writer (for example, a Kafka Streams application that owns a partition and keeps the aggregate state in a local state store backed by a compacted changelog topic), the single writer enforces ordering and the state store provides fast reads. This works well for stream-processing-shaped domains. For command-driven business aggregates with many concurrent writers, a database-backed event store plus a stream for distribution is the safer split. The most common streaming technologies are Kafka, Kinesis and Pulsar for the log, with Flink and Kafka Streams for processing. See Kafka.
Worked example: an event-sourced wallet ledger#
A digital wallet holds balances for 10 million users and processes 1,500 transfers per second at peak. Regulators require every balance change to be explainable, and the balance must never go negative.
Aggregates and streams. Each wallet is an aggregate with a stream per wallet per month (wallet-42-2026-12). The first event of each month is PeriodOpened {opening_balance}, so a stream rarely exceeds a few hundred events and no snapshots are needed.
Events. FundsCredited {amount, source, transfer_id}, FundsDebited {amount, destination, transfer_id}, FundsHeld {amount, hold_id}, HoldReleased {hold_id}, HoldCaptured {hold_id}. Amounts are integers in the smallest currency unit, never floats.
A transfer spans two aggregates. Wallet A's invariant (no negative balance) can only be checked inside wallet A's stream, and wallet B is a separate stream, so a transfer cannot be one atomic append. A process manager coordinates it:
- A
TransferRequested {transfer_id, from: A, to: B, amount: 500}command goes to wallet A. If A's balance is at least 500, A appendsFundsDebitedwith the transfer ID. Otherwise it appendsTransferRejected. - The transfer process manager sees
FundsDebitedand sendsCreditFunds {transfer_id}to wallet B. - Wallet B appends
FundsCredited. If B is closed, it appendsCreditRejected, and the process manager sends a compensatingRefundFundsto A. - Every step is idempotent by
transfer_id: a wallet that already has an event for this transfer ID does nothing.
Money in flight. Between steps 1 and 3, 500 has left A but not reached B. The ledger must still balance. Double-entry bookkeeping solves this: the debit from A is posted against a "transfers in flight" clearing account, and the credit to B moves it out of the clearing account. A reconciliation projection checks that the clearing account returns to zero for every completed transfer, and alerts on any transfer stuck in it for more than a minute.
Projections.
wallet_balance(inline, same Postgres transaction as the append): the balance shown in the app right after a transfer.statement_lines(asynchronous, into Elasticsearch): searchable history with merchant names, under one second behind.daily_totals(asynchronous, into the warehouse): regulatory reports.fraud_features(asynchronous, through Kafka into a Flink job): velocity features such as "transfers in the last 10 minutes".
Sizing. 1,500 transfers per second produce about 3,000 events per second (a debit and a credit), plus about 500 per second from other operations, so 3,500 events per second at 300 bytes, about 1 MB/s. That is well within a sharded Postgres cluster of four primaries keyed by wallet ID. Monthly storage is about 9 billion events at peak rate, but average traffic is a fifth of peak, so around 1.8 billion events, or about 550 GB a month, kept hot for 13 months and then moved to archive storage.
Questions the design answers easily. "Why is my balance 1,204?" is answered by listing this month's events. "What was the balance at 23:59 on 30 November?" is a fold of November's stream. "Did this transfer complete?" is a lookup of its events by transfer ID. "Replay all of last week's events through the new fraud model" is a new consumer reading from an offset.
Worked example: order history for customer service#
An online retailer's support agents need to answer questions like "why was my order delayed?" and "who changed my delivery address?". The order service is state-oriented today and only keeps the latest status, so agents cannot answer. Moving order history to event sourcing is a classic, contained use of the pattern.
The order lifecycle as events. Each order is a stream. Events mirror the business lifecycle:
Along the way, events such as DeliveryAddressChanged {by: customer or agent, old, new}, DelayReported {reason: carrier} and ItemSubstituted capture what support needs. Each event's metadata carries who caused it (customer, agent ID, or system process) and the correlation ID of the request.
The support timeline projection. A projection writes every event for an order into a document in a search index, rendered as a timeline: "10:02 placed by customer, 10:03 payment captured, 14:30 address changed by agent 117 (reason: customer called), 18:00 carrier reported delay: weather". Agents search by order ID, email or phone number. The projection is asynchronous and a second or two behind, which agents never notice.
Volume. At 300,000 orders a day and about 12 events per order, the store grows by 3.6 million events a day, roughly 1.1 GB a day at 300 bytes per event. Streams are short (tens of events), so there are no snapshots, and the whole history of a year fits in a single Postgres database of around 400 GB.
Incremental adoption. The team does not rewrite the order service in one go. Step one: keep the existing orders table as the write model, and append events to an order_events table in the same transaction (effectively an outbox that is kept forever). Step two: build the timeline projection from those events. Step three, only if the benefits justify it: make the events the source of truth and derive the orders table as an inline projection. Many teams stop after step two, which already delivers the audit trail. That is a legitimate end state: event-sourced history without an event-sourced write model.
What changes for analytics. With every state change recorded, the data team can measure time between each pair of states (placed to shipped per warehouse, shipped to delivered per carrier) directly from events, rather than inferring it from periodic snapshots of the orders table.
When to Use It#
- Ledgers and financial systems: balances derived from immutable entries; audit is mandatory.
- Order and booking history: customer service needs to see every state change and why.
- Trading and matching engines: replaying the input event log rebuilds exact in-memory state after a crash. See Design a Stock Exchange.
- Domains where "how did we get here?" matters: insurance claims, compliance workflows, collaborative editing.
- CQRS alone: when read patterns differ greatly from writes (search, dashboards, feeds) or reads vastly outnumber writes.
When NOT to Use It#
- Simple CRUD (user profiles, settings, catalogues): event sourcing adds a lot of machinery for little value; a normal table plus an audit log or CDC is enough.
- Teams new to the pattern on a critical deadline: projections, versioning and eventual consistency take experience.
- When users require strongly consistent queries everywhere: async read models are eventually consistent.
- Data that must be truly deleted (personal data under GDPR) without a plan: immutable logs conflict with erasure. Plan crypto-shredding (encrypt personal fields per user and delete the key) or keep personal data outside the events.
- Whole-system event sourcing: apply it to the few bounded contexts that benefit, not everywhere.
How to Implement It#
- Pick the bounded context that needs history; keep the rest conventional.
- Design aggregates and events in business terms; keep aggregates small, so streams stay short.
- Choose an event store: EventStoreDB/Kurrent, Postgres with an events table (or Marten for .NET), Axon Server, or DynamoDB with conditional writes. Kafka is a fine event transport, but is awkward as the primary store, because it lacks per-aggregate streams with optimistic concurrency.
- Append with expected versions; retry on conflict.
- Add snapshots only for long streams.
- Build projections with checkpoints and idempotent updates; measure projection lag.
- Version events and upcast old ones; register schemas.
- Plan rebuilds: blue/green read models rebuilt from position 0.
- Plan erasure with crypto-shredding.
| Technology | Fits when |
|---|---|
| EventStoreDB / Kurrent | Purpose-built event store with streams and subscriptions |
| Postgres events table, Marten | Event sourcing on familiar infrastructure |
| Axon Framework / Axon Server | Java CQRS and event sourcing framework |
| DynamoDB (conditional writes) + Streams | Serverless event store on AWS |
| Kafka | Transporting events to projections and other services |
| Elasticsearch, Redis, Postgres views | Read models |
Trade-offs#
| Choice | Gain | Cost | Pick when |
|---|---|---|---|
| Event sourcing | Full history, audit, time travel, replays, new views from history | Complexity, versioning forever, eventual reads, erasure is hard | Ledgers, orders, compliance |
| State storage + audit log/CDC | Simple, familiar | History is secondary and may be incomplete | Most CRUD systems |
| CQRS with async read models | Optimised and independently scaled reads | Eventual consistency, more moving parts | Read-heavy, varied queries |
| CQRS in one database | Clear separation with strong consistency | Limited scaling | Moderate scale |
| Snapshots | Fast aggregate loading | Snapshot versioning | Streams with thousands of events |
| Inline projection | Strongly consistent reads | Slower commands, same database | The one or two views users check right after a write |
| Asynchronous projection | Any store, independent scaling | Lag, idempotency needed | Search, analytics, dashboards |
| Stream per aggregate per period | Short streams, no snapshots, easy archiving | Opening-balance events to manage | Ledgers and accounts |
| Redis Streams as the log | Fast, already deployed | Durability depends on persistence settings | Work queues and modest fan-out, not ledgers |
| Kafka Streams single writer | Streams-native aggregates with local state | Limited query patterns | Stream-processing domains |
Common Pitfalls#
- Event sourcing an entire system, including simple CRUD.
- Huge, long-lived aggregates with millions of events and no snapshot or period split.
- Events named after database changes (
RowUpdated) instead of business facts. - Non-idempotent projections that double count after redelivery.
- Changing event schemas without upcasters, so old events no longer load.
- Using Kafka as the only event store with no way to enforce per-aggregate concurrency.
- Forgetting read-your-writes, so users do not see what they just did.
- Calling external services or the clock inside
evolve, so replays send emails or change results. - Hot aggregates with hundreds of commands per second, so optimistic concurrency retries collapse throughput.
- Snapshots without a schema version, which load wrongly after the state shape changes.
- Personal data stored in events with no erasure plan.
- Rebuild times never measured, so a corrupted projection takes days to recover.
Real-World Examples#
Martin Fowler's description of the LMAX architecture explains how a retail trading platform kept its business logic in memory and recovered state by replaying an input event log, using snapshots to shorten replays.
Accounting ledgers have used the append-only idea for centuries: entries are never erased, and corrections are new entries, which is the same principle event sourcing applies to software.
Temporal stores every workflow as an event history partitioned into history shards, keeps a materialised mutable state for speed, and commits transfer tasks with state changes as an internal outbox.
Redis streams support event-sourced designs with XADD, consumer groups and XCLAIM, with durability limited by Redis persistence settings.
In the Interview#
Event sourcing and CQRS in interview problems#
Interviewers usually react well when event sourcing is proposed narrowly and justified, and badly when it is proposed as a default. Good fits and how to frame them:
- Payment system or wallet. "The ledger is append-only: every balance change is an immutable entry with a unique transfer ID, balances are projections, and corrections are new entries." This is event sourcing in spirit even if you never say the words. See Design a Payment System.
- Stock exchange. "The matching engine is single-threaded per instrument and keeps the order book in memory. Every input order is written to a replicated sequenced log first. On failover, a standby rebuilds the book by replaying the log from the last snapshot." See Design a Stock Exchange.
- Ad click aggregator or analytics. "Raw click events go to Kafka with long retention. Aggregates are projections built by Flink. If the aggregation logic has a bug, we fix it and replay." This is CQRS plus replay, without per-aggregate event sourcing. See Design an Ad Click Aggregator.
- Workflow or job systems. "Workflow state is an event history, as in Temporal: state is rebuilt by deterministic replay, and a materialised current state is kept for speed."
Be ready for three probing questions: how you query across aggregates (projections), how you change an event schema (additive changes, upcasting), and how you delete personal data (keep it out of events, or crypto-shred). If you cannot answer those, choose a state-oriented design with an audit log instead.
Deep Dive: Ordering for projections, rebuild at scale, and process managersShow
Global order for projections. Projections need a reliable order across streams. A BIGSERIAL global position in Postgres can be assigned out of commit order: transaction A takes position 101, transaction B takes 102 and commits first. A projection that reads 102 and checkpoints there would skip 101. Fixes: read only up to positions older than the oldest in-flight transaction (pg_snapshot_xmin-style approaches), use a single appender, or rely on an event store that assigns positions at commit time.
Rebuild at scale. Rebuilding a projection over a billion events can take hours. Parallelise by partitioning on stream ID (each worker owns a key range, so per-stream order is kept), use bulk writes into a new table, and switch reads only after the new projection catches up to live.
Process managers. A long-running workflow across aggregates (order → payment → shipment) is handled by a process manager (or saga) that listens to events and issues commands, with its own state. In an event-sourced system, it is often itself event-sourced. See Distributed Transactions.
Consistency boundaries. Invariants are enforced only inside one aggregate (one stream). Rules spanning aggregates ("usernames are unique") need a separate mechanism, such as a reservation table with a unique constraint checked before the event is appended.
Deep Dive: Temporal as an event-sourced systemShow
Durable execution engines are among the most widely deployed event-sourced systems, and Temporal's storage design shows the pattern working at scale.
History shards. A Temporal cluster may manage millions of concurrent workflow executions, so no single machine can own all of them. Executions are hashed into a fixed number of history shards, chosen when the cluster is created. Each instance of the History Service owns a subset of shards and handles the requests and timers for workflows in them. When instances are added, removed or fail, shard ownership moves between instances. This is the same move as partitioning an event store by stream ID: each shard is the unit of ownership and ordering.
A state transition. When something happens to a workflow (say, the chargeCustomer activity completes), the History Service performs one state transition that persists three things together:
- New events appended to the workflow's Event History, the durable, append-only record.
- Updated Mutable State: the materialised current state, including pending activities, outstanding timers and child workflows. It could be rebuilt from the history, but scanning the history on every change would be wasteful, so it is kept alongside, exactly like an inline projection or a continuously updated snapshot.
- A Transfer Task: a durable record that some follow-up work must be dispatched, for example "the workflow needs to run again, so create a workflow task for a worker".
The transfer task is a transactional outbox. If the History Service crashed after updating the state but before telling the Matching Service, the workflow would be stuck forever. Committing the transfer task in the same write means a background processor will always find it and dispatch it, even after a crash. This is the outbox pattern applied inside a workflow engine.
Timers use the same mechanism. A timer (sleep for 3 days) is stored as a timer task in the shard. When its fire time arrives, Temporal records a TimerFired event in the history and creates the work to run the workflow again. Because timers are persisted, a workflow can sleep for months across deploys and cluster restarts.
Replay on the worker. Workers do not keep workflow state between tasks. To continue a workflow, a worker loads its event history and re-executes the workflow code from the start, matching each command the code issues against events already in the history, so completed activities are not run again but their recorded results are returned. That is replay through a deterministic evolve. It is why workflow code must not read the clock, generate random numbers or call services directly: those must go through the SDK so the results are recorded as events. Long-running workflows keep histories bounded with continue-as-new, which starts a fresh execution carrying forward only the needed state, the same idea as closing a ledger period.
Storage. For self-hosted clusters, the persistence layer can be PostgreSQL, MySQL or Cassandra, and Temporal manages the schema for event histories, mutable state and internal task queues. The design shows that a general-purpose database, partitioned by shard, is a perfectly good event store when the access patterns are "append to one stream" and "read one stream".
Key Takeaways#
- Event sourcing stores every change as an immutable event; current state is a replay of them.
- Snapshots shorten replays; projections turn events into query-friendly read models.
- CQRS separates the command (write) model from query (read) models so each can be optimised and scaled.
- The two are independent but complement each other; read models are usually eventually consistent.
- Use them for ledgers, order history and audit-heavy domains, not for simple CRUD; plan versioning and data erasure up front.
- Keep
decideandevolvepure and deterministic, so aggregates are easy to test and replays are safe. - Snapshot only long streams. Shorter streams per period are often a better fix than snapshots.
- Make projections exactly-once by storing the checkpoint with the read model, or idempotent by version.
- The event store is its own outbox. Publish curated public events from it, not the private ones.
- Version with weak schemas, new event types and upcasters. Never rewrite history; plan erasure up front.