ealeng

Episode 21 of 55 · Search and files

Typeahead and geohash: why short prefixes are slow, and why no cell size is best everywhere

On every keystroke, the search box asks for the ten most popular names that start with what's typed. For one letter, Postgres has to rank 50,093 of a million names: its slowest 1 in 100 answers took 16.1 ms, and at 1,500 keystrokes a second the slowest 1 in 100 took 82.2 ms. A cache of answers per prefix brought that to 3.4 ms. The same question on a map, 'which drivers are within 500 m or 2 km?', is answered with geohash cells, and the smallest cells win in the dense centre and lose almost eightfold in the suburbs. How a sorted index answers typeahead, why a cache works on skewed typing, how geohash cells turn a radius into a lookup, and how to check an index against a brute-force answer.

Lab 11 · Search, Geo and Object Storage12 min read
Video transcript9:36

0:00Cold open

0:01

Every time a user types a letter into my search box, the database finds the ten most popular products that start with it.

0:09

At fifteen hundred keystrokes a second, the slowest answer in every hundred took eighty-two milliseconds.

0:17

With a cache of answers in front: three point four.

0:22

Then a map: which drivers are near me? For five hundred metres in the city centre, the smallest cells were the fastest. For two kilometres in the suburbs, they were almost eight times slower than the next size up.

0:37

Why would the same small cells win in one part of town, and lose almost eightfold in another?

0:45Intro

0:46

Hands-on system design, part twenty-one.

0:50

Today: typeahead on every keystroke, and finding drivers near you.

0:56Meet Lucía

0:57

I’m Lucía, a platform engineer.

1:00

My shop has a million products. The names are generated, like kadoon ultra tent y909, and so is each one’s popularity: a few are very popular, most are rarely bought.

1:14

On every keystroke, the search box asks for the ten most popular names that start with what you’ve typed. That’s called typeahead.

1:23

Think of a phone book. The names are sorted, so everything that starts with what you typed is one run of pages. Type one letter, and that run is huge.

1:3501 · What you need

1:37

To run it yourself: Python with a few packages, and Docker for Postgres with its map extension, PostGIS, and the typeahead service.

1:47

The quick tests run in a couple of seconds, without Docker.

1:52

The names, the keystrokes and the city are all generated, from fixed seeds. No cloud, and no API keys.

2:0202 · Short prefixes

2:03

Why would one letter be slow? The letters typed so far are called the prefix. Watch its run of pages shrink as you type.

2:12

One letter, k: fifty thousand names. Three letters: about ten thousand.

2:18

The whole brand, kadoon: two and a half thousand. Add the first letter of the next word: eighty-four. Kadoon ultra tent: three.

2:28

To give the ten most popular, Postgres has to look at every matching name and rank it. Fifty thousand names for one letter. Three for a long prefix.

2:4003 · One at a time

2:42

Sixty prefixes of each length, one at a time. The slowest answer in every hundred: with sixty, that’s close to the slowest one.

2:51

One letter: Postgres took under six milliseconds typically, and sixteen at the slowest. Eight letters: about one millisecond.

3:01

Now the phone-book index, in memory, built for this. It answered in about a millisecond at most, at every length but three letters.

3:11

And both gave the same top ten, for all three hundred prefixes.

3:1704 · The index in code

3:19

How does the phone-book index do it? It keeps the names sorted.

3:24

It finds the run with a binary search: jump to the middle, then the middle of the half that’s left, until it hits the start of the run.

3:33

And when it starts up, it works out the top ten for every one- and two-letter prefix. These generated names start with only nineteen letters, and twenty two-letter pairs: thirty-nine tabs. The code calls them a cache, but they’re built once and never expire, unlike the cache coming up.

3:52

A short prefix is answered from its tab. Anything longer is ranked on the spot.

3:58

That’s why three letters was its slow case: no tab. Kad, our example, has ten thousand names. The median three-letter prefix has two and a half thousand; the biggest, sixty thousand. Five point three milliseconds at the slowest.

4:1505 · Many users typing

4:16

Now many users typing at once. The keystrokes are generated too: each is the first one to ten letters of a product, picked by popularity. So the hundred most common prefixes make up thirty-seven percent of all keystrokes.

4:33

Five hundred keystrokes a second: all three ways stayed under eight milliseconds, at the slowest one in a hundred.

4:41

Fifteen hundred a second. Postgres alone: eighty-two milliseconds. My guess: the short prefixes queued up behind each other. This test doesn’t measure the queue.

4:53

And with a cache of answers per prefix in front, each kept for sixty seconds?

5:00

Three point four milliseconds. The cache answered seventy-nine percent of keystrokes, because people keep typing the same prefixes, and the short, slow ones repeat the most.

5:13

