Most systems store the current state of the world and throw away how it got there. A row says the account balance is 4,200; it does not say it started at 0, took eleven deposits and three withdrawals, and was frozen for a day in between. For a lot of software that is fine. For anything where the history is the product - ledgers, order lifecycles, audit-heavy workflows, anything where “how did we get here” is a question you must answer - storing only the latest state is lossy by construction. You cannot recover a fact you overwrote.
An event store inverts this. The source of truth is an append-only, immutable log of events - MoneyDeposited, OrderShipped, ItemAddedToCart - and current state is a fold over those events, not a stored row. You never update or delete; you only append. The current state of an account is whatever you get by replaying its events from the beginning. This is event sourcing, and the store that makes it work at scale is what this post designs.
The hard part is not appending to a log - any log does that. The hard part is twofold and in tension. First, every write to a single aggregate must be strictly ordered and must not lose a concurrent update: if two requests both try to append to account #42 based on the same starting state, exactly one must win and the other must be rejected and retried, or you silently double-spend. We enforce that with an optimistic concurrency check on the expected stream version. Second, many independent read models must be built from that one log and kept up to date in real time without coupling to the writers, which is CQRS plus durable catch-up subscriptions. The whole design is the resolution of: strict per-aggregate ordering on the write side, eventual cross-aggregate consistency on the read side, over one immutable log.
The core problem stated once: an event appended to an aggregate’s stream must be totally ordered within that stream and survive a concurrency conflict check, while every projection reads the global flow of events in a durable, resumable, at-least-once way so that read models converge without ever blocking a writer. Everything below follows from that.
Functional Requirements (FR)
In scope:
- Append events to a per-aggregate stream. A stream is identified by an aggregate id (
account-42,order-9981). An append carries one or more events plus the expected version of the stream. The store assigns each event a monotonic stream version (1, 2, 3, …) within its stream and a global log position. - Optimistic concurrency control on append. If the caller’s
expected_versiondoes not match the stream’s current version, the append is rejected with a conflict. This is how two concurrent writers to the same aggregate are serialized - one wins, the other retries against fresh state. No lost updates. - Immutability. Events are never updated or deleted in place. The only write operation is append. Corrections are new events (
PaymentReversed), never edits. - Read a stream. Read all events for an aggregate from version N forward (or from the start), in order, to rebuild its current state by folding.
- Subscribe to the global event flow. A consumer can subscribe from a given global position and receive every event after it, in order, forever - a catch-up subscription. This is how projections (read models) are built and kept live.
- Project independent read models (CQRS). Many separate read models - a SQL summary table, a search index, a cache, a materialized dashboard - each built by its own subscription folding the same events its own way, each advancing at its own pace.
- Snapshots. To avoid replaying a million events to load one aggregate, periodically persist a snapshot of an aggregate’s state at a version, and load from the latest snapshot plus the events after it.
- Optional stream metadata. Max age / max count for retention of non-critical streams, and an ACL per stream.
Explicitly out of scope (name it to own the scope):
- Business logic / command validation. Deciding whether a
WithdrawMoneycommand is allowed (sufficient balance) lives in the aggregate / domain layer. The store enforces ordering and concurrency, not domain rules. It only sees events. - The read model query engines. We define how a projection is fed and how it tracks progress, but we do not design the SQL database, search engine, or cache that a projection writes into.
- Cross-aggregate transactions. There is no multi-stream atomic append. A single append is atomic within one stream only. Processes that span aggregates are sagas over events, out of scope here.
- Full-text search over event payloads. Events are opaque blobs to the store; indexing their contents is a projection concern.
- Schema / event versioning strategy (upcasting old event shapes) - we note where it hooks in but do not design the upcaster.
The decision that drives everything: the stream version is a per-aggregate optimistic lock, and the global log position is the single ordering token for all projections. Writers care about the stream version (did someone beat me?); readers care about the global position (where am I in the firehose?). Those two numbers, and keeping them honest under partitioning and failure, are the whole design.
Non-Functional Requirements (NFR)
- Scale: a platform holding hundreds of millions of streams and tens of billions of events, taking ~30,000 event appends/sec sustained (bursts to 100K/sec), with reads dominated by projections: every event is read by ~10 projections plus occasional full rebuilds, so read throughput is several times write throughput.
- Latency: append acknowledged in p99 < 20 ms (it must feel like a database write on the command path). A projection sees a new event (end-to-end append-to-visible-in-read-model) in tens to low hundreds of milliseconds - near real time, not batch.
- Availability: 99.95%+ on append and read. A broker, projector, or subscription host failing must not lose an acknowledged event and must not stall appends to unrelated streams for more than a failover.
- Consistency: strict serializable ordering within a single stream (linearizable append with version check). Eventual consistency across streams and in every read model - a projection may lag the write side by a bounded amount. The write side is strongly consistent per aggregate; the read side is eventually consistent globally. This split is the entire point of CQRS.
- Durability: an acknowledged append is durable across node failures. Replication factor 3, quorum acks. No acknowledged event is ever lost or reordered within its stream.
- Immutability / auditability: the log is append-only and tamper-evident. You can always reconstruct the exact state of any aggregate at any past version.
The tension to state up front: per-aggregate writes want a single serialization point (to check version N and append N+1 atomically); projections want to read one globally ordered stream for determinism; and a store sharded for scale has no single global order for free. We resolve it by making the aggregate id the shard/partition key so each stream lives on one partition that serializes it, while a per-partition monotonic position plus a merge/ordering scheme gives projections a deterministic global read order. Concurrency safety is bought with a conditional append (compare-and-set on version), never a lock held across a round trip.
Back-of-the-Envelope Estimation (BoE)
Real numbers with the arithmetic, because they set the partition count, the storage budget, and the snapshot cadence.
Write throughput and bandwidth:
Sustained append rate: 30,000 events/sec (peak 100K/sec)
Average event size: ~500 bytes (type + payload + metadata, JSON-ish)
Write bandwidth: 30K/sec * 500 B = 15 MB/sec sustained (50 MB/sec peak)
With RF=3: 15 MB/sec * 3 = 45 MB/sec of replicated write traffic
Read / projection fan-out (reads dominate):
Projections per event: ~10 read models each subscribe to the global flow
Steady read bandwidth: 15 MB/sec * 10 = ~150 MB/sec of outbound event reads
Plus rebuilds: a full rebuild of one projection re-reads the entire log.
=> Size network + page cache for read fan-out (~150-300 MB/sec), not for the 15 MB/sec in.
Storage (the log is forever - that is the point):
Daily events: 30K/sec * 86,400 = ~2.6 billion events/day
Daily bytes: 2.6B * 500 B = ~1.3 TB/day of events (one copy)
With RF=3: ~3.9 TB/day raw.
Retention: events are the source of truth -> effectively infinite retention.
1 year of one copy: 1.3 TB * 365 = ~475 TB. At RF=3: ~1.4 PB/year.
=> Tiered storage is mandatory: hot recent events on SSD, cold old events on object
storage. You never delete, so cold tiering is not optional, it is the storage plan.
Snapshot math (why you cannot replay from zero):
A hot aggregate (a busy account) may accumulate 100,000+ events over its life.
Loading it by folding 100K events at ~1us each = 100 ms just to CPU-fold, plus the read.
With a snapshot every 500 events: load latest snapshot + <=500 events -> sub-millisecond fold.
=> Snapshot cadence trades snapshot storage for load latency. Snapshot "long" streams
(more than a few hundred events) and skip snapshots for short-lived ones.
Partition count (the ordering + parallelism unit):
Per-partition sustainable append throughput ~ 5K-15K events/sec (append+replicate+fsync).
To absorb 100K/sec peak: 100K / ~10K = ~10 partitions minimum.
Add headroom + projection parallelism -> ~32-64 partitions.
One stream -> one partition (by hash of aggregate id), so a partition owns many whole streams.
Partition count caps how parallel the write side and the projection side can be.
The headline shape: ~15 MB/sec of small events in, ~150 MB/sec out after projection fan-out, a log that grows ~1.3 TB/day and is never deleted (petabytes/year, so cold tiering is the storage plan), and two numbers to keep honest - a per-stream version for write safety and a global position for read ordering. Size for infinite retention, read fan-out, and per-stream serialization.
High-Level Design (HLD)
Three planes: a write plane that appends events to streams with a version check, a storage plane that is a partitioned, replicated, append-only commit log, and a read plane of catch-up subscriptions feeding independent projections. A coordination layer (Raft-based) holds partition leadership, the global position watermark, and subscription checkpoints.
WRITE PLANE (command side) STORAGE PLANE (append-only log) READ PLANE (query side / CQRS)
┌───────────────────────┐ ┌──────────────────────────────────┐ ┌───────────────────────────┐
│ client / aggregate │ │ partitioned commit log (RF=3) │ catch │ projector: SQL summary │
│ append(stream, │ route by │ ┌ p0 ┐┌ p1 ┐┌ p2 ┐┌ p3 ┐ ... │ -up │ fold -> read_model table │
│ expected_version, │ hash(agg) │ │strm││strm││strm││strm│ │ subscr │ checkpoint=global_pos │
│ events[]) │───────────▶│ │ v++││ v++││ v++││ v++│ │────────▶├───────────────────────────┤
│ │ │ └────┘└────┘└────┘└────┘ │ from │ projector: search index │
│ CAS on stream version │◀── 409 ────│ each append: check version, │ pos N │ checkpoint=global_pos │
└───────────┬───────────┘ conflict │ assign v+1 + global position │────────▶├───────────────────────────┤
│ │ fsync + replicate to quorum │ │ projector: cache / cmv │
read stream (fold) └──────────────┬───────────────────┘────────▶│ checkpoint=global_pos │
│ │ └───────────────────────────┘
▼ ┌─────────────┴──────────────┐ each projection = its own
┌──────────────┐ │ COORDINATION (Raft) │ subscription + checkpoint,
│ snapshot store│◀─ periodic ─────│ - partition leaders │ lagging independently
│ (agg state@v) │ snapshots │ - global position watermark │
└──────────────┘ │ - subscription checkpoints │ tiered storage: hot SSD -> cold object store
└─────────────────────────────┘ (old events demoted, never deleted)
Append flow (a command becomes a durable, ordered event):
- The caller computes the next events for an aggregate (domain logic, out of scope) and calls
append(stream="account-42", expected_version=7, events=[MoneyDeposited]). - The request is routed to the partition that owns
account-42bypartition = hash(stream_id) % N. That partition’s leader is the single serialization point for this stream. - The leader does a conditional append: it checks that the current version of
account-42is exactly 7. If not, it returns 409 Conflict with the actual version and appends nothing. If yes, it assigns the event version 8, assigns the next global position for that partition, and appends. - The leader replicates the appended record to its followers and waits for a quorum ack (RF 3, 2 in-sync) plus a local fsync, then acknowledges the append to the caller. The event is now durable and ordered.
- The event is now visible to catch-up subscriptions at its global position.
Read-your-own-aggregate flow (rebuild state):
- To load
account-42, read its latest snapshot (state at version V) from the snapshot store, then read eventsV+1 .. currentfrom its stream on the owning partition, and fold them to get current state. - If no snapshot, read from version 1. This is strongly consistent: the stream’s current version and events come from the same partition leader that serializes its appends.
Projection flow (CQRS read side):
- Each projection runs a catch-up subscription starting from its last checkpoint (a global position). It reads every event after that position, in global order, applies its own fold into its own read model (a SQL table, an index, a cache), and periodically persists its checkpoint after the read-model write is durable.
- A new projection starts from position 0 and replays the whole log to build itself - the log is the complete history, so a read model can always be rebuilt from scratch by dropping it and resubscribing from 0.
The structural insight: two monotonic counters carry the whole system. The per-stream version makes appends safe (optimistic lock, serialized by the owning partition leader). The global position makes reads deterministic and resumable (every projection is just “I have processed up to position P; give me P+1 onward”). The write side is linearizable per stream; the read side is eventually consistent and fully rebuildable. Everything hangs off those two numbers.
Component Deep Dive
Four hard parts, naive-first then evolved: (1) enforcing per-aggregate ordering and no-lost-updates - the optimistic concurrency check, the stated headline; (2) giving projections a deterministic, resumable global order out of a sharded log - catch-up subscriptions; (3) loading aggregates without replaying their whole history - snapshots; (4) keeping read models consistent and exactly-once-ish without coupling them to writers.
1. Ordering and concurrency: last-write-wins -> optimistic concurrency on expected version
Two requests hit account-42 concurrently, both having read balance = 100, both appending a withdrawal. We must serialize them so the second sees the first. How?
Naive approach: just append, last write wins
Treat the stream as a dumb log. Every append succeeds; events land in arrival order; whoever appends last is “latest.”
append(stream, events):
log.append(stream, events) # always succeeds, no check
return ok
Where it breaks:
- Lost updates / double spend. Both requests read balance 100, both decide “withdraw 80 is allowed,” both append
MoneyWithdrawn(80). The log now has two withdrawals totaling 160 from a 100 balance. Neither writer knew about the other because nothing made them check. The store silently permitted an impossible state. For a ledger this is a catastrophe, and it is the entire reason event stores exist. - No serialization point. With multiple partitions or multiple writers, “arrival order” is not even well defined - two appends can interleave on different replicas and you have no authority on which came first for that stream.
- Corrupt folds. State is a fold over events in order. If order is ambiguous or an update is lost, the fold produces a wrong current state and every projection inherits the error.
A dumb append-only log preserves history faithfully but provides zero protection against concurrent writers, which is exactly the protection a system-of-record needs.
Evolved approach: conditional append (compare-and-set) on the expected stream version
Every stream has a current version - the number of events in it. An append must declare the version it expects the stream to be at. The owning partition leader - the single serialization point for that stream - checks it atomically:
append(stream, expected_version, events):
lock the stream on its owning partition leader (local, in-memory, cheap)
current = version_of(stream) # e.g. 7
if expected_version != current:
return CONFLICT(actual=current) # 409: someone beat you; refetch and retry
base = current
for i, e in enumerate(events):
e.stream_version = base + 1 + i # 8, 9, ...
e.global_position = next_global_position(partition)
log.append(stream, events) # atomic append of the batch
replicate_to_quorum(); fsync()
return ok(new_version = base + len(events))
The caller’s loop:
while true:
state, version = load(stream) # fold events, note current version
events = decide(state, command) # domain logic
r = append(stream, expected_version=version, events)
if r == CONFLICT: continue # someone appended; reload and re-decide
break
Why this is right:
- No lost updates, provably. Two concurrent writers both read version 7. The first appends with
expected_version=7, succeeds, stream is now 8. The second appends withexpected_version=7, but current is 8, so it gets 409. It reloads (now sees the first withdrawal), re-runs domain logic against the real state, and either appends withexpected_version=8or correctly rejects the command. Exactly one of the two concurrent writers wins each round; the loser never silently overwrites. - Serialization is local and cheap. The check is a compare-and-set against an in-memory version on the one leader that owns the stream. There is no distributed lock, no cross-node coordination per append - the partition leader is the lock, because one stream lives on one partition. This keeps p99 append under 20 ms.
- Optimistic, not pessimistic. No lock is held across the client’s think time. The client reads, thinks, and only at append time is the version checked. Conflicts are rare (same aggregate, truly concurrent) and resolved by a cheap retry, so the common path pays nothing.
- Idempotent appends too. The caller can attach an idempotency key per event; a retried append that the leader already applied returns the prior result instead of duplicating, so a client retry after a lost ack does not double-write.
The subtlety: the version check and the append must be atomic on the leader. If the leader checked version 7, then crashed before replicating, a failover replica must not have already told another writer the version was 8. This is why the version counter, the append, and the replication are one linearizable operation on the Raft group for that partition - the version is part of the replicated state, not a separate cache. expected_version also supports modes: a specific number (strict), ANY (no check, for idempotent event types), NO_STREAM (must not exist yet, for creation), and STREAM_EXISTS.
2. Projections: poll every stream -> one deterministic global order via catch-up subscriptions
A projection needs every event, from every stream, in a stable order, and must resume exactly where it left off after a restart. The log is sharded across partitions, each with its own local order. How does a projection get one deterministic global order it can checkpoint against?
Naive approach: each projection polls every stream for new events
A projection remembers, per stream, the last version it saw, and periodically asks each stream “anything after version K?”
every tick:
for stream in all_streams: # hundreds of millions of them
new = read(stream, after=last_seen[stream])
for e in new: project(e); last_seen[stream] = e.version
Where it breaks:
- It does not scale to the stream count. With hundreds of millions of streams, polling each one is absurd - you cannot iterate the key space on a timer. Most streams have nothing new; you burn everything scanning for the few that changed.
- No global order. Per-stream polling gives you events grouped by stream with no defined order between streams, so two projections could apply cross-stream events in different orders and produce different read models from the same log. Non-determinism in a system whose selling point is reproducibility.
- Checkpointing is a map, not a number. “Where am I” becomes a huge map of per-stream positions, expensive to store and to resume from, and racy to update.
- Latency is the poll interval. Freshness is capped at how often you can afford to sweep, which with that many streams is slow.
Polling the streams treats the store as a pile of independent logs, when a projection needs it as one ordered firehose.
Evolved approach: a global-ordered read stream plus durable per-subscription checkpoints
Maintain, in addition to per-stream order, a global position: every appended event gets a monotonic position in a total order the store defines (per-partition monotonic positions merged into a global order, or a single $all ordered index). A catch-up subscription reads this global stream from a position and pushes events to the projection; the projection persists a single checkpoint (one number) after its read-model write is durable.
subscription (per projection):
pos = load_checkpoint(projection_id) # single number, e.g. 4_880_201
while true:
batch = read_all(from=pos, limit=1000) # global-ordered events after pos
for e in batch:
project(e) # fold into this read model
write_read_model_durable() # the projection's own store commit
pos = batch.last.global_position
save_checkpoint(projection_id, pos) # resume point; one number
# when caught up, switch to push: broker notifies on new appends (live tailing),
# fall back to catch-up read if the subscriber lags behind the live edge.
Why this is right:
- One deterministic order every projection shares. Reading the global
$allstream in position order means every projection sees events in the same order, so the same log deterministically produces the same read model every time. Rebuild a projection from 0 and you get a bitwise-reproducible result. That reproducibility is the whole value proposition of event sourcing, and the global position is what guarantees it. - “Catch-up then live” covers cold start and steady state. A new or restarted projection catches up by batch-reading from its checkpoint to the live edge (fast sequential scans), then subscribes live - the broker pushes new events as they are appended, so steady-state latency is a push, not a poll. If a live subscriber falls behind (slow read model), it transparently falls back to catch-up reads until it reaches the edge again. No stream-by-stream polling anywhere.
- Checkpoint is one number, resume is exact. Progress is a single global position per projection. A crash resumes by reading from that number forward. Because the read-model write is made durable before the checkpoint advances, a crash re-reads a few events (at-least-once) rather than skipping any - which deep dive 4 makes harmless.
- Projections are fully independent. Each has its own subscription and its own checkpoint, so a slow search-index projection lags without affecting the SQL projection or the writers. Adding a new read model is just a new subscription from position 0 - no change to the write side, no change to other projections. This is CQRS in one mechanism: many readers, each folding the one log their own way, at their own speed.
The global-order subtlety. Defining a single global position across a sharded log is the real cost. Options: (a) a single ordering sequencer that stamps a global position at append (simple, deterministic, but the sequencer is a throughput ceiling and a hot spot); (b) per-partition positions merged at read time by a monotonic merge (scales writes, but “global order” is then a defined merge of partition clocks, and a subscriber must wait for all partitions up to a low-water mark to avoid seeing a gap fill in later). The honest trade: strict single global order caps write throughput at the sequencer; per-partition order with a merged $all view scales but makes the global order a defined order (by partition then position, gated on a low-water mark) rather than wall-clock. Most real event stores take (b) and expose the $all stream as that defined, gap-free-on-read order. Either way the projection still gets a stable, resumable, single-number position.
3. Loading aggregates: replay from event 1 -> snapshot plus tail
To handle a command against account-42, you must load its current state by folding its events. A long-lived aggregate has tens of thousands of events. Folding all of them on every command is too slow.
Naive approach: always fold the full stream from version 1
load(stream):
state = initial()
for e in read(stream, from=1): # could be 100,000 events
state = apply(state, e)
return state, current_version
Where it breaks:
- Load latency grows without bound. A busy aggregate accumulates events forever (append-only, never deleted). A stream with 100K events costs a 100K-event read plus fold on every single command, so the hottest aggregates - the ones hit most - are also the slowest to load. Latency scales with history length, which only grows.
- Read amplification. Every command re-reads the entire history it already read last time. At 30K appends/sec against hot aggregates, that is enormous wasted IO and CPU re-folding events whose contribution to state never changes.
- It gets worse over time, by design. Because you never delete, the problem is strictly monotonic - the system slows down the longer it runs. Unacceptable for a store meant to run for years.
Replaying from zero is correct but has a cost that grows with the very history the store is built to keep forever.
Evolved approach: periodic snapshots, load from latest snapshot plus the tail
Periodically persist the folded state of an aggregate at a version - a snapshot - keyed by (stream, version). To load, read the latest snapshot and fold only the events after it.
snapshot (async, every S events or on a schedule):
state, v = load(stream)
snapshot_store.put(stream, version=v, state=state) # separate store, overwritable per stream
load(stream):
snap = snapshot_store.latest(stream) # state @ version v, or none
state = snap ? snap.state : initial()
from = snap ? snap.version + 1 : 1
for e in read(stream, from=from): # only the tail, <= S events
state = apply(state, e)
return state, current_version
Why this is right:
- Bounded load cost. With a snapshot every S = 500 events, a load folds at most ~500 events regardless of whether the stream has 500 or 5,000,000 events total. Load latency is flat over the aggregate’s lifetime, so the hot, long-lived aggregates stay fast.
- Snapshots are a cache, not truth. The event log remains the single source of truth; a snapshot is a derived, disposable optimization. If a snapshot is corrupt or its schema changes, you delete it and rebuild from events - correctness never depends on the snapshot, only speed. This keeps immutability intact: we did not weaken the log, we added a cache in front of the fold.
- Overwritable and cheap. You only need the latest snapshot per stream (older ones are replaceable), so snapshot storage is ~one state blob per long stream, not per event. Short-lived streams (few events) get no snapshot at all - the tail fold is already cheap.
- Async, off the write path. Snapshotting runs in the background (triggered by event count or time), so it never slows an append. A stale snapshot just means a slightly longer tail fold until the next snapshot runs - always safe.
The subtlety: snapshot schema evolution. A snapshot is a serialized state shape; if the aggregate’s state structure changes (a new field), old snapshots are stale-shaped. The fix is to version the snapshot schema and treat a snapshot whose version you cannot read as absent - fall back to folding events (which are themselves versioned and upcastable). Never let a snapshot you cannot interpret block a load; the log can always rebuild it.
4. Read-model consistency: write twice and hope -> at-least-once projection, idempotent on global position
A projection reads an event and writes to its read model (a SQL row, an index doc). The projector can crash between the read-model write and the checkpoint advance, or redeliver on restart. How do read models stay correct and not double-apply?
Naive approach: project, then checkpoint, with no idempotency
for e in subscription:
read_model.apply(e) # (1) e.g. UPDATE summary SET count = count + 1
save_checkpoint(e.position) # (2) after (1)
Where it breaks:
- Crash between (1) and (2) double-applies. If the projector writes the read model then dies before saving the checkpoint, on restart it re-reads from the old checkpoint and applies the event again. A
count = count + 1becomes +2; a non-idempotent insert duplicates a row. The read model is now wrong and there is no error to notice it by. - At-least-once is unavoidable. The subscription is durable and resumable, which inherently means it may redeliver an event after a crash - that is the price of never dropping one. You cannot make the read-model write and the checkpoint save atomic across two different stores without a distributed transaction per event, which is far too slow at this throughput.
- Out-of-order on recovery. If the projector also parallelizes across partitions for speed, a naive recovery can re-apply events in a different interleaving than before, and a non-commutative fold diverges.
At-least-once delivery plus a non-idempotent projection equals a read model that drifts on every crash.
Evolved approach: make the projection idempotent on the global position, checkpoint atomically where possible
Accept at-least-once delivery and make re-applying an event a no-op. The global position is monotonic, so a projection records the last position it applied and ignores anything at or below it. Where the read-model store is transactional, write the data change and the checkpoint in one transaction.
projection apply (idempotent on global position):
on event e at global_position P:
begin tx (in the read model's own store, if transactional)
if P <= applied_position: return # duplicate / replay -> no-op
read_model.apply(e) # the fold step
applied_position = P # advance in the SAME tx
commit tx
# if the read model store is NOT transactional:
# use P as a version/condition on the written row (apply only if P > stored_pos),
# or dedupe on a processed-positions set. Same monotonic-position idea.
Concrete shapes per read-model type:
| Read model | Idempotency mechanism |
|---|---|
| SQL summary table | Store _applied_position (per row or a single checkpoint row); UPDATE the data and the checkpoint in one transaction; skip if P <= _applied_position |
| Search index | Use P as the document external version; the engine drops an update with an older version - replays are no-ops automatically |
| Key-value cache | Conditional set with a stored position, or rely on last-writer-wins since global order is already stable |
| Another service | Dedup table on the global position or an idempotency key; apply inside that service’s transaction |
Why this is right:
- Duplicates are provably harmless. A redelivered event has
P <= applied_positionand is skipped. So at-least-once delivery plus an idempotent, position-versioned projection gives effectively-exactly-once read-model updates with no cross-store distributed transaction. The projector and the store stay independently available. - One number does ordering and idempotency. The global position both defines the order the projection applies events and serves as the high-water mark that rejects replays and stragglers. The same mechanism from deep dive 2 (catch-up ordering) is the dedup key here - no second bookkeeping.
- Atomic apply-and-checkpoint closes the gap. When the read-model store is transactional, committing the data write and the
applied_positiontogether makes “applied” and “progress” a single fact - there is no window where one is true and the other is not, so no double-apply is possible. For non-transactional sinks, the position-version check is the fallback that makes a re-apply idempotent anyway. - Rebuild is always available. Because the log is complete and the projection is a pure deterministic fold over the global-ordered stream, you can always drop a corrupt read model and rebuild it from position 0. The idempotency and the determinism together mean the rebuilt model is identical to what it should be - the ultimate repair tool, which only an immutable log gives you.
The honest caveat. End-to-end exactly-once requires the read model to cooperate - a transaction bundling the write with the checkpoint, or an idempotency key it dedupes on. A read model that supports neither (a fire-and-forget external call) can only be at-least-once; the best the store does is hand it a stable key (the global position) and document that the sink owns the dedup. The write side is strongly consistent per stream; the read side is eventually consistent and converges - a projection is, for a bounded window, behind. Clients that need read-your-write on a projection must either read from the write side (fold the aggregate) or wait for the projection to reach the position their append returned.
API Design & Data Schema
Write API (command side)
POST /streams/{stream_id}/events # append with optimistic concurrency
Header: Expected-Version: 7 # number | any | no_stream | stream_exists
Body: [ { "type": "MoneyDeposited",
"data": { "amount": 500, "currency": "INR" },
"metadata": { "causation_id": "...", "correlation_id": "..." },
"idempotency_key": "cmd-abc123" } ]
-> 201 { "stream_id": "account-42", "next_version": 8,
"global_position": 4880201 }
-> 409 { "error": "wrong_expected_version", "expected": 7, "actual": 8 }
GET /streams/{stream_id}/events?from=0&limit=100 # read a stream forward to fold
-> { "events": [ { "version": 1, "global_position": 4880011, "type": "...",
"data": {...}, "metadata": {...}, "created_at": "..." }, ... ],
"current_version": 8 }
GET /streams/{stream_id}/events?from=5&direction=backward # for reverse reads
Read API (subscriptions / projections)
GET /subscriptions/all?from_position=4880201&limit=1000 # catch-up read of $all
-> global-ordered events after the position
WS /subscriptions/all/live?from_position=4880201 # live push after catch-up
<- streamed events as they are appended (fall back to catch-up if lagging)
PUT /subscriptions/{projection_id}/checkpoint # persist progress
{ "position": 4880201 } # after read-model durable
GET /streams/{stream_id}/snapshot # latest snapshot for fast load
-> { "version": 7500, "state": {...} }
Data model: the log, the index, the snapshots, the checkpoints
The hot path is an append-only commit log, deliberately not a general-purpose SQL table. The workload is append-and-sequential-scan with an immutable, ever-growing dataset - a log-structured store (segment files + indexes) is the right tool; a random-access, update-in-place RDBMS with per-row indexes is the wrong one for the event data itself. The small coordination and index stores are strongly consistent because they are correctness-critical and comparatively tiny.
Events (the source of truth - append-only log, partitioned by stream):
event record (immutable, never updated or deleted):
global_position BIGINT # total order for $all reads (primary read key)
stream_id STRING # e.g. "account-42" (partition key = hash(stream_id))
stream_version INT # 1,2,3... within the stream (UNIQUE per stream_id)
event_id UUID
event_type STRING
data BLOB # opaque payload (JSON/Avro/protobuf)
metadata BLOB # causation_id, correlation_id, actor, idempotency_key
created_at TIMESTAMP
INDEX: (stream_id, stream_version) -> stream reads + the version check (UNIQUE: no dup version)
INDEX: (global_position) -> $all catch-up reads (clustered / primary order)
Storage: segmented append-only files; recent segments on SSD, old on object storage (tiered)
The UNIQUE (stream_id, stream_version) constraint is the optimistic concurrency check made physical: two concurrent appends claiming version 8 cannot both commit - the second violates uniqueness and becomes the 409. The version check is not just an app-level compare; it is enforced by the storage layer so a race cannot slip through.
Stream metadata (per stream, small, strongly consistent):
stream_meta:
stream_id PK
current_version INT # the authoritative version for the CAS check
max_age / max_count # optional retention for non-source-of-truth streams
acl # read/write permissions
truncate_before INT # for GDPR-style stream deletion (tombstone, rare)
Snapshots (derived cache, overwritable per stream):
snapshot:
stream_id PK
version INT # events folded up to here
state BLOB # serialized aggregate state
schema_version INT # to detect/skip unreadable old snapshots
-> keep only the latest per stream; disposable, rebuildable from events
Subscription checkpoints (per projection, one number each):
checkpoint:
projection_id PK
global_position BIGINT # resume point; advanced AFTER read-model write is durable
updated_at
Why SQL vs NoSQL, stated: the event log is a purpose-built append-only, log-structured store (segments + sparse indexes), not SQL or document - infinite immutable append and sequential replay are the entire access pattern, and tiered cold storage is mandatory. Stream metadata and checkpoints are small, correctness-critical, and strongly consistent, so they live in a replicated consistent store (Raft-backed KV or a small SQL table) - the current_version must be linearizable for the CAS to be safe. Snapshots are a disposable blob cache keyed by stream. The read models are whatever each projection needs (SQL, search, cache); the store imposes only that a projection fold the global stream idempotently on position.
Bottlenecks & Scaling
Where it breaks first, in order, and the fix for each.
1. A hot aggregate serializes all its writes on one leader. Every append to account-42 is version-checked on one partition leader, so a single very-hot aggregate caps at that leader’s single-stream append rate. You cannot shard one stream - its order is irreducibly serial.
Fix: this is inherent and usually fine (one real-world aggregate rarely needs more than a few thousand appends/sec). Where it is not, model smaller aggregates (split a giant aggregate into many streams so load spreads across partitions) - a domain fix, not an infra one. Never split one stream’s order to parallelize it; that reintroduces lost updates.
2. Append throughput caps per partition. One partition fsyncs and replicates serially, capping at ~10K appends/sec.
Fix: more partitions, keyed by hash(stream_id). Streams spread across partitions, so aggregate throughput scales with partition count. Partition count caps both write parallelism and projection parallelism, so size it for peak (deep dive BoE: ~32-64).
3. The global $all order is a throughput ceiling or a merge cost. A single global sequencer stamping every event is a hot spot; a merged per-partition order needs a low-water-mark gate.
Fix: prefer per-partition monotonic positions merged into a defined $all order (by partition, gated on a low-water mark so no gap fills in after a reader passes it). This scales writes linearly with partitions; the price is that “global order” is a defined merge, not wall-clock - which projections do not care about as long as it is stable and resumable.
4. Projection lag under fan-out and rebuilds. Ten projections each read the full flow, and a rebuild re-reads the entire log - saturating read bandwidth and lagging read models behind writers. Fix: projections are decoupled by the log - a slow one lags its own checkpoint without touching writers or other projections. Serve catch-up reads from follower replicas to spread read load off leaders; parallelize a projection across partitions (one worker per partition) where its fold is per-stream and commutative across streams; autoscale projectors on checkpoint lag. Keep rebuilds throttled and off the hot leaders.
5. Storage grows without bound (never delete). The log is the source of truth and grows ~1.3 TB/day forever, so disks fill. Fix: tiered storage is the plan, not an add-on - hot recent segments on SSD for fast appends and catch-up, cold old segments demoted to object storage (cheap, slower), with the index knowing where each segment lives. Replays of old events pull from cold storage. Snapshots mean most loads never touch cold events, so cold-tier latency rarely matters on the command path.
6. Loading long aggregates is slow. A million-event stream is too slow to fold per command. Fix: snapshots (deep dive 3) bound load cost to the tail length regardless of total history. Snapshot long streams on an event-count trigger; skip short ones.
7. Concurrency conflicts storm a hot stream. If many writers truly contend on one aggregate, the optimistic retry loop can livelock (everyone conflicts, retries, conflicts again). Fix: optimistic CC is ideal for low contention (the common case). For a genuinely hot contended stream, serialize commands to that aggregate through a single in-memory handler (an actor/consumer per aggregate that processes its commands one at a time), turning optimistic retries into an ordered queue - no wasted retries. Or redesign the aggregate boundary (#1). Back off retries with jitter meanwhile.
8. Checkpoint or metadata store is a single point of failure. If current_version or a projection checkpoint lives on one node, its loss corrupts the CAS or loses projection progress.
Fix: keep stream metadata and checkpoints in a Raft-replicated consistent store (current_version must be linearizable for the CAS to be correct); replicate the event log RF 3 with quorum acks and min.insync=2 so an acked append survives a node loss and is never reordered within its stream.
9. Poison event stalls a projection. One event a projection cannot apply (bad data, a constraint violation) blocks its ordered progress - you cannot skip it blindly without a gap. Fix: bounded retries, then route the poison event to a dead-letter record with its position and reason, alert, and advance past it - accepting that read model is now missing that one effect until reconciled, rather than stalling the whole projection. Reconcile by fixing the projector and rebuilding from 0 (the log still has the truth).
10. Schema drift in events over years. Event shapes change over a multi-year log; old events no longer match current code. Fix: version events and upcast old shapes to current on read (a transform in the read path), so folds and projections always see the current shape. Never rewrite old events (immutability); transform them on the way out. Snapshots carry a schema version and are rebuilt from upcasted events when their shape changes.
Shard key, stated plainly: the aggregate (stream) id is the partition key via hash(stream_id) % N. It is simultaneously the unit of ordering (one stream, one serializing leader, strict version order), the unit of concurrency control (the CAS on current_version is local to that leader), and the unit of write parallelism (different streams, different partitions). The global position is the separate, orthogonal ordering token the read side keys on - the unit of deterministic projection order and of idempotency. Two keys, two jobs: stream id for safe writes, global position for resumable reads.
Wrap-Up
The trade-offs that define this design:
- Store events, derive state. The log of immutable events is the source of truth and current state is a fold over it - we trade the simplicity of updating a row for complete history, perfect auditability, and the ability to build any read model after the fact and rebuild it exactly. The cost is that every read of current state is a fold, which snapshots bound and projections amortize.
- Optimistic concurrency on the expected version, not locks. The CAS on stream version serializes concurrent writers to one aggregate with no lost updates and no held locks - cheap and correct under low contention. We trade pessimistic locking for a retry loop, and accept that a genuinely hot contended stream must be handled by a single-writer actor or a smaller aggregate boundary, because one stream’s order is irreducibly serial.
- Strong per-stream, eventual cross-stream (CQRS). Writes are linearizable within an aggregate; read models are eventually consistent and lag by a bounded window. We trade global read-your-write (clients needing it read the write side) for independent, scalable, rebuildable projections that never block or couple to writers.
- Catch-up subscriptions on one global position. Projections read one deterministic global order from a single checkpoint number, catching up then tailing live, idempotent on position so at-least-once delivery becomes effectively-exactly-once - without any cross-store distributed transaction.
- Never delete, so tier storage. Infinite retention is the feature, which makes tiered hot-SSD / cold-object storage the storage plan and snapshots the thing that keeps the command path fast as history grows forever.
One-line summary: a distributed event store appends immutable events to per-aggregate streams partitioned by stream id, enforces strict ordering and no lost updates with an optimistic compare-and-set on the expected stream version at the single owning partition leader, and feeds many independent CQRS read models through durable catch-up subscriptions over one global-ordered position that each projection checkpoints and applies idempotently - strongly consistent per aggregate on the write side, eventually consistent and fully rebuildable on the read side, over a log that is never deleted and tiered to cold storage.
Comments