Scaling Writes

One database leader commits about 1,000 writes a second, because every commit waits for a 1 ms disk flush. Fifteen batched shards absorb 1,000,000 with room to spare.

Pick a design and press Run. Watch a million writes a second arrive and see where they pile up. Then we build each layer from zero: shards, partition keys, the hash ring, batching, queues, conflict rules and the storage engine.

You need to know that a database keeps what you write and that a network call takes time. A little Python helps for the code. We build the rest here.

The read side of the same database is the sister lesson, Scaling Reads. We work every number on this page by hand and label the illustrative ones.

Absorb a million writes a second

Illustrative model: 1,000,000 writes a second on average, with bursts of up to about 12%. One commit costs 1 ms of disk flush; a batch of 100 writes shares one flush. Chapter 9 derives the 15.

Chapter 0

The Write Wall

Find the one disk flush that every write must wait for, and see why no cache can hide it

An ad network logs every ad shown and every tap. Advertisers pay per event, so the system must keep each event once and never lose it. On launch day the forecast is 1,000,000 writes a second. The whole system starts as one Postgres database.

The read side has escape hatches. A copy of the data can answer a read. A cache can reuse an old answer. A write has neither. It is new information, and one place must record it for good before anyone hears "saved".

What "committed" costs

Postgres first appends each change to the write-ahead log (WAL), one append-only file of changes. Then it calls fsync, a system call that returns only when the disk confirms the bytes are on stable storage. Only then does the client hear that the commit succeeded. A crash one instant later cannot erase it.

One leader has one WAL. Every write from every table goes through it. Say one fsync takes tf seconds and each commit waits for its own fsync. How many commits fit in a second?

Say it aloud

C equals one divided by t-f.

C
C the ceiling: durable commits per second that one log can do, one at a time.
tf
t-f the time of one fsync, in seconds. About 0.001 s on network-attached cloud disk.
In plain words

Each commit holds the log for one fsync of t-f seconds. Count how many t-f slots fit in one second. That count is the ceiling C.

With numbers

With an illustrative t-f of 1 ms: C = 1 / 0.001 s = 1,000 commits a second. The forecast is 1,000,000, so the gap is 1,000,000 / 1,000 = 1,000 times.

What happens to the writes that do not fit? They wait in line. Call the arrival rate λ (writes per second) and the time the overload lasts T.

Say it aloud

Q equals lambda minus C, times T.

Q
Q the backlog: writes accepted but not yet committed.
λ
lambda the arrival rate, in writes per second.
C
C the ceiling from above, in commits per second.
T
T how long arrivals stay above the ceiling, in seconds.
In plain words

Each second, lambda writes arrive and C leave. The difference stays behind. Multiply it by the T seconds the overload lasts to get the backlog Q.

With numbers

With made-up numbers: a spike of lambda = 3,000 a second against C = 1,000 for T = 60 s. Q = 2,000 × 60 = 120,000 writes waiting in memory, each one crash away from loss.

Push writes into one log

Blue is what arrives, teal is what the log commits, warm is the backlog. Drag the arrival rate past 1,000 and watch the line climb.

3,000/s

Illustrative: a steady arrival rate and a fixed 1 ms fsync. Real fsync times vary with the disk, so measure yours.

The failure, as symptom, measurement and fix

The symptom is rising write latency with no errors, while disk throughput in MB/s looks low. Measure commits per second against the fsync ceiling, and the p99 of WAL flush time. The fix is a new shape for the system: the next nine chapters.

The road

  1. A bigger box or more boxes: what a faster disk buys, and what many leaders buy.
  2. Sharding: split the data so each write has one home among many.
  3. Hot keys: why one popular key can melt one shard.
  4. Consistent hashing: add a shard and move a fair share, not everything.
  5. Batching: let one fsync carry 100 writes.
  6. Queues and backpressure: absorb bursts and drain them.
  7. Multi-leader writes: two regions write the same record.
  8. LSM tree or B-tree: the bytes the disk writes for each byte of data.
  9. Assembling the write path: the hero, derived.
  10. Field guide: numbers, checklist, code and links.
One Postgres leader commits each write with its own 1 ms fsync. A team adds two read replicas. What happens to the write ceiling?

Chapter 1

A Bigger Box or More Boxes

Price a faster disk against many small leaders, and find where each one stops

