Chapter 12 / 24 · System Design

Counting at scale: probabilistic structures

Unique menu viewers and trending dishes, live and merged across servers: when a small, calculable error buys kilobytes instead of gigabytes, and when it does not.

A sketch is a small data structure that summarises a large stream well enough to answer one kind of question approximately, with an error we can calculate in advance. This chapter covers the three sketches most systems meet: HyperLogLog for counting distinct things, count-min for estimating how often something occurred, and the Bloom filter for checking whether something has been seen. Just as important, it covers when the exact answer is cheap enough that none of them is needed.

Dabba’s partner app is getting a dashboard. Restaurant owners want to know how many different customers looked at their menu today, this week and this month. The growth team wants a “trending near you” row showing the dishes being ordered most in each city in the last hour. Both questions are asked continuously, by many people, over data that arrives at thousands of events a second.

Start by pricing the exact answer

Before reaching for anything clever, we estimate what exact counting would cost, because often it is fine. The brief puts menu views at about 16 million a day, roughly sixteen for every order placed. Many are repeats: the same customer opening the same menu twice. Say 10 million distinct (restaurant, customer) pairs a day.

For a nightly report, exact is easy. The warehouse from the last chapter runs COUNT(DISTINCT customer_id) grouped by restaurant over yesterday’s views, and nobody needs anything more. Exact counting becomes expensive under three conditions, which are worth naming because they decide when a sketch earns its place: when the answer must be live rather than nightly, when it must be combined across arbitrary ranges (“the last 30 days” starting from any day), and when the events are counted on many machines that each see only part of the stream.

Dabba’s dashboard meets all three. Views are counted by the 30 API servers, the owner can pick any range, and the number should move while she watches it at dinner time. To keep exact answers we would store, for each restaurant and day, the set of customer ids that viewed it, and union 30 of those sets whenever someone opens the monthly view. For a popular restaurant with 40,000 viewers a month, that union reads and merges hundreds of thousands of ids for one tile on one screen.

Predict first

Two API servers each keep an exact count of distinct customers who viewed restaurant 88213 today. Server A reports 4,000 and server B reports 3,000. How many distinct customers viewed the menu today?

Show the worked answer

We cannot tell. Somewhere between 4,000 and 7,000. If every customer who hit server B also hit server A (load balancers spread one customer’s requests across servers all the time), the answer is 4,000. If the two groups never overlap, it is 7,000.

Distinct counts do not add. To combine them we need the sets themselves, or something that summarises a set in a way that can be merged. That property, mergeability, is the main reason HyperLogLog exists in production systems.

How HyperLogLog counts what it never stores

HyperLogLog estimates how many distinct items a stream contains. It relies on one fact about random numbers. Hash each customer id to a random-looking 64-bit number. Half of all hashes start with a 0 bit, a quarter start with two 0 bits, one in eight with three. If, after hashing everyone who viewed the menu, the longest run of leading zeros we have seen is 12, then we have probably seen something like 2 to the power 12, about 4,000, different values. Seeing the same customer again produces the same hash, so repeats change nothing. That is what makes it count distinct items rather than events.

One such observation is a noisy estimate; a single lucky hash can throw it off by a factor of two. So HyperLogLog splits the stream. It uses the first 14 bits of each hash to choose one of 16,384 registers, and in each register it keeps the longest run of leading zeros seen among the remaining bits. The final estimate combines all registers with a harmonic mean, which limits the damage from a few unlucky ones, plus corrections for very small and very large counts.

The numbers that make it useful: 16,384 registers of 6 bits each is 12 KB, and the standard error is about 1.04 divided by the square root of the register count, which comes to 0.81%. That is the same whether the true count is a thousand or a billion. Redis implements it with exactly these parameters in PFADD and PFCOUNT, and stores small counts in a sparse encoding of a few hundred bytes, moving to the 12 KB form only as they grow.

Merging is where it pays off. Two HyperLogLogs built with the same parameters merge by taking the larger value in each register, and the result is exactly the sketch we would have built from the combined stream. So each API server keeps its own sketch per restaurant per day, they merge freely, and “the last 30 days” is a merge of 30 small objects. For the restaurant with 40,000 monthly viewers the answer is 40,000 plus or minus about 320, computed in microseconds.

