Courses / System Design Interview / Chapter 23
Module 4 · Building Blocks III: Limits, Storage and Search · Chapter 23 of 49
Sharded Counters
Builds on Core Concepts: RPCs, Consistency, Failures and Time, Building Blocks: The Parts Every Design Reuses, Databases: Choosing, Replicating and Partitioning, Distributed Caches, Rate Limiters and Distributed Task Schedulers. Next up: AI Building Blocks: Inference, Embeddings, Retrieval and Agents.
Part 1 · The hot-key problem
A counter is one row
A post can collect thousands of likes in a minute when a film star shares it, and each like has to be counted. The obvious design stores a number next to the post and adds 1 for every like.
That design is correct and it has a ceiling. A counter is a single value, so every increment touches the same row, key or document. A counter on a viral post is the standard example of the hot key from the distributed cache chapter. Databases protect a row while it is being changed, by holding a lock or by retrying conflicting updates, so concurrent increments to one row wait in a line. The rate at which that line moves is fixed by how long one write takes, however many servers are sending likes.
The Firestore documentation says this plainly: you cannot update a single document at an unlimited rate, and frequent updates to one counter document eventually cause contention. Other stores differ in detail and share the shape of the problem. Redis INCR is atomic and a single key lives on one node. A relational row lock does the same job.
There are two separate failures to keep apart. The first is correctness: two clients that read the value, add 1 and write it back can overwrite each other, so likes are lost. As the rate limiter chapter showed, the fix is an atomic increment inside the database, such as SET n = n + 1. The second is throughput: even with correct atomic increments, writes to one row are serialised. The program below shows both.
Both failures in one run
Eight threads each add 200 likes to the same row of a SQLite table, 1,600 in all. Each thread has its own connection. In the first mode a thread reads the value, adds 1 in Python and writes it back. In the second the thread sends n = n + 1 to the database and lets it do the addition.
import os, sqlite3, tempfile, threading, time path = os.path.join(tempfile.mkdtemp(), "likes.db") db = sqlite3.connect(path, isolation_level=None) db.execute("PRAGMA journal_mode=WAL") db.execute("CREATE TABLE likes (post INTEGER PRIMARY KEY, n INTEGER)") db.execute("INSERT INTO likes VALUES (1, 0)") def worker(mode, times): c = sqlite3.connect(path, isolation_level=None, timeout=30) for _ in range(times): if mode == "atomic": c.execute("UPDATE likes SET n = n + 1 WHERE post = 1") else: # read, add in Python, write back n = c.execute( "SELECT n FROM likes WHERE post = 1").fetchone()[0] c.execute("UPDATE likes SET n = ? WHERE post = 1", (n + 1, ))
hot.py: the table and the worker
for mode in ("read-modify-write", "atomic"): db.execute("UPDATE likes SET n = 0") threads = [ threading.Thread(target=worker, args=(mode, 200)) for _ in range(8) ] t0 = time.perf_counter() for t in threads: t.start() for t in threads: t.join() took = time.perf_counter() - t0 n = db.execute("SELECT n FROM likes").fetchone()[0] print(f"{mode:18} expected 1600, got {n}, {took:.2f} s")
hot.py: eight threads, two modes
read-modify-write expected 1600, got 102, 3.90 s atomic expected 1600, got 1600, 4.08 s
Python 3.12.10 on this machine. The lost updates and timings vary from run to run; this is one real run.
The read-modify-write version should have counted 1,600 and counted 102 in this run, so about 94 percent of the likes vanished. Threads read the same old value, each wrote back the same value plus one, and the later writes overwrote the earlier ones. An earlier run produced 200. The exact number changes every time, which is itself a warning sign.
The atomic version counted all 1,600. It also took about 4 seconds on this machine, roughly 400 increments per second. SQLite locks the whole database file for each write transaction, so this number measures one writer at a time and not row locks. Its point is the shape: the throughput is a property of how fast one serialised writer commits, and sending more threads does not raise it.
Where the ceiling comes from
A real client-server database commits writes with an fsync, a request to push the change from memory to stable storage, and the row stays locked for part of that time. The ceiling follows from it: if one write holds the row for a millisecond, the line moves at most about a thousand writes per second. The run above measured about 400 per second on this machine, and the limit belongs to that one row. The rest of the cluster is idle while the line for the one row grows.
A burst bigger than the ceiling does not fail cleanly. Requests wait, time out and are retried, and the retries add load. The user sees a spinner or a lost like. The system as a whole may be nearly idle, because the other posts are quiet. This is why the problem is solved in the data model, by changing what is stored, and not by adding machines.
The idea of the next lesson is to stop storing one number. Store several numbers that together add up to the count, and let each write pick one of them.
In the run, the read-modify-write mode counted 102 of 1,600 likes. What caused the loss?
- Several threads read the same value before any of them wrote. Each wrote back its old value plus one, so later writes overwrote earlier ones.
Does an atomic n = n + 1 remove the hot-key problem?
- It fixes correctness, because no update is lost. It does not remove the ceiling, since writes to the one row still happen one at a time.
Why do retries make a hot key worse?
- A request that times out is sent again, which adds more waiting writes to a row that is already the bottleneck.
Part 2 · Sharded counters
Many rows, one total
A sharded counter, also called a distributed counter, replaces the single row with N rows, the shards. The total is the sum of the shards. To add a like, the writer picks one shard at random and increments only that one. Two writers pick different shards most of the time, so they no longer wait for each other. With N shards the write ceiling rises to about N times that of one row, as long as the writes spread evenly.
The Firestore documentation describes exactly this design. It splits a counter into a subcollection of shard documents, says the total is the sum of all the shards, and says that a counter with 10 shards can handle ten times the writes of a plain one. Its own sample code assumes about one increment per second per shard, so the number of shards you need depends on the store, which the fourth lesson of this chapter takes up.
Watch for the likes landing on different rows instead of one
Read it as steps
Each like adds to one random shard, and the page adds the shards to show the total.
The scene shows five likes landing on four rows, two of them on the same shard by chance, and then a reader adding the rows up. The price of the design is on the read side: a read must now fetch N values and add them, where it used to fetch one. The documentation notes that read cost grows with the number of shards.
Measuring the effect
A model measures the effect without a database cluster. Each shard is a lock that a write holds for 2 milliseconds, standing in for the time a store holds a row while it commits. Sixteen threads each make 100 writes, 1,600 in total, and each write picks a shard at random. The program runs it for 1, 4, 16 and 64 shards.
import random, threading, time # time a store holds a row's lock to commit one write WRITE_MS = 2 THREADS, EACH = 16, 100 def run(shards): locks = [threading.Lock() for _ in range(shards)] counts = [0] * shards def worker(seed): rnd = random.Random(seed) for _ in range(EACH): i = rnd.randrange(shards) # pick a random shard # row lock, held while committing with locks[i]: time.sleep(WRITE_MS / 1000) counts[i] += 1
shards.py: a lock per shard, held for 2 ms per write
ts = [
threading.Thread(target=worker, args=(s, ))
for s in range(THREADS)
]
t0 = time.perf_counter()
for t in ts:
t.start()
for t in ts:
t.join()
took = time.perf_counter() - t0
assert sum(counts) == THREADS * EACH
return took, sum(counts)for n in (1, 4, 16, 64): took, total = run(n) print( f"shards={n:3} total={total} {took:5.2f} s " f"{total / took:7,.0f} writes/s" )
shards= 1 total=1600 3.68 s 435 writes/s shards= 4 total=1600 1.06 s 1,504 writes/s shards= 16 total=1600 0.41 s 3,885 writes/s shards= 64 total=1600 0.27 s 5,977 writes/s
Python 3.12.10 on this machine. The timings vary from run to run.
With one shard, the 1,600 writes took 3.68 seconds, or 435 writes per second: about 1 divided by 2 ms is the ideal 500, so the model is close to that. With 4 shards the rate was 1,504 per second, with 16 it was 3,885 and with 64 it was 5,977. Throughput grew with the shard count, but less than proportionally. Random choice sometimes puts two writes on the same shard while another sits idle, and with 16 threads there are never more than 16 writes to spread, so more than 16 shards gives little.
Be clear about what this is. It is a model of a store that locks a row for 2 ms per write, and not a measurement of any database. The SQLite run in the previous lesson showed a real serialised writer, and this run shows what happens to the line when it is split into several. The shape of the result, a rise that flattens, is what matters, and real stores show the same shape at different absolute rates.
Retries and shard names
Two practical details decide whether the counter stays correct. A retried request must not count twice: the network can deliver a like request two times, and a plain increment would add 2. The usual guard is an idempotency key, as in the task scheduler chapter: a separate table of likes keyed by user and post. The insert and the increment run in one transaction, and the increment happens only when the insert succeeds, so a repeated request fails on the key and adds nothing. And the shard row is named by a fixed pattern such as post-9:shard-3, so any server can find all N rows of a counter by arithmetic, without a lookup.
What changes when you go from one counter row to N shards, for writes and for reads?
- Writes spread over N rows, so the ceiling is about N times higher. A read must fetch and add N rows instead of one.
In the model, why did 64 shards not give 64 times the throughput of one?
- Random placement leaves some shards idle while others get two writes at once, and 16 threads can only have 16 writes in flight at a time.
What would break if the writer picked the shard by user id instead of at random?
- A very active user, or a bot, would always hit the same shard and recreate the hot key on a smaller scale.
Part 3 · Reading the total
Summing on read
The simplest read is to fetch every shard and add them. It gives the exact total at that moment, and the cost grows with the number of shards. For a counter shown on a page that thousands of people open each second, that is too many reads: with 8 shards, each page view costs 8 row reads, and 1 lakh views a minute cost 8 lakh.
The usual remedy is a cached total. A background job or the first reader after expiry adds up the shards and stores the result under a single key, with a short time to live. Page views read the one cached number. The total on the page is then slightly behind the truth, which is acceptable for a like count: nobody can tell whether a post has 60,228 or 60,231 likes.
This trades freshness for cost, and the trade is the same as in the cache chapter: how stale a value may be, and what a stale value costs. A like count may lag by seconds. A stock count shown at checkout must not lag at all, and an inventory counter should not be sharded this way in the first place, since the check 'is there stock left' needs the exact total at the moment of the write.
The program below simulates a counter that gets about 1,000 likes per second for a minute, spread over 8 shards. The cached total is refreshed every 5 seconds. It prints the read cost of the two strategies and the largest gap between the cache and the exact count.
What the cache costs
import random rnd = random.Random(5) SHARDS = 8 shards = [0] * SHARDS cached, cached_at = 0, 0 errors = [] reads_of_shards = 0 for second in range(1, 61): # about 1,000 likes per second for _ in range(rnd.randint(800, 1200)): shards[rnd.randrange(SHARDS)] += 1 # refresh the cache every 5 s if second % 5 == 0: cached, cached_at = sum(shards), second reads_of_shards += SHARDS exact = sum(shards) errors.append(exact - cached) print("shard reads in 60 s with a 5 s cache:", reads_of_shards) print("shard reads if every second summed :", 60 * SHARDS) print("largest gap between cache and truth :", max(errors), "likes") print( f"gap at second 59: {errors[58]} likes, " f"{errors[58] / (errors[58] + cached):.2%} of the true total" ) print("at second 60 the cache was just refreshed: gap", errors[59])
readtotal.py: exact sum every second against a cache refreshed every 5 s
shard reads in 60 s with a 5 s cache: 96 shard reads if every second summed : 480 largest gap between cache and truth : 4227 likes gap at second 59: 3905 likes, 6.09% of the true total at second 60 the cache was just refreshed: gap 0
Python 3.12.10 on this machine. Deterministic: seeded.
Refreshing every 5 seconds read the shards 96 times, which is 12 refreshes of 8 shards each. Summing on every second would have read them 480 times. That is a fivefold saving, and the saving applies to the shards only, because the many page views read the cache either way.
The price is the gap. Just before a refresh the cache was behind by up to 4,227 likes in this run. At second 59, four seconds after the previous refresh, it showed 3,905 fewer likes than the truth, 6 percent of the total. Just after a refresh the gap is zero, as at second 60. The lag is bounded by the refresh interval multiplied by the write rate, so the way to tighten the number is to shorten the interval and not to add shards.
A busy post makes the percentage small, and a new post makes it large: when a post has 50 likes in total, a lag of 5 seconds is no longer invisible. Some systems therefore refresh quickly for young counters and slowly for old ones, or keep the cached total up to date by also applying each increment to it. That second approach puts a hot key back, in the cache, so it is used with care.
A user who taps like expects to see the number go up at once, even though the cached total will not change for a few seconds. The client handles that by adding 1 to what it shows after its own request succeeds, a small case of the read-your-writes idea from the databases chapter. Other users see the cached value, which catches up at the next refresh. Nobody compares the two numbers, so the shortcut is safe for a like count.
Part 4 · Choosing and changing the number of shards
How many shards
The number of shards, N, is a decision about three costs. More shards raise the write ceiling. They also raise the cost of every read that sums them, and they use more storage and more keys to manage. A reasonable method starts from the rate you must support and the rate one shard sustains.
Let w be the peak write rate for one counter and c the rate one shard can take. The shards needed are w divided by c, rounded up, and then multiplied by a headroom factor so that no shard runs near its limit, since random placement is uneven. With a headroom of 2, a shard runs at half its ceiling on average.
import math # sustained writes per second one shard row handles (assumed) PER_SHARD = 100 HEADROOM = 2 # keep shards at half load def shards_needed(writes_per_s): return max(1, math.ceil(writes_per_s * HEADROOM / PER_SHARD)) for rate in (5, 80, 450, 3_000, 25_000): n = shards_needed(rate) print( f"{rate:>7,} likes/s -> {n:>4} shards, a read sums {n} rows") # Growing N never loses counts: old shards stay, new ones start at zero. shards = [120, 98, 143, 110] total_before = sum(shards) shards += [0, 0, 0, 0] print("total before growing:", total_before, "| after:", sum(shards))
chosen.py: shards for a write rate, and growing the count
5 likes/s -> 1 shards, a read sums 1 rows 80 likes/s -> 2 shards, a read sums 2 rows 450 likes/s -> 9 shards, a read sums 9 rows 3,000 likes/s -> 60 shards, a read sums 60 rows 25,000 likes/s -> 500 shards, a read sums 500 rows total before growing: 471 | after: 471
Python 3.12.10 on this machine. Deterministic. The 100 writes per second per shard is an assumption; measure your own store.
A counter that sees 5 likes per second needs no sharding, and one shard is the right answer. At 450 likes per second the method gives 9 shards, at 3,000 it gives 60, and at 25,000 it gives 500. The last number is a warning. A read that adds 500 rows is expensive, and a cached total becomes the main way to read it. Past a point the better answer is a batching tier: servers add up the likes they have seen for a second in memory or in a queue and write one increment of 40, not forty increments of 1, so the database sees a rate that no longer depends on the number of fans.
Changing N while counting
Traffic is uneven, and a counter that was quiet can become hot in an hour. The count of shards should be able to grow without stopping the counter. This is easy because the total is a sum. Adding shards means creating new rows that start at zero, and from then on writers choose among N + K rows. The old shards keep their values, so the total is unchanged at the moment of the change.
The last lines of the run show this with four shards holding 471 likes in total. After four more empty shards were added, the sum was still 471. Nothing had to be copied or recalculated.
Shrinking is harder, since a shard cannot just be deleted without losing its count. The safe way is to stop writing to the shard, add its value to another shard in one atomic step, and then delete it. A simple policy is never to shrink, because an unused shard costs almost nothing.
One more detail follows from the fixed shard names of the second lesson. Decide what a missing shard means: a shard that was never written does not exist as a row, and the reader should treat it as zero and not as an error.
Sharding does not guarantee an even load. Random choice is even over many writes and uneven over a few, and a store may place two shard rows on the same node. So watch the write rate of each shard and not only of the counter. A shard that runs hot while the others are idle points to a skewed choice or to rows placed together, and the fix is to move or add rows, not to add threads.
A counter takes 450 writes per second, one shard handles 100 per second, and the headroom is 2. How many shards, and why?
- Nine: 450 times 2 divided by 100 is 9. The headroom keeps each shard at about half its limit, so random uneven placement does not overload one.
Why is growing the shard count safe while the counter is in use?
- The total is a sum, and new shards start at zero. The old shards keep their values, so the total does not change when they are added.
Why is shrinking harder than growing?
Part 5 · Approximate counts for unique viewers
Counting distinct things
A like counter adds 1 for each event. A unique viewers counter is a different problem: it must count each person once however many times they open the post. The exact way is to keep a set of every viewer id and report its size. That takes memory proportional to the number of viewers. For a post seen by 10 crore people it is gigabytes for one number, on one key, that every viewer touches.
An approximate answer is usually enough for a viewer count. The question is how to get one in a small, fixed amount of memory. The best-known method is HyperLogLog. It rests on a property of hashing: if you hash each id to a random-looking bit string, then among n different ids the longest run of leading zeros you see is about the base-2 logarithm of n. Seeing a hash that starts with twenty zeros is a hint that you have looked at around 10 lakh ids.
One maximum is too noisy, so the method splits the ids into m buckets, called registers, by the first bits of the hash. Each register remembers the longest run of zeros seen among the ids sent to it, and a formula combines all the registers into an estimate. Repeated ids give the same hash and change nothing, which is what makes the count distinct. The HyperLogLog paper by Flajolet and others (2007) gives the standard error as about 1.04 divided by the square root of m, so more registers mean a better answer.
A small implementation
The version below uses 2 to the power 14 = 16,384 registers, the count the Redis source code uses, so its expected error is 1.04 / 128, about 0.81 percent. It hashes with BLAKE2 to 64 bits, uses the first 14 bits to choose a register and records the position of the first 1 bit in the remaining 50 bits. The estimate is the usual harmonic-mean formula, with a correction for small counts when many registers are still empty.
import hashlib, math P = 14 # 2**14 = 16,384 registers M = 1 << P ALPHA = 0.7213 / (1 + 1.079 / M) class HLL: def __init__(self): self.reg = bytearray(M) def add(self, item): x = int.from_bytes( hashlib.blake2b(item.encode(), digest_size=8).digest(), "big") # first 14 bits pick a register idx = x >> (64 - P) rest = x & ((1 << (64 - P)) - 1) rank = (64 - P) - rest.bit_length() + 1 # leading zeros + 1 if rank > self.reg[idx]: self.reg[idx] = rank def count(self): est = ALPHA * M * M / sum(2.0**-r for r in self.reg) zeros = self.reg.count(0) # small-range correction if est <= 2.5 * M and zeros: est = M * math.log(M / zeros) return round(est)
hll.py: the HyperLogLog class
for n in (1_000, 100_000, 1_000_000): h, exact = HLL(), set() for i in range(n): uid = f"viewer-{i}" h.add(uid) exact.add(uid) est = h.count() print(f"{n:>9,} viewers: estimate {est:>9,}, " f"error {abs(est - n) / n:.2%}") print( f"{'':9} set: {len(exact):,} strings | HLL: {len(h.reg):,} B" )
hll.py: exact set against the estimate
# Two shards each keep a sketch; their viewers overlap. s1, s2, both = HLL(), HLL(), HLL() for i in range(60_000): s1.add(f"viewer-{i}") # viewers 0 to 59,999 for i in range(40_000, 100_000): s2.add(f"viewer-{i}") # viewers 40,000 to 99,999 for i in range(100_000): both.add(f"viewer-{i}") merged = HLL() merged.reg = bytearray(max(x, y) for x, y in zip(s1.reg, s2.reg)) print("shard sketches:", s1.count(), "+", s2.count()) print("merged:", merged.count(), "| same registers as one sketch:", merged.reg == both.reg)
hll.py: two shard sketches merged
1,000 viewers: estimate 1,000, error 0.00% set: 1,000 strings | HLL: 16,384 B 100,000 viewers: estimate 99,894, error 0.11% set: 100,000 strings | HLL: 16,384 B 1,000,000 viewers: estimate 1,009,280, error 0.93% set: 1,000,000 strings | HLL: 16,384 B shard sketches: 60432 + 59989 merged: 99894 | same registers as one sketch: True
Python 3.12.10 on this machine. Deterministic: the ids are fixed.
The result, and using it
For 1,000 viewers the estimate was exact. For 1 lakh it was 99,894, an error of 0.11 percent. For 10 lakh it was 10,09,280, an error of 0.93 percent, slightly above the 0.81 percent expected: the standard error is a typical size, and single runs fall on either side of it. The exact set held 10 lakh strings, while the estimator used the same 16,384 bytes at every size.
This implementation stores one byte per register. The comments in the Redis source describe 16,384 registers of 6 bits each, 12,288 bytes, which is the 12 KB its documentation states along with a standard error of 0.81 percent. Redis offers PFADD to add an item, PFCOUNT to estimate and PFMERGE to combine sketches. Merging is the feature that matters for sharded systems: two sketches merge by taking the larger value in each register, which is what the Redis source does. In the last run, two shards saw overlapping viewers, 0 to 59,999 and 40,000 to 99,999. Their estimates add up to about 1.2 lakh, which counts the overlap twice. The merged sketch estimated 99,894, and its registers were identical to a sketch fed all 1 lakh viewers directly, so each shard or each hour can keep its own sketch and the reader merges them.
Limits of a sketch
A sketch has limits. It counts distinct items but cannot list them or remove one. The answer is not exact, so it does not suit a figure that must reconcile to the unit, such as the number of paid customers. It also needs a good hash function, since a poor one skews the registers. For views, unique visitors and distinct search terms, it is the standard tool.
| Term | Meaning |
|---|---|
| Hot key | A key that receives far more traffic than the others |
| Sharded counter | A counter split into several rows whose sum is the total |
| Headroom | Spare capacity kept so uneven placement does not overload one shard |
| Cached total | A stored sum, refreshed on a schedule, read instead of the shards |
| HyperLogLog | A fixed-size sketch that estimates the number of distinct items |
Why does adding the same viewer id twice not change a HyperLogLog estimate?
- The same id gives the same hash, so it lands in the same register with the same run length. The register already holds that maximum.
In the run, how many bytes did the estimator use for 1,000 and for 10 lakh viewers?
- 16,384 bytes for both. The memory does not grow with the number of viewers.
Two shards report 60,432 and 59,989 unique viewers. Why is 1,20,421 the wrong total, and how do you get the right one?
- The shards saw some of the same viewers, so adding their counts counts the overlap twice.
- Merge the sketches by taking the larger value in each register and estimate from the result. The run gave 99,894, the same registers as one sketch of all viewers.