The first idea is a bigger machine. On a write path the useful upgrade is not more cores. It is a disk with a faster fsync, such as a local NVMe drive instead of network storage. This is vertical scaling: one leader, made faster.

Tier (illustrative)Diskfsync tfCeiling 1 / tf
Smallnetwork SSD1.0 ms1,000 /s
Largelocal NVMe0.4 ms2,500 /s
X-Largefast local NVMe0.25 ms4,000 /s

The best tier gives 4 times the ceiling. A disk ten times faster than the small tier, at 0.1 ms, still gives only 10,000 a second. That is 100 times short of the target. A single log on a single disk cannot close a 1,000-times gap at any price.

The other idea is horizontal scaling: many independent leaders, each with its own WAL and its own fsync. Each takes a slice of the writes. Call the target rate λ and the ceiling of one leader c. How many leaders do you need?

Say it aloud

N equals lambda over c, rounded up.

N
N the number of leaders (shards) needed.
λ
lambda the target write rate, in writes per second.
c
c the ceiling of one leader, in writes per second.
⌈ ⌉
rounded up you cannot run part of a leader, so any fraction becomes one more.
In plain words

Divide the target rate lambda by what one leader c can commit. Round up. That is how many leaders N must share the load.

With numbers

With lambda = 1,000,000 and c = 1,000 (no batching yet): N = 1,000 leaders. If the real ceiling is 800, N = 1,250. A 20% error in c costs 25% more machines, so measure c.

Set a target and count boxes

Pick a tier for the single box and drag the target. Teal is a box's ceiling; blue is the target. The dots are the small boxes horizontal scaling needs.

19,000/s

Illustrative tiers. We assume each small box commits 1,000 writes a second, one fsync per write.

Horizontal scaling has its own bill. A thousand leaders means a thousand things to patch, back up and watch. It also removes a single point of failure: losing one of 1,000 leaders loses 0.1% of capacity, not all of it.

VerticalHorizontal
Ceilingbounded by one disk's fsyncgrows with N
One failurestops all writesstops 1/N of writes
Operationsone machineN machines, routing, rebalancing
Right calla gap of 2 to 4 timesa gap of 10 times or more

The failure, as symptom, measurement and fix

The symptom: a bigger instance shows idle CPUs and the same write ceiling. Measure fsync time before and after the upgrade. The fix: when the target is far past what one disk can flush, add leaders.

The target is 1,000,000 writes a second. One leader commits 1,000. With no batching, how many leaders do you need?

Chapter 2

Sharding

Give every write one home among many leaders, and choose the rule that picks it

A shard is a slice of the data with its own leader, its own WAL and its own fsync. Sharding splits one dataset across many shards, so the write load splits too. Each write needs a rule that names its shard. The read path must use the same rule, or the data becomes unfindable.

The usual rule takes one field of the write, the partition key, and runs a hash on it. A hash turns any key into a number that looks random, so similar keys land far apart. Call the key k and the number of shards N.

Say it aloud

s equals hash of k, mod N.

s
s the shard number, from 0 to N minus 1.
hash(k)
hash of k a large number computed from the partition key k, such as a click ID.
mod
mod the remainder after division, so the result always lands in 0 to N minus 1.
N
N the number of shards.
In plain words

Hash the key k to a big number. Divide by N and keep the remainder. The remainder s is the shard that owns the write.

With numbers

With made-up numbers: hash("click-8f2a") = 7,302,519 and N = 1,000. The remainder is 519, so shard 519 owns it. The next click hashes somewhere else entirely.

The other family is range sharding: each shard owns a contiguous range of a sort key. Shard by hour, and "everything from the last hour" sits on one shard. That is fast for reads. For a live stream it is a trap.

Route the stream two ways

Each blue dot is a write. Pick a rule and watch which of the 24 shards fill. The teal line is each shard's ceiling.

Illustrative: 24,000 writes a second over 24 shards with a ceiling of 1,500 each.

Every write in a live stream has the timestamp "now". So every write lands on the shard that owns the current hour. The other 23 shards sit idle with old data. This is a hot shard: Chapter 0's wall, rebuilt inside a sharded system.

Hash sharding has a price too. "Every click for campaign 44012" now lives on all shards. Answering it means asking every shard and merging the results, a scatter-gather. A common middle path hashes on one key to pick the shard, then stores rows sorted by time inside each shard.

