Key takeaways
- ✓Typeahead returns the 10 most popular names that start with what's typed, on every keystroke. One letter matches 50,093 of the million names, and Postgres must rank all of them: its slowest 1 in 100 one-letter answers took 16.1 ms, against 1.0 ms for an eight-letter prefix.
- ✓A sorted index with a precomputed top 10 for each of the 39 one- and two-letter prefixes answered one letter in 0.89 ms at p99. Its one slow length was three letters, at 5.35 ms, because that length has no precomputed table and a three-letter prefix can match 2,537 names at the median and 60,225 at most.
- ✓At 1,500 keystrokes a second, Postgres alone had a p99 of 82.2 ms. A 60-second cache of answers per prefix brought the p99 to 3.4 ms, answering 79% of keystrokes from memory, because people keep typing the same short prefixes.
- ✓A geohash names a rectangular cell, and each extra character makes the cell 32 times smaller in area. For drivers within 500 m of the dense centre, precision 7 (cells of about 150 m) checked 5,438.5 drivers and took 3.3 ms, against 64,158 drivers and 19.8 ms at precision 5.
- ✓In the suburbs, for drivers within 2 km, precision 7 visited 1,188 mostly empty cells and took 8.6 ms, about eight times precision 6's 1.1 ms. No cell size was best everywhere, so choose by how crowded the map is or use an index that adapts.
- ✓Every geohash answer matched a brute-force check of all 200,000 drivers, while PostGIS's GiST index (a tree of bounding boxes) differed on up to 14 of 150 queries, each by a driver within 2.6 mm of the circle's edge, because its Earth is 8.8 m wider. Agree on the model before you call a difference a bug.
Every search box with suggestions does the same job on every keystroke: find the ten most popular names that start with what's been typed so far. This chapter takes the job apart in two places. The first is typeahead over a million product names, where the short prefixes are the hard case and a cache of answers fixes most of the cost. The second is the same question on a map, "which drivers are within 500 m or 2 km?", answered with geohash cells, where the best cell size changes from one part of a city to another.
The examples come from Lab 11 (Search, Geo and Object Storage) of the system design labs, scripts 02_typeahead.py (typeahead, one query at a time and under load) and 03_geo.py (drivers within a radius, with geohash cells and PostGIS). The lab's modules are prefix_index.py (the sorted index with precomputed answers for short prefixes), service/app.py (the typeahead service that Postgres and the cache sit behind) and geohash.py (the geohash encoding, the cell covering and the grid index). The episode this chapter follows is part 21 of the system design track, with the presenter Lucía, a platform engineer. The setup is the earlier chapters' laptop, an Apple M4 Max with Docker Desktop, Postgres 17.7 and PostGIS 3.6.1 in Docker. Other jobs were running during the tests, with load averages between about 4 and 20, so read the shapes and the orders of magnitude, not the last digit. The names, the keystrokes and the city are generated from fixed seeds, so nothing needs a cloud account or an API key; the timings are real measurements.
The phone book
Typeahead is a phone-book problem. If the names are sorted, every name that starts with k sits in one run of pages, and every name that starts with kad sits in a smaller run inside it. Each extra letter typed narrows the run. The work to find the top 10 is the work to look at the whole run, because popularity is not the sort order: the 10 most popular names can be anywhere in it.
Two facts follow. A short prefix has a huge run, so it is slow. And a short prefix repeats constantly, so it is worth caching. The rest of the chapter measures both.
The test: a million names and a skewed crowd
The names are generated from fixed word lists, such as "kadoon ultra tent y909", and each name gets a popularity from a skewed (Zipf) distribution, so a few are very popular and most are rarely bought. The lab's datasets.py builds the million names from a fixed seed. That is the same list for every run, and the lab's scripts type prefixes of it.
The typeahead service answers three ways:
- Postgres:
name LIKE 'q%' ORDER BY popularity DESC LIMIT 10, with an index on the names. - Postgres + prefix cache: the same query, behind a cache of answers per prefix that each live for 60 seconds.
- In-memory index: the names in sorted order in memory, with the top 10 precomputed for every one- and two-letter prefix at startup.
All three returned the same top 10 for all 300 test prefixes, so the comparison is about speed, not answers.
Short prefixes are the slow ones
For one query at a time, the script ran 60 prefixes of each length through each way. Here is the lab's result, in milliseconds. p50 is the median answer, and p99 is the slowest 1 in 100 answers.
| Prefix length | Postgres p50 | Postgres p99 | In-memory index p50 | In-memory index p99 |
|---|---|---|---|---|
| 1 letter | 5.70 | 16.1 | 0.59 | 0.89 |
| 2 letters | 4.84 | 7.15 | 0.56 | 0.75 |
| 3 letters | 1.20 | 6.09 | 0.92 | 5.35 |
| 5 letters | 1.01 | 5.70 | 0.78 | 1.20 |
| 8 letters | 0.69 | 1.00 | 0.53 | 0.77 |
Postgres got faster as the prefix got longer, which is the phone-book point: longer prefixes mean shorter runs. The index was flat, except at three letters. It precomputes answers only for one and two letters, because there are only 39 of them (19 one-letter and 20 two-letter prefixes in these names). A three-letter prefix is ranked on the spot.
The widget below uses the same names. Pick a prefix to see how many names it has to rank, whether the index answers it from a precomputed tab or ranks it on the spot, and the lab's measured p99 for its length.
Pick what has been typed so far
Bar on a log scale, from 1 name to all 1,000,000.
Answered from a tab: the top 10 for every one- and two-letter prefix was worked out once at startup, so this costs one lookup.
The lab's p99 by prefix length, one query at a time (the slowest 1 in 100 of 60 prefixes per length)
This prefix length is in the table: Postgres p50 5.70 ms, index p50 0.59 ms. The index's 5.35 ms at three letters is the one length it doesn't precompute (244 three-letter prefixes, median 2,537 names, biggest 60,225).
Two notes from the lab's run. With 60 prefixes per length, the "slowest 1 in 100" is close to the slowest single answer, so treat the p99 as an order of magnitude. And the three-letter number is the index's weak spot: 244 three-letter prefixes exist, with a median of 2,537 names each.
Many users typing
One query at a time says little about a busy search box. The next test sends keystrokes at a fixed rate, 500 and then 1,500 a second, from users typing popular products. The top 100 prefixes were 37% of all keystrokes, and the runs lasted 20 seconds each.
Keystrokes per second, from users typing popular products
Bars: p99, the slowest 1 in 100 keystrokes, on one scale (0 to 90 ms). 29,803 keystrokes per run, none failed.
At 1,500 a second, Postgres's short prefixes queued behind each other. The cache answered 79% of keystrokes, because people keep typing the same prefixes, and those are the expensive ones.
At 500 keystrokes a second, all three ways stayed under 8 ms at p99. At 1,500, Postgres alone had a p99 of 82.2 ms. The lab's guess is that the short prefixes queued behind each other: one slow ranking holds up the next request. That queue was not measured. The in-memory index was not flat at that rate either: its p99 rose to 7.6 ms, from 3.3 ms at 500. The lab's explanation is that the service runs as one process, so a slow three-letter ranking delays the keystrokes behind it. That is also a guess, not a measurement.
The cache is the cheap fix, and it works because of the same skew. The cache answered 65% of keystrokes at 500 a second and 79% at 1,500. More keystrokes per second means more repeats of the same prefixes within each 60-second cache lifetime, and those repeats are the expensive short prefixes. Each run began with an empty cache, so the first time a prefix appeared it was a miss.
The cache has a cost that the number hides. It keeps an answer for 60 seconds, so a new product could take up to a minute to appear in the suggestions. The index has the opposite trade: it is always up to date with the names it was built from, but a rebuild is needed when the names change.
The index in code
The sorted index does three things:
- It finds the run by binary search. It jumps to the middle of the sorted names, then the middle of the half that is left, until it reaches the first name of the run.
- It holds 39 tabs. At startup it works out the top 10 for every one- and two-letter prefix. The code calls them a cache, but they are built once and never expire, unlike the per-prefix cache in front of Postgres.
- It ranks the rest on the spot. A prefix with a tab is one lookup. A longer prefix ranks its run, which for three letters is a median of 2,537 names and at most 60,225.
Cells on a map
Now the map. A rider asks which drivers are within a radius. Scanning all 200,000 drivers is the brute-force answer, and it is always right, but slow for every request.
A geohash cuts the map into rectangular cells, each named by a short base-32 code. The number of characters is the precision. Each extra character adds five bits, which makes the cell 32 times smaller in area, and points that share a prefix share a cell. The lab's table, at the equator, is:
| Precision | Cell (at the equator) | At the city's latitude |
|---|---|---|
| 5 | about 4.9 × 4.9 km | 4.9 km north–south × 3.0 km east–west |
| 6 | about 1.2 × 0.61 km | 610 m north–south × 740 m east–west |
| 7 | about 153 × 153 m | 150 m north–south × 90 m east–west |
The city is generated around central Berlin (52.52° N), where east–west sides are about 0.61 of their equator length. The lab's table is the equatorial one; the city column is what the video shows on screen.
To find drivers within a radius, the code does three things. Each driver goes into the cell of its geohash, at one chosen precision. A query lists the cells that cover the circle. It then collects the drivers in those cells and keeps only those whose exact distance is within the radius. The first two steps are cheap, and the last one costs a distance calculation per driver, so the cell size trades cells visited against drivers checked.
Picking the cell size
The same three geohash precisions and PostGIS were run on 150 riders in the dense centre and 150 in the suburbs, at 500 m and 2 km. The city had 200,000 drivers, 60% of them in the dense centre, and every answer was checked against brute force.
Median over 150 riders: 3,520 drivers found. Each row is one way to answer the same question; the fastest geohash is marked, and every geohash answer matched a brute-force check of all 200,000 drivers.
Cells: how many grid cells the query looked into. Checked: drivers whose exact distance was computed. PostGIS has no cell count; its index is an R-tree (GiST). PostGIS disagreed with brute force on 2 of 150 queries; each difference was a driver within 2.6 mm of the edge of the circle, because PostGIS's Earth is 8.8 m wider.
Cell sizes (side lengths)
Precision 7 checked 5,439 drivers instead of 64,158 at precision 5.
Read the rows for the dense centre at 500 m. Precision 5 covers the circle with two cells, but those cells hold 64,158 drivers to check, and it takes 19.8 ms. Precision 7 covers it with 88 small cells, checks 5,438.5 drivers, and takes 3.3 ms. The small cells win there.
Now the suburbs at 2 km. The circle holds about a thousand drivers, spread thin. Precision 7 has to visit 1,188 cells, nearly all empty, and takes 8.6 ms. Precision 6 visits 48 cells and takes 1.1 ms, about eight times faster. The same small cells that won in the centre lose badly here.
So no single cell size was best everywhere. The right size depends on how crowded that part of the map is, and a city has both densities. Two ways to handle it: choose the precision by density, or use an index that adapts. PostGIS's GiST index, which is a tree of bounding boxes that follow the data, did that by itself. It was never the fastest and never the slowest in the four rows that were tested.
The 2 km centre query also shows a different limit. It returns 45,894 drivers, so any method has to produce about 46,000 results, and the p50 is 31 to 37 ms for geohash and 34.6 ms for PostGIS, whose p99 was 145.9 ms. No index returns that many rows quickly. A ride-hailing app that needs the 10 nearest drivers asks a different question: search the rider's cell and its neighbours, widen the search until you have 10, then sort by distance.
Checking the index against brute force
Every geohash answer matched the brute-force check, at every precision and every radius. PostGIS did not. It differed on 0 to 14 of the 150 queries in each row, and in every case the driver was within 2.6 mm of the circle's edge.
The reason is a difference in the model, not a bug. PostGIS treats the Earth as a sphere with a radius of 6,371,008.8 m, and the lab's own code uses 6,371,000 m. On a 2 km circle, that 8.8 m difference moves the edge by about 2.8 mm, which is enough to put a driver on the other side. The video's worked example repeats the check with PostGIS's radius and reproduces the same differences; that re-run is not in the lab's results files.
The lesson is to agree on the model before comparing answers. A check against brute force is what found the 3 mm, and that check is worth keeping in the test suite.
Caveats
- One laptop, one run per row. The lab's results are single runs of 20 seconds (typeahead) and of 150 queries (geo). The p99 numbers are from 60 or 150 samples, so they are rough. The cache's 65% and 79% depend on the run starting empty.
- The 60-second expiry never fired. Each run started with an empty cache and lasted 20 seconds, so the cache's freshness cost was described, not measured.
- The queue was not measured. The lab's note that short prefixes queued behind each other at 1,500 keystrokes a second is an explanation, not a measurement. The index's rise to 7.6 ms p99 has the same unmeasured cause.
- Generated data. The names, the popularity and the city are generated, so the skew is a model. A real catalogue may repeat different prefixes.
- The cell sizes are at the equator in the lab's table. The city column comes from the video's on-screen dimensions at the city's latitude; both are arithmetic on the same cell rule.
The checklist
- Measure p99 for short prefixes separately. The median hides the one-letter case, which was 16.1 ms at p99 in Postgres against 1.0 ms at eight letters.
- Precompute what's hot and short. Tabs for one and two letters cost 39 entries here and kept those prefixes under 0.9 ms at p99.
- Cache answers per prefix, and state the staleness. A cache answered 79% of keystrokes at 1,500 a second, and it can serve a new product up to 60 seconds late.
- Choose the geohash precision by density, or use an index that adapts. Test both the dense centre and the sparse suburbs, because the best cell size differs between them.
- Check the index against brute force, and agree on the Earth model before you call a difference a bug.
Check your understanding
Try each question before opening its answer.
Why is one letter slow for typeahead, when eight letters take about a millisecond?
A one-letter prefix matches 50,093 of the million names, and the query has to rank all of them to find the 10 most popular. An eight-letter prefix matches only a handful, so the work is small. Postgres took 16.1 ms at p99 for one letter and 1.0 ms for eight.
The in-memory index answers one and two letters from precomputed tabs but ranks three letters on the spot. Why was three letters its slow case at 5.35 ms, and what would fix it?
There are 244 three-letter prefixes, with a median of 2,537 names and a largest of 60,225, and none has a precomputed table, so each query ranks its run. Precomputing three-letter tabs, or caching them on demand, would remove the slow case. The lab did not test either.
At 500 keystrokes a second the cache answered 65% of keystrokes, and at 1,500 it answered 79%. Why did the share rise with load?
More keystrokes per second means more repeats of the same prefixes within each 60-second cache lifetime, and the repeats are mostly the short, expensive prefixes. Each run started with an empty cache, so each prefix's first appearance was a miss; more keystrokes made those misses a smaller share.
For drivers within 500 m of the dense centre, precision 7 was fastest, and within 2 km of the suburbs precision 6 was. What decides which cell size is best?
How many drivers and empty cells the query touches. In the dense centre, precision 5 checks 64,158 drivers, while precision 7 visits 88 cells and checks 5,438.5. In the suburbs, precision 7 visits 1,188 mostly empty cells for a 2 km circle. The best size follows the density of the part of the map being searched.
PostGIS disagreed with the brute-force check on up to 14 of 150 queries. Is PostGIS wrong?
No. Each difference was a driver within 2.6 mm of the circle's edge. PostGIS uses an Earth radius of 6,371,008.8 m and the lab's code uses 6,371,000 m, and on a 2 km circle that 8.8 m difference moves the edge by about 2.8 mm. The two systems use different models, so compare answers only after agreeing on one.
Next up: Chapter 22, multipart uploads. Typeahead and nearby search are the last two kinds of index in Lab 11's search, geo and storage work. The next chapter covers the lab's last script: a 2 GB upload over a connection that keeps dropping, where a failed part is resent alone and a presigned URL lets the client upload without holding a credential.