Bloom Filters, HyperLogLog, Geohash and Quadtrees
Overview
Two families of tricks show up again and again in system design interviews. Probabilistic data structures trade a small, controlled error for enormous savings in memory: "is this URL already in my set of a billion?" in 1 GB instead of 100 GB. Spatial indexes make "find places within 2 km of me" fast, which a plain database index cannot do well on latitude and longitude.
This lesson explains the Bloom filter and HyperLogLog (the idea only), then geohash and quadtree, each step by step with worked numbers.
Detailed Notes
What is it?
Bloom filter
A Bloom filter answers one question, "have I seen this item before?", using very little memory. It can answer:
- "Definitely not in the set": always correct.
- "Possibly in the set": usually correct but sometimes wrong. This is a false positive.
It never gives a false negative. It cannot delete items (in the basic version) and cannot list what is inside; it only stores bits.
HyperLogLog
HyperLogLog (HLL) estimates the number of distinct items in a very large stream (unique visitors, unique search queries) using a fixed, tiny amount of memory. The idea: hash each item to a random-looking bit string and remember only the longest run of leading zeros seen. Seeing a hash that begins with 20 zeros is a rare event (probability about 1 in a million), which suggests you have probably seen about a million different items. HLL averages this over many small buckets (called registers) to reduce noise. Redis offers it as the PFADD and PFCOUNT commands. A standard HLL uses about 12 KB and has an error around 0.8%, whether it counted a thousand items or a billion. Counting a billion exact distinct 8-byte IDs would need about 8 GB (plus overhead for a hash set).
A related structure, the Count-Min Sketch, estimates how many times each item occurred, which is useful for finding the most frequent items ("heavy hitters", such as trending hashtags) in a stream.
Geospatial indexes
A geospatial index supports "what is near this point?". A database index on a single column sorts one dimension, but a location has two (latitude and longitude). Searching "lat between A and B" and "lng between C and D" with two separate indexes scans huge ranges. Two approaches turn 2D into something an ordinary index can handle:
- Geohash: encode a location as a short string; nearby places usually share a prefix.
- Quadtree: a tree that recursively splits crowded map areas into four quadrants.
Why do we need it?
- Bloom filter: avoid expensive lookups. A web crawler must check whether it has crawled a URL among 10 billion; a cache layer wants to skip database queries for keys that do not exist (the cache penetration problem from the caching lesson); a database checks whether a key might be in an on-disk file before reading it (LSM trees, from the indexing lesson, do exactly this).
- HyperLogLog: unique counts at scale, where exactness is not needed. "About 41.2 million unique viewers" is as useful as "41,203,874".
- Geo: ride sharing (nearest drivers), restaurant search, "friends nearby". Millions of moving points need an index that finds neighbours in milliseconds.
How does it work?
Bloom filter step by step
A Bloom filter is an array of m bits, all 0 at the start, plus k different hash functions that each map an item to a position in the array.
- Add: compute the k positions for the item and set those bits to 1.
- Check: compute the k positions. If any bit is 0, the item was never added (definitely not). If all are 1, it was probably added.
Tiny example: m = 10 bits, k = 3 hashes.
Add "cat": hashes -> positions 1, 4, 8 bits: 0 1 0 0 1 0 0 0 1 0
Add "dog": hashes -> positions 2, 4, 9 bits: 0 1 1 0 1 0 0 0 1 1
Check "cow": positions 1, 5, 8 -> bit 5 is 0 -> DEFINITELY NOT present
Check "fox": positions 2, 4, 8 -> all are 1 -> "possibly present" (but fox was never added)
"fox" is a false positive: other items happened to set exactly its bits. As more items are added, more bits become 1 and false positives become more likely.
Adding items
set k bits per item
- 1
Start: 0000000000
all 10 bits are 0
- 2
Add cat: hashes 1, 4, 8
0100100010
- 3
Add dog: hashes 2, 4, 9
0110100011 (bit 4 shared)
- Insert is k hash computations
- No item data stored
- Basic filter cannot delete
Bits are only ever turned on
Checking items
read the same k bits
- 1
Check cow: bits 1, 5, 8
bit 5 is 0: definitely not
- 2
Check cat: bits 1, 4, 8
all 1: possibly present
- 3
Check fox: bits 2, 4, 8
all 1 but never added: false positive
- Never a false negative
- Constant time per check
- False positives grow as bits fill
Confirm 'possibly' answers in the real store
Hashing sets or reads three bits. One zero bit proves absence; all ones only suggests presence.
Sizing. The false-positive rate p depends on bits per item (m/n) and the number of hashes. The well-known rules of thumb:
bits per item = about 1.44 x log2(1/p)
hash functions = bits per item x 0.69
p = 1% -> about 9.6 bits per item, 7 hashes
p = 0.1% -> about 14.4 bits per item, 10 hashes
Example: 1 billion URLs at p = 1%:
1,000,000,000 x 9.6 bits = 9.6 billion bits = 1.2 GB
Storing the URLs themselves: 1 billion x 100 bytes = 100 GB
So 1.2 GB (small enough for one machine's memory) filters out 99% of the useless lookups. Each extra 4.8 bits per item cuts false positives tenfold.
Request load
Store the URLs
100 GB
1 B x 100 bytes, exact answers
Bloom filter, 1%
1.2 GB
7 hashes, 1 in 100 false positives
Bloom filter, 0.1%
1.8 GB
14.4 bits per item, 10 hashes
Rule of thumb: bits per item = 1.44 x log2(1/p), hash functions = bits per item x 0.69.
Use a Bloom filter when a false positive only costs one extra lookup (the real store then answers correctly), never when a false positive is a correctness problem on its own.
Geohash step by step
A geohash repeatedly halves the map, alternating between longitude (east-west) and latitude (north-south), and records each half as a bit: 0 for the lower half, 1 for the upper half. Every five bits are written as one base-32 character.
- Start with the whole world. Is the point in the western or eastern half? Record a bit.
- Split the chosen half north/south; record a bit.
- Repeat. Each extra character makes the box smaller.
Longer strings mean a smaller box:
Length 4: about 39 km x 20 km
Length 5: about 5 km x 5 km
Length 6: about 1.2 km x 0.6 km
Length 7: about 150 m x 150 m
Two points in the same box share the same string, and nearby boxes usually share a prefix, so a plain index on the geohash column supports "find all places whose geohash starts with ttn5" as a fast range scan. To search within 2 km, choose the length whose box is about that size (length 5), compute the user's cell, and query it plus its 8 neighbours.
Why the neighbours? The boundary problem: two points 10 metres apart can lie on opposite sides of a cell border and have totally different prefixes. Querying the 3x3 block around the user fixes it; then compute exact distances and filter.
Quadtree step by step
A quadtree starts with one box covering the area, and splits a box into four equal quadrants whenever it contains more than a limit of points (say 100). Dense areas (a city centre) split many times; empty areas (an ocean) stay as one big leaf.
- Insert points; the root box fills up.
- When it exceeds 100, split it into four children and distribute the points.
- Repeat for any child that exceeds 100.
- To search near a point: walk down from the root to the leaf containing it, then collect points from that leaf and its neighbouring leaves until you have enough results or have covered the radius.
Sizing: 200 million places with at most 100 per leaf needs at least 2 million leaves. With internal nodes (about one third more), roughly 2.7 million nodes at about 100 bytes each is under 300 MB, and the points themselves (200 million x 24 bytes) are about 5 GB. The whole index fits in the memory of one server; replicate it for availability and rebuild it from the database on start-up.
Geohash
string prefix per grid cell
- 1
Encode lat/lng as a string
halve the map, alternate axes
- 2
Pick length for the radius
length 5 is about 5 km
- 3
Query own cell + 8 neighbours
prefix range scan
- 4
Filter by exact distance
- Works with any indexed column
- Easy to shard by prefix
- Cheap updates for moving points
- Fixed cell size ignores density
- Boundary problem needs the 9-cell query
Moving objects, key-value stores
Quadtree
tree that splits crowded areas
- 1
Start with one box
- 2
Split into 4 if over 100 points
repeat on crowded children
- 3
Descend to the leaf for the point
- 4
Collect from leaf + neighbours
until enough results
- Dense cities get fine cells, oceans stay coarse
- Natural for k-nearest
- In-memory, custom code
- Moving points require tree updates
Static, uneven data like places
Both turn two-dimensional location into something fast to search.
Interview tip. For "find nearby" questions do not say "query latitude and longitude with SQL BETWEEN". Name a spatial index (geohash or quadtree; real systems also use S2 or H3, which are cell-based grids on a sphere) and mention the boundary problem. For "have we seen this?" at billion scale, say Bloom filter and give the memory estimate and false-positive trade-off.
Real-world example
A web crawler keeps a Bloom filter of URLs it has already fetched, so most "have I seen this?" checks stay in memory. A "possibly seen" answer is verified against the real URL store; a "definitely not seen" answer needs no lookup. An analytics dashboard shows daily unique visitors using HyperLogLog, 12 KB per page per day instead of millions of user IDs.
System design example
A ride-hailing app must find the 10 nearest available drivers to a rider, with 500,000 drivers online sending a location every 4 seconds.
Location updates: 500,000 / 4 s = 125,000 updates per second
Writing 125,000 updates per second to a disk database is heavy, so keep live driver positions in memory: a hash map from geohash cell (length 6, about 1 km) to the set of driver IDs in it, stored in a sharded in-memory store (shard by the geohash prefix, so a neighbourhood lives on one shard). A driver moving into a new cell is removed from the old set and added to the new. To match a rider: compute the rider's cell and its 8 neighbours, fetch those driver sets, compute exact distances, return the 10 nearest. If fewer than 10 are found, widen to length 5 cells. Persist trips and a periodic location history asynchronously.
Interview discussion. "A plain index can't do two-dimensional proximity, so I'd bucket locations by geohash and query the user's cell and its 8 neighbours, then filter by exact distance. For static, uneven data like places a quadtree adapts to density. For dedup at billion scale I'd put a Bloom filter in front: 1.2 GB for 1% false positives, and false positives only cost an extra lookup."
Trade-off thinking. Bloom filters and HyperLogLog trade exactness for a 100x memory saving, so use them only where approximate is acceptable. Geohash is simple, works with any key-value store and index, and suits frequently moving points; its fixed grid ignores density and needs the 9-cell query. A quadtree adapts to density and gives better nearest-neighbour results, but it is an in-memory structure that must be built and updated by your own code.
Key interview takeaway
Bloom filter: definite no, probable yes, about 10 bits per item for 1% errors, no deletes. HyperLogLog: approximate distinct counts in 12 KB. Geohash: prefix-based grid cells, query the cell and its 8 neighbours. Quadtree: recursive splitting by density. Always say what the error costs you.
Real World Example
A web crawler keeps a Bloom filter of fetched URLs so most already-seen checks stay in memory, and a dashboard counts daily unique visitors with HyperLogLog at 12 KB per page per day. A ride-hailing app finds nearby drivers by looking up the rider's geohash cell and its 8 neighbours.
Common Interview Questions
Chapter quiz
Speed, Async and Coordination · 6 questions
1.A service has a 1 ms cache and a 20 ms database. Going from a 90% to a 99% cache hit rate changes database load by roughly:
2.A very popular cache key expires and thousands of requests hit the database at once. What is this called and what prevents it?
3.Which design gives effectively exactly-once processing with a message broker?
4.A token bucket has capacity 10 and refills 5 tokens per second. It is empty at t = 0. How many requests can be accepted at t = 1 second?
5.10,000 clients fail at the same moment and use exponential backoff without jitter. What happens?
6.A client holds a lease, pauses for 40 seconds, and wakes up after its lease expired and another client took over. What protects the data?
0 of 6 answered
Finished this lesson?
0 of 44 lessons done · 0% of the course