pythondef shard_for(click_id: str) -> int:
    return stable_hash(click_id) % NUM_SHARDS      # same rule for writes AND reads

def write_click(ev):
    shards[shard_for(ev.click_id)].execute("INSERT INTO ad_events ...", ev)

def get_click(click_id):
    return shards[shard_for(click_id)].execute("SELECT ... WHERE click_id = %s", click_id)

The failure, as symptom, measurement and fix

The symptom: one shard at its ceiling while the fleet average looks calm. Measure write rate per shard, never only the fleet average. The fix: route by a key whose values arrive spread out, not by time.

A team range-shards ad events by hour across 24 shards. What happens to 24,000 writes a second?

Chapter 3

Hot Keys and the Partition Key

Work out how much traffic the most popular key draws, and split it with salt

Hash by campaign_id and campaign reports stay on one shard. It looks right. But campaigns are not equally popular. A national brand launch draws far more taps than a small shop. A hash sends every write of one key to the same shard, no matter how many writes that key gets.

Popularity often follows Zipf's law. Rank the keys from most to least popular. The key at rank k then gets traffic in proportion to 1 / ks. The skew s sets how steep the drop is; s = 1 is the classic case. To turn proportions into shares, divide by their total. For s = 1 that total is the harmonic number HN = 1 + 1/2 + 1/3 + … + 1/N.

Say it aloud

p-k equals one over, k to the s times H-N.

pk
p-k the share of all writes that the key at rank k gets, from 0 to 1.
ks
k to the s the rank k raised to the skew s. Rank 1 is the most popular key.
HN
H-N the total of 1 / ks over all N keys, so the shares add up to 1. For s = 1 it is about ln N + 0.577.
In plain words

Give the key at rank k a weight of 1 over k to the s. Add the weights of all N keys to get H-N. The share p-k is the key's weight divided by H-N.

With numbers

With an assumed 12,000 active campaigns and s = 1: H-N = 9.97, so p-1 = 1 / 9.97 = 10.0%. Of 1,000,000 writes a second, rank 1 gets 100,302. Against a 1,000 a second shard, that is 100 times over.

RankShareWrites /s of 1,000,000Times a 1,000/s shard
110.0%100,302100
25.0%50,15150
33.3%33,43433
Top 522.9%229,0225 keys, one shard each

This is a hot key. The fleet average looks healthy, and one shard melts. Fewer keys make it worse: with 100 campaigns, H-N is 5.19 and the top key takes 19%.

Turn up the skew

Twenty keys land on twenty shards. Yellow is the shard holding the top key. Drag the skew, then salt the top key into four buckets.

1.00

Illustrative toy: 6,000 writes a second over 20 keys and 20 shards with a ceiling of 1,000 each. The key-to-shard map is a fixed hash, so two keys can share a shard.

There are two fixes.

Fix 1: partition by a key with no popularity at all, such as click_id, which every event gets once. Campaign reports then need scatter-gather.

Fix 2: keep the key and add a salt, a small number from 0 to B − 1, so one campaign writes to B buckets. AWS documents this for DynamoDB as write sharding with random or calculated suffixes. Size B so each bucket fits: ⌈100,302 / 1,000⌉ = 101 buckets. A read of that campaign then gathers from all 101.

The failure, as symptom, measurement and fix

The symptom: one shard far above the rest, every day, at the same hours. Measure per-key write rates on that shard by sampling. The fix: salt the hot keys, and give cold keys one bucket.

Same skew s = 1, same total traffic, but 100 campaigns instead of 12,000. What happens to the top campaign's share?

Chapter 4

Consistent Hashing

Add a shard and move only its fair share of the keys

The fleet must grow from 1,000 shards to 1,001. With hash(k) mod N, a key stays on its shard only if its remainder is the same for 1,000 and for 1,001. That holds for 1 key in 1,001. So 99.9% of all data must move while the stream keeps arriving.

Consistent hashing removes N from the rule. Picture a ring of hash values, from 0 to 232. Hash each shard to a point on the ring. Hash each key too. A key belongs to the first shard point you meet walking clockwise from it.

Add a shard and it takes one arc from its clockwise neighbour. No other key moves. With N shards spread evenly, the new shard claims about its fair share.

Say it aloud