PFADD  views:r88213:2026-10-15  cust:4471
PFADD  views:r88213:2026-10-16  cust:4471 cust:9902
PFCOUNT views:r88213:2026-10-15 views:r88213:2026-10-16
-- merges the two days on the fly; customer 4471 counted once

Is ±0.8% acceptable? For an owner deciding whether her new menu photos brought more people in, yes. She is comparing 40,000 with 31,000, not 40,000 with 40,100. For anything that is paid on, it is not, and the last section returns to that line.

Which dishes are trending: estimating frequency

The trending row asks a different question: for each dish, how many times was it ordered in this city in the last hour, and which are the top 20? The exact answer is a hash map from dish to count. At Dabba’s order rate that map is small: about 150,000 orders in the dinner hour, perhaps 450,000 item events, across at most a few hundred thousand distinct dishes nationally, a few tens of megabytes. One process could hold it exactly.

So for orders, Dabba counts exactly. The case changes when we move from orders to impressions: each time a dish card appears on someone’s screen. At around 40 cards per session and 4 million sessions a day, that is 160 million impressions a day. The dinner hour carries 15% of the day, 24 million impressions, about 6,700 a second, spread over 30 servers, with a long tail of dishes that appear once. Exact per-server maps that must be shipped and merged every minute become a real cost. A count-min sketch replaces each map with a fixed-size grid.

“chicken biryani, Bengaluru, this hour” → hash₁ … hash₄row 1341071298052194row 2811003602231492row 3217509861304116row 4995382601344179801003986995min = 980other dishes that share a counter can only add to it, never subtractso every row overestimates · the smallest row overestimates least
A count-min sketch: one dish hashes to one counter in each row. Other dishes sharing a counter only ever add to it, so the smallest of the four counters is the closest estimate.

The grid has d rows of w counters, and each row has its own hash function. To record an impression of “chicken biryani”, we hash it once per row and add one to the chosen counter in each row. To estimate its count, we read those same d counters and take the smallest. Other dishes that happen to hash to the same counter add to it, so every counter can only overestimate. The row where the dish shared its counter with the fewest others gives the closest answer.

The error has a precise and slightly surprising shape. With w counters per row, the overestimate is at most e/w times the total number of events counted, with probability 1 − e−d. Take w = 2,000 and d = 5: 10,000 counters, 40 KB at 4 bytes each. If Bengaluru shows 7 million impressions in the dinner hour (about 30% of 24 million), the overestimate for any dish is at most about 0.14% of 7 million, roughly 9,500, with 99.3% probability.

Notice that the error is relative to the whole stream, not to the dish. For a popular biryani with 150,000 impressions, an overestimate of up to 9,500 hardly changes its rank. For a dish with 1,000 impressions, the estimate is noise. That makes count-min good at exactly one thing: finding the heavy hitters, the items far above the noise floor. Alongside the grid we keep a small heap of the current top 100 candidates; each new event updates the grid, and if the dish’s estimate beats the smallest entry in the heap, it takes that place. Like HyperLogLog, count-min merges simply: add two grids cell by cell.

The same structure has a less visible use. Counting requests per cache key with a count-min sketch finds the hot keys, the handful of menus receiving a large share of reads, so they can be replicated or cached closer to the user before they overload one cache node.

Bloom filters: a cheap “definitely not”

A Bloom filter answers “have we seen this item before?” with one asymmetry. A “no” is certain. A “yes” means probably. It is a bit array of m bits and k hash functions. Adding an item sets the k bits its hashes point to. Checking an item looks at those k bits: if any is 0, the item was never added; if all are 1, it was either added or its bits were all set by other items.

Its main use is skipping expensive work whose answer is usually “not here”. Dabba stores each rider’s location history, used for disputes and payouts, in an LSM-based store such as Cassandra or RocksDB. Data there is spread over many immutable files, and a read for rider 4411’s history at 20:15 might otherwise open dozens of them. Each file carries a Bloom filter of the keys it contains, so the read checks the filters in memory and opens only the one or two files that might hold the rider. Most teams use Bloom filters this way without ever writing one; it helps to know they are there and why.