At five hundred a second, sixty-five percent. Each run started with an empty cache, so a prefix’s first appearance is a miss. The fifteen hundred run had thirty thousand keystrokes against ten thousand, so more of them were repeats. And by its design, the cache keeps an answer for sixty seconds, so a new product could wait up to a minute to show up.

5:36

And the phone-book index: seven point six. The service is one process, so while it ranks a big three-letter run, other keystrokes wait. A guess, not measured.

5:4806 · Cells on a map

5:50

Now the map. A rider asks: which drivers are within five hundred metres, or two kilometres?

5:57

A geohash cuts the map into rectangular cells, each named by a short code. The number of characters is the precision. One more character: a cell thirty-two times smaller in area. Here: about five by three kilometres, six hundred by seven hundred metres, and a hundred and fifty by ninety.

6:18

The city is generated: two hundred thousand drivers, sixty percent in a dense centre, most within three kilometres of the middle. The cells run in Python. PostGIS, the map extension, is a real database query, so its times include the trip to the database.

6:3907 · Finding drivers

6:40

To find drivers, in code: each driver goes in the cell of its geohash.

6:46

A query lists the cells around the circle,

6:50

collects the drivers in them,

6:53

and checks each one’s real distance.

6:5808 · The centre

6:59

Five hundred metres, in the dense centre: about three and a half thousand drivers found.

7:06

Big cells, precision five: two cells, but sixty-four thousand drivers to check. Twenty milliseconds typically.

7:15

Precision six: six cells, eleven and a half thousand checked, five milliseconds.

7:22

Precision seven: eighty-eight small cells, only five and a half thousand checked. Three point three milliseconds. Here, the smallest cells win.

7:33

PostGIS: four point seven, close behind, and that includes the trip to the database.

7:4209 · The suburbs

7:43

Now two kilometres, in the suburbs, where drivers are few: about a thousand found.

7:50

Precision six: forty-eight cells, one point one milliseconds.

7:55

Will the small cells win again?

8:00

No. Precision seven had to visit eleven hundred and eighty-eight cells, about one driver in each. Eight point six milliseconds: almost eight times slower.

8:12

So no cell size was best everywhere. The right size depends on how crowded that part of the map is, and a city has both. PostGIS’s index adapts by itself: one point nine here. Typically, never the fastest and never the slowest, in all four tests.

8:31

Every geohash answer matched a brute-force check of all two hundred thousand drivers. PostGIS differed on up to fourteen of a hundred and fifty: its Earth is eight point eight metres bigger, which moves a two-kilometre edge by about three millimetres. Rechecking with its radius gives the same answers.

8:52Back to Lucía

8:54

So, three lessons.

8:56

Short prefixes are the slow ones, and the common ones: give them tabs, or cache them.

9:03

Pick the cell size by how crowded the map is, or use an index that adapts.

9:10

And check the index against a brute-force answer. That’s how the three millimetres showed up.

9:17

Next time: a two-gigabyte upload over a connection that keeps dropping.

9:23

For today: cache the short ones.Lucía: Cache the short ones.

9:26Summary

9:28

Cache the short prefixes, size the cells by density, and check against brute force.

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.

Try it · How many names a prefix must rankLab 11 · 02_typeahead.py · prefix_index.py · 1,000,000 names

Pick what has been typed so far

“k”50,093 names start with it

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)

1 letterPostgres 16.1 msIndex 0.89 ms
2 lettersPostgres 7.15 msIndex 0.75 ms
3 lettersPostgres 6.09 msIndex 5.35 ms
5 lettersPostgres 5.70 msIndex 1.20 ms
8 lettersPostgres 1.00 msIndex 0.77 ms

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.

Try it · Keystrokes under loadLab 11 · 02_typeahead.py · exercise 2 · 20 s per run

Keystrokes per second, from users typing popular products

Postgres, p99
82.2 ms
With prefix cache, p99
3.37 ms
In-memory index, p99
7.57 ms
Postgresp50 1.87 ms
Postgres + prefix cachep50 0.38 ms · answered from cache 79%
In-memory indexp50 0.53 ms

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:

  1. 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.
  2. 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.
  3. 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.

Try it · Geohash cell sizeLab 11 · 03_geo.py · geohash.py · 200,000 drivers · 150 riders per area

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.

MethodCellsCheckedp50
Geohash, precision 5264,15819.8 ms
Geohash, precision 6611,5715.03 ms
Geohash, precision 7fastest885,438.53.31 ms
PostGIS (GiST index)––4.70 ms

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 5
4.9 × 4.9 km at the equator
4.9 km N–S × 3.0 km E–W at the city's latitude
precision 6
1.2 × 0.61 km at the equator
610 m N–S × 740 m E–W at the city's latitude
precision 7
153 × 153 m at the equator
150 m N–S × 90 m E–W at the city's latitude

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

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.

Learning something useful?

New labs, articles, and videos on evaluating and testing AI systems come out regularly. Follow along so you don't miss the next one.