f equals one over N plus one.

f
f the fraction of all keys that change shard when one new shard joins the ring.
N
N the number of shards before the addition.
In plain words

After the addition there are N + 1 shards, and the new one owns about one share. Only the keys in that share move. With mod N, a key stays only 1 time in N + 1, so N / (N + 1) of all keys move.

With numbers

For N = 1,000: the ring moves f = 1 / 1,001 = 0.1% of keys. Mod N moves 1,000 / 1,001 = 99.9%. Same operation, 1,000 times less data to copy.

Add a shard to the ring

400 keys sit on a ring of 8 shards. Press Add shard and count the keys that move. Turn on virtual nodes and compare the biggest shard with the average.

Illustrative toy: 400 keys and a deterministic hash. The mod N count uses the same 400 keys going from 8 to 9 shards.

One point per shard leaves uneven arcs by chance. In our simulation of random rings, the biggest shard owned 2.7 times the average with 8 shards and 7.3 times with 1,000. Virtual nodes fix this: hash each shard to many points, say 150. Each shard's total then averages out. With 150 points, the biggest shard dropped to 1.12 times the average for 8 shards and 1.29 times for 1,000. Cassandra's docs describe this design: tokens on a ring, with several tokens per node.

A ring of 1,000 shards × 150 points has 150,000 sorted entries. A binary search finds a key's owner in about 17 comparisons, far less than the network trip that follows.

The failure, as symptom, measurement and fix

The symptom: adding one machine starts a migration of nearly all data. Measure the fraction of keys whose owner changes in a dry run. The fix: a ring with virtual nodes, then copy the moved arc, dual-write it, and cut over.

What problem do virtual nodes solve on a hash ring?

Chapter 5

Batching Behind One fsync

Let one disk flush carry many writes, and pay for it with a short wait

An fsync costs about the same for 200 bytes or 20 kilobytes. The cost is the round trip to stable storage, not the size. So put many writes in one WAL append and flush once. This is batching. Call the number of writes per flush the batch size b.

Say it aloud

X equals b over t-f.

X
X the write ceiling of one shard, in writes per second.
b
b the batch size: writes that share one fsync.
tf
t-f the time of one fsync, in seconds.
In plain words

Each flush takes t-f seconds and commits b writes. Divide b by t-f to get the writes per second X.

With numbers

With b = 100 and t-f = 1 ms: X = 100 / 0.001 = 100,000 writes a second per shard. The target then needs 1,000,000 / 100,000 = 10 shards instead of 1,000.

The price is waiting. A batch must fill before it flushes. At an arrival rate λ, filling b writes takes b / λ seconds. So the writer flushes on whichever comes first: b writes, or a timer of T seconds.

added wait = min(b / λ, T)  ·  at λ = 1,000,000/s: 100 / 1,000,000 = 0.1 ms  ·  at λ = 500/s: 100 / 500 = 200 ms, so a T = 10 ms timer fires first with 500 × 0.01 = 5 writes

Fill a batch, then flush

Blue dots arrive; each warm box is one flush of one fsync. Pick a traffic level and drag the batch size. The timer is 10 ms.

40

Illustrative: fsync time held at 1 ms whatever the batch holds, which is close for batches of a few tens of kilobytes. The drawing thins the arrival dots to stay readable.

Pick b from a stated budget, not a round number. Say the slowest traffic you serve is 2,000 a second and you allow 20 ms of added wait. Then b = 2,000 × 0.020 = 40. At 1 ms per flush that gives 40,000 a second per shard, so 25 shards for the target.

The same idea appears in real tools. Postgres has commit_delay: a committing session waits that many microseconds so others can share its flush. The Kafka producer has batch.size (a byte limit, default 16,384) and linger.ms (a wait, default 5 ms since Kafka 4.0). That is the count-or-timer rule.

pythonclass BatchWriter:
    def __init__(self, max_batch=100, max_wait_ms=10):
        self.buf, self.max_batch, self.max_wait_ms = [], max_batch, max_wait_ms
    def add(self, ev):
        self.buf.append(ev)
        if len(self.buf) >= self.max_batch: self.flush()   # count trigger
    def on_timer(self):                                   # runs every max_wait_ms
        if self.buf: self.flush()                          # timer trigger
    def flush(self):
        batch, self.buf = self.buf, []
        conn.execute_many("INSERT INTO ad_events VALUES ...", batch)   # one commit, one fsync
        for ev in batch: ev.ack()                        # acknowledge only after the fsync