When we do size one ourselves, the formula is fixed. For n items and a target false-positive rate p, we need m = −n ln p ÷ (ln 2)2 bits and about (m/n) ln 2 hash functions. For p = 1% that is about 9.6 bits per item and 7 hashes. Eight million items, roughly a day of Dabba’s order events at eight events per order, need about 10 MB.

Predict first

The notifications consumer from the streams chapter wants to skip duplicate events cheaply. Someone proposes: keep a Bloom filter of processed event ids, and if the filter says “seen”, skip the event. The filter is sized for 1% false positives. What goes wrong?

Show the worked answer

A false positive means the filter says “seen” for an event that was never processed. With this design, 1% of genuinely new events are skipped. At about 340 events a second in the dinner hour, that is three or four notifications a second that silently never go out, including “your rider has arrived”.

The filter is pointed in the wrong direction. Used correctly, it answers only the question it is certain about: if the filter says “definitely not seen”, process the event without checking the database; if it says “maybe seen”, check the processed_events table, which is authoritative. A false positive then costs one extra database read, not a lost message.

Before asking how big a filter must be, it is worth asking what a false positive costs in each use. In the LSM store it costs one wasted file read. In the dedupe check it costs one database read, if the filter is used as a pre-check, and a lost notification if it is used as the authority. And at Dabba’s few hundred order events a second, the database check is cheap enough that the filter may not be worth having at all. It would earn its place on a much faster stream, like the 10,000 rider locations a second.

A filter that quietly filled up

Here is how a Bloom filter usually fails. A team sizes a filter for 2 million event ids a day at 1% false positives: about 19 million bits, 7 hashes. It works well at launch. A year later, after Dabba expands to more cities and adds new event types, the same filter receives 8 million ids a day. Nobody changed the code, so nobody looked at it.

The false-positive rate of a Bloom filter with n items is about (1 − e−kn/m)k. With k = 7, n = 8 million and m = 19.2 million, kn/m is about 2.9, e−2.9 is about 0.054, and 0.946 to the power 7 is about 0.68. The filter now says “maybe seen” for 68% of new ids. Used as a pre-check, it sends 68% of events to the database it was supposed to protect, and the database load that the filter used to absorb arrives all at once on a busy evening. Used as an authority, it would be dropping two-thirds of notifications.

The fix is to treat the expected item count as a parameter that must be revisited. Dabba rotates the filter daily, sizes it for twice the current daily volume, and exports its fill ratio (the fraction of bits set) as a metric with an alert at 50%. During the first minutes after midnight the consumer checks both today’s and yesterday’s filters. The cost is memory sized for growth that has not happened yet and two lookups for a short period each day. In exchange, the filter fails loudly on a dashboard instead of quietly in the database.

SketchQuestion it answersSizeShape of the errorMerges by
HyperLogLogHow many distinct items?12 KB, whatever the count±0.81% standard error, either directionTaking the max per register
Count-minHow many times did this item occur?w × d counters, e.g. 40 KBOverestimates only, by up to a fraction of the total streamAdding grids cell by cell
Bloom filterHave we seen this item?~9.6 bits per item at 1%False “yes”, never a false “no”; worsens as it fillsOR-ing bit arrays of the same size
Exact set or mapAny of the aboveGrows with the dataNoneUnion, which needs all the data

When the approximate answer is the wrong one

A sketch belongs where the answer informs a decision and a small error does not change the decision: dashboards, trending lists, capacity planning, choosing what to cache. It does not belong where the number is a promise. Restaurant payouts are computed from exact order totals. “One first-order coupon per customer” is checked against an exact table. A customer’s order count shown on a loyalty badge is an exact count, because a customer who sees “9 orders” after her tenth will write to support.

We also revisit sketches when the data is small. A restaurant with 50 viewers a day is better served by an exact set; Redis’s sparse HyperLogLog encoding is partly there to avoid paying 12 KB for small counts, but an exact answer is still easier to explain. And if the question moves from “roughly how many” to “exactly which”, for example a list of customers who viewed and did not order, no sketch can help, because sketches keep no members.

The trending row has one more requirement: “near you”. Ranking dishes per city is easy because city is a column. Finding restaurants within delivery range of a customer, and riders within a few hundred metres of a restaurant, is not something any index we have met so far can do. The next chapter, on geospatial indexing, builds the structures for it.