The failure, as symptom, measurement and fix

The symptom: write latency at night is far higher than at peak. Measure the batch size per flush and the wait per write by hour. The fix: add or shorten the timer.

fsync takes 1 ms. A writer flushes 100 writes per fsync. What is one shard's write ceiling?

Chapter 6

Queues and Backpressure

Put a durable buffer in front of the shards, size it from a burst, and decide what happens when it fills

Events arrive one at a time from millions of phones. Something must collect them into batches. That something is a durable queue, such as a Kafka topic. Producers append each event and get a fast acknowledgment. A writer reads up to b events and commits them with one fsync.

A queue does not add capacity. It buys time.

A breaking news story pushes arrivals to 1,300,000 a second for 90 s against a capacity of 1,000,000. By Chapter 0's backlog rule, Q = 300,000 × 90 = 27,000,000 events. At an assumed 200 bytes each, that is 5.4 GB. How long until the queue is empty again? Call the capacity μ and the arrival rate after the burst λ′.

Say it aloud

T-drain equals Q over, mu minus lambda-prime.

Tdrain
T-drain the seconds until the backlog is gone.
Q
Q the backlog when the burst ends, in events.
μ
mu the capacity of the writers and shards, in events per second.
λ′
lambda-prime the arrival rate after the burst, in events per second. It must be below mu.
In plain words

After the burst, the shards commit mu a second while lambda-prime new events arrive. The difference eats the backlog. Divide Q by that difference to get T-drain.

With numbers

With Q = 27,000,000, mu = 1,000,000 and an illustrative lambda-prime of 800,000: T-drain = 27,000,000 / 200,000 = 135 s. The newest event at the peak waits Q / mu = 27 s.

Survive a burst

The burst lasts 90 s. Drag its height. Warm is the backlog in the queue; the dashed line is the queue's disk budget of 8 GB.

1.30 M/s

Illustrative: capacity 1,000,000 a second, 800,000 after the burst, 200 bytes per event, an 8 GB queue budget.

When the queue would fill anyway, the system needs a policy. This is backpressure: a signal that pushes back against the producers.

PolicyWhat it doesIts cost
Slow the producersthe queue refuses or delays new appendsonly works if producers can wait
Shed loaddrop writes past a depth limitreal data loss; fine for samples, not for billing
Add writersmore consumers drain fasteronly up to the shards' ceiling; takes time to start

The failure, as symptom, measurement and fix

The symptom: the backlog stays high long after traffic falls. Measure consumer lag in events and seconds, and compare it with the drain rule. The fix: keep capacity well above normal traffic, so μ − λ′ is large.

A burst leaves 27 million events queued. Capacity is 1,000,000 a second and traffic after the burst is 900,000. How long does draining take?

Chapter 7

Multi-Leader Writes

Let two regions write the same record, and choose a merge rule that keeps both writes

A campaign's budget lives in one row. Tokyo and Virginia both charge it. Sending every charge across the ocean to one leader adds a long round trip. With multi-leader replication, each region has a leader that accepts writes and later copies them to the other. Now two writes to the same row can cross in flight. That is a conflict.

The budget is $10,000. At true time 0 ms Tokyo charges $50 and writes $9,950. At 30 ms Virginia charges $75 and writes $9,925. Each started from $10,000. The correct budget is $9,875.

The simplest rule is last write wins (LWW): keep the write with the later timestamp, drop the other. It loses $50 even with perfect clocks. And if Virginia's clock runs more than 30 ms slow, its write looks earlier, so LWW keeps the older write. Cassandra and DynamoDB global tables (in their default eventual mode) both resolve concurrent writes this way, by timestamp.

Merge two charges

Teal is Tokyo, pink is Virginia. Drag how slow Virginia's clock runs, then switch the merge rule.

0 ms

Illustrative: one $50 charge and one $75 charge, 30 ms apart.

A CRDT (conflict-free replicated data type) is a structure whose merge never drops a write, in any order. For a counter it is the PN-counter. Each region r keeps its own running total of increases Pr and decreases Nr. A merge takes, per region, the larger of the two copies. Call the starting value v0.

Say it aloud

v equals v-zero, plus the sum over r of P-r, minus the sum over r of N-r.

v
v the counter's value after the merge: the budget left.
v0
v-zero the starting value, $10,000 here.
Σr
the sum over r add one term for each region r.
Pr
P-r the total that region r has added (top-ups).
Nr
N-r the total that region r has subtracted (charges).
In plain words

Each region counts only its own top-ups P-r and charges N-r. To read the value, start from v-zero, add every region's P-r and subtract every region's N-r. The rule uses no timestamp.

With numbers

Tokyo: P = 0, N = 50. Virginia: P = 0, N = 75. v = 10,000 + 0 − (50 + 75) = $9,875, whatever the clocks say.

CRDTs exist for data with an order-free merge: counters, sets, some maps. A record whose fields depend on each other has no such merge. For that, send its writes through one leader, or use consensus, as Spanner-style systems do.

The failure, as symptom, measurement and fix

The symptom: totals drift from the sum of their events, with no error logged. Measure a daily reconcile of the counter against its event log. The fix: a CRDT for counters, one home leader for other contended rows.

Tokyo charges $50 and Virginia charges $75 against $10,000 at nearly the same time. What does a PN-counter merge give?

Chapter 8

LSM Tree or B-Tree

Count the bytes the disk writes for each byte you asked it to store

Inside each shard, a storage engine puts rows on disk. Postgres keeps tables and indexes in 8 kB pages. A B-tree is a tree of such pages; a write finds its leaf page and changes it in place. With random keys, like our click IDs, two writes rarely share a page. So each 200-byte row can dirty one whole 8 kB page that must go back to disk.

Call the bytes the disk writes D and the bytes of data you asked to store U. Their ratio is the write amplification.

Say it aloud

W-A equals D over U.

WA
W-A write amplification: how many bytes hit the disk per byte of data.
D
D bytes the device physically writes, in bytes.
U
U bytes of data the application asked to write, in bytes.
In plain words

Count the bytes the disk writes, D, over some time. Count the bytes of rows you inserted, U. Divide D by U.

With numbers

With a toy B-tree that writes one 8,192-byte page per 200-byte row: WA = 8,192 / 200 = 41. The WAL record adds more on top.

An LSM tree (log-structured merge tree) never edits in place. A write goes to the WAL and to a sorted table in memory, the memtable. When the memtable fills, it goes to disk in one sequential pass as an immutable file, an SSTable. A background job, compaction, later merges SSTables and drops old versions. Compaction rewrites bytes, so an LSM tree has write amplification too. The RocksDB wiki says leveled compaction's is often larger than 10.

Count the disk bytes

Blue is the row you wrote. Purple is what the disk writes for it. Drag the row size and compare the two engines.

200 B

Illustrative disk: 50,000 random 8 kB page writes a second, or 500 MB/s sequential. Toy engines: the B-tree writes one page per row; the LSM tree has a write amplification of 12.

The B-tree pays at once, with random writes, on the path of every commit. The LSM tree pays a little at once, sequentially, and the rest later in the background. A disk does far more bytes a second sequentially than at random offsets. For 200-byte rows the toy gives 50,000 rows a second for the B-tree and 208,333 for the LSM tree.

Cassandra, HBase and RocksDB are LSM engines. Kafka's own storage is simpler still: an append-only log with no tree.

The LSM tree pays on reads instead. A key can sit in the memtable or in several SSTables, so a read may check many files. A Bloom filter per file answers "definitely not here" for most of them.

The failure, as symptom, measurement and fix

The symptom: disk write bandwidth is full while the row rate is modest. Measure device bytes written (from the OS) against bytes inserted. The fix: an LSM engine for scattered-key ingest, or keys that arrive in order.

Why does an LSM tree usually beat a B-tree on a stream of random-key inserts?

Chapter 9

Assembling the Write Path

Put every layer in the order an event travels, and size the fleet for 1,000,000 writes a second

Follow one tap. The phone sends the event to an API server. The server appends it to the queue and answers. A batch writer reads 100 events and routes each by hash(click_id) on the ring. The shard commits the batch with one fsync into an LSM engine.

Size the fleet. A batched shard does X = 100 / 0.001 = 100,000 writes a second. Chapter 0 showed that a log near its ceiling builds a backlog from every burst, so plan for 70% of it: 70,000. Then N = ⌈1,000,000 / 70,000⌉ = 15 shards, at 67% average load.

Now key the same events by campaign_id instead. The top campaign's 100,302 a second land on one shard that already carries 1/15 of the rest, 59,980. That shard holds 160,282, 1.6 times its ceiling. Salt the top key into 11 buckets on 11 shards: each bucket gets 9,118, and those shards carry 69,098, just under 70%. Batching shrank the salt from 101 buckets to 11.

Build the write path

1,000,000 writes a second arrive. Set the shard count and batch size, pick the partition key, and salt the hot key. Keep every bar under the dashed 70% line.

15

Illustrative: fsync 1 ms, the 70% target from this chapter, the Zipf shares of Chapter 3 (12,000 campaigns, s = 1). With campaign keys, other campaigns spread evenly; salt picks the buckets needed to fit under 70%.

LayerWhat it removesChapter
Shardsthe one-log ceiling2
Unskewed key + salthot shards3
Ring + virtual nodesmoving all data to grow4
Batchingone fsync per write5
Queuelost writes during bursts6
PN-counter, scopedlost charges across regions7
LSM enginerandom page rewrites8

Multi-leader stays narrow. Click events are distinct rows that never conflict, so those shards keep one leader each. Only the budget counters replicate across regions as PN-counters. And a pipeline of a few hundred events a second needs none of this: one leader clears it.

Keyed by click_id, the same events never make a hot shard. Keyed by campaign_id, they do. Why?

Chapter 10

Field Guide

Keep the terms, the numbers, a checklist and the core code in one place

A write is durable only after an fsync, and one log does one fsync at a time. Every layer here attacks that point: more logs (shards), more writes per fsync (batching), or a cheaper path to disk (LSM). The rest keeps the load even and the data correct.

TermMeaningWorked number
Ceiling C = 1 / tfcommits per second of one log1 ms fsync: 1,000 /s
Backlog Q = (λ − C)Twrites waiting during overload3,000 vs 1,000 for 60 s: 120,000
Shards N = ⌈λ / c⌉leaders needed1,000,000 / 1,000: 1,000
Zipf share 1 / (ksHN)traffic on the rank-k key12,000 keys, s = 1: top 10.0%
Ring move 1 / (N + 1)keys moved by one added shardN = 1,000: 0.1% (mod N: 99.9%)
Batch X = b / tfwrites per second with b per fsyncb = 100: 100,000 /s
Drain Q / (μ − λ′)time to empty a queue27 M / 200,000: 135 s
PN-counterv0 + ΣPr − ΣNr10,000 − 125 = 9,875
WA = D / Udisk bytes per data byte8,192 / 200 = 41 (toy B-tree)

Checklist

  1. Measure fsync time on your disk. Compute C.
  2. Divide the peak by the batched ceiling at 70%. That is N.
  3. Pick a partition key with no popularity. Salt the keys that must stay.
  4. Put the shards on a ring with virtual nodes.
  5. Flush on a count or a timer. Acknowledge after the fsync.
  6. Size the queue from your largest burst. Choose the backpressure policy now.
  7. Use multi-leader only for rows that need it, with a CRDT merge.
  8. Use an LSM engine for scattered-key ingest. Watch disk bytes written.
pythonimport bisect, hashlib, random

def h(s): return int(hashlib.md5(s.encode()).hexdigest(), 16) % 2**32

class Ring:
    def __init__(self, vnodes=150):
        self.vnodes, self.pts = vnodes, []                 # sorted [(position, shard)]
    def add(self, shard):
        for i in range(self.vnodes):
            bisect.insort(self.pts, (h(f"{shard}#{i}"), shard))
    def owner(self, key):
        i = bisect.bisect_left(self.pts, (h(key), ""))   # first point clockwise
        return self.pts[i % len(self.pts)][1]                # wrap past the top

def salted_key(campaign_id, buckets):
    return f"{campaign_id}#{random.randrange(buckets)}"  # reads gather all buckets

Keep going

Sources

The takeaway. Writes do not cache. Split the log, fill each fsync, keep every shard below its ceiling, and merge concurrent writes without dropping one.

Teach it back with Present or Teach. Then go back to the hero and explain why the middle design fails at the first burst.

Scaling Writes
Scaling Reads · Back to Gleams