Lesson 3 · Minutes 20-30

Proximity Service: Scaling It

Problem

Minutes twenty to thirty start from the 16,000 rows you volunteered, and the interviewer pulls on that thread in four places. First they ask you to say exactly what the compound index does with a box. Then they set 4,000 searches beside 2 edits and ask whether the index belongs in the database at all. Next they compare one search downtown with the same search in farm country. Last, they stand the user beside the edge of a cell, with the answer just across it.

Each of those gets one change and the price of that change. The last figure on this page is the first figure with the changes marked.

Two Ranges, One Index

"Walk me through what that index reads to answer a box." It reads the strip. The index is sorted by latitude, so the latitude range is one run of entries. Inside that run, longitude is in no useful order, so the second condition gets checked row by row across the whole strip. A second index on longitude only reads a strip of its own.

The change is to name each small area of the map with one sortable value, a cell ID, and index that. A geohash is the usual way to make one. It takes the bits of latitude and longitude, interleaves them one from each, and writes the result in base 32. A shared prefix then means a shared larger cell, and a prefix on a sorted index is one range, the cheap scan of neighbouring keys in Chapter 3's Range, Hash and Directory.

A 6-character cell is 1.2 km by 610 metres at the equator, about 0.7 square km, which suits a 500-metre radius. Assume a suburb with 100 places a square km. That is about 70 rows a cell, against the strip's 16,000.

What it costs is a column computed on every write, and two new problems. "Near" now has edges, and the cells ignore density. Both are waiting further down this page.

Thousands of Reads, a Handful of Writes

"It's 4,000 searches a second at peak and about 2 edits. Does that change where the index lives?" It does: the index leaves the database. This is where the number you parked in Scope comes back. The searchable part is about 2 GB against 100 GB of memory, so each application server becomes a search server with a full copy of the cell index in memory, and copies carry the load.

Assume one server answers 1,000 searches a second at half its limit. That is 4 servers at peak, and a fifth so that losing one changes nothing.

The index only finds IDs, so the records come from somewhere else. Twenty results at 4,000 searches a second is 80,000 record reads a second, from a cache filled on a miss and keyed by place ID, the cache-aside of Chapter 2's Caching at Scale. At half of 100,000 operations a second, that is 2 nodes, and their 200 GB holds all 160 GB. Read replicas of the database take the rare misses. Give each cache node a replica of its own, because a lost node would otherwise drop 40,000 reads a second on those replicas at once.

The 100 milliseconds is not in danger. A server asks each of the 2 nodes for its share of the 20 in one batched call, so that is two round trips, 1 to 2 milliseconds each even across zones. That leaves more than 90 of the 100. Batching saves trips and lightens the reads as well, so 2 nodes sized for 80,000 plain reads stay on the safe side.

Partitions wait until the index outgrows a server. A hundred GB at 24 bytes is about 4 billion places, and about 2 billion if a server must hold two indexes during a swap. Either is at least 25 times today's count. If that day comes, split by ranges of cell ID, since a hash scatters neighbours. Say it plainly: "Copies, not partitions. The index is about 2 GB, so every server can hold all of it."

The index still has to learn about edits, away from the request path. An edit goes to the primary, which records it in a change log. Each hour a builder applies that log to the last index and publishes the result as one file. Every server loads the new file next to the one in service and swaps, and 2 GB over a 10-gigabit link is under two seconds. When it publishes, the builder also removes the hour's edited places from the record cache, so a record is never further behind than the index. That cache needs no short expiry; a day is enough, as a net under a removal that fails.

Chapter 9 rebuilds and swaps too, and there the swap is the dangerous step: an index that nearly fills a machine, and a load that takes minutes. Here the file loads in two seconds and leaves most of the memory free. A bad file still reaches every server at once, so the builder compares its count of places with the last file's before publishing, and the last good one is two seconds away.

The new parts can fail, and search outlives each of them. A builder that stops leaves the last file in service, and results age past the hour until it runs again. If the log is ever lost, the builder reads the whole table from a replica and starts clean. A lost primary stops edits and no searches, and one replica kept synchronous takes over with every saved edit, the arrangement in Chapter 4's Leaders, Followers and Everyone.

What it costs: results up to an hour stale, a builder to run, and a server that has to load the file before it can answer, so the load balancer sends a new server nothing until it has.

Downtown and the Prairie

"Same 500 metres, downtown and in farm country. What does each search read?" Downtown, far too much. Assume 4,000 places a square km. A 500-metre circle of about 0.8 square km holds about 3,200, and a 6-character cell holds about 2,900. In the country, nearly nothing. Assume one place per 10 square km. That circle usually holds none, and the 2 km retry, about 13 square km, holds about one.

So let cell length follow density. The index becomes a tree of cells that starts at 5 characters, and a cell past a cap, assume 200 places, splits one character deeper. It starts at 5 because a cap alone would stop the country at 4, about 76 places a cell and nearly 700 in a block, when 5 characters already reach past the 2 km retry. A leaf is a cell that has not split. Downtown goes to 7 characters, 153 by 152 metres, about 93 places a leaf. The country stays at 5. Splitting stops at 9 characters, about 5 metres, because a mall's shops can share one point and no split would ever part them. That rare leaf runs past the cap.

Eighty million places in leaves of about 100 would be about 800,000 leaves. Assume the country's thin leaves push that to a few million, and that a leaf costs under 100 bytes, a cell ID and where its entries start. The tree is still under a gigabyte. That decides nothing: the whole index stays under 3 GB, and the file still loads in under three seconds.

What it costs: cells of mixed length, which only a structure in memory handles well, and splits that wait for the next rebuild. The next probe says why a search reads nine cells and not one.

The same 500 metres, downtown and in the country
Downtown4,000 places a square km
7-character cells, about 93 places a cell. About 840 places checked in nine cells.
The countryone place per 10 square km
5-character cells, about 2.4 places a cell. About 22 places checked in nine cells.

The Edge of the Cell

"They're on the boundary, and the closest place is ten metres the other way. What did you just return?" The wrong answer, if you read only the user's cell. So always read the 3-by-3 block, the user's cell and its eight neighbours, and filter all of it by true distance. That also corrects an earlier sum: a suburb's search checks about 630 places, not 70, still a twenty-fifth of the strip.

Neighbours come from coordinates: step one cell's width from the centre in each direction, and find the cell there. Trimming the ID does not work, because adjacent cells can share no prefix at all, across the equator, the prime meridian or any coarser split line. Where a neighbour has split finer, you read each of its leaves along the shared side, which adds a few lookups, and the block's edge on that side moves in to the far side of those leaves.

The block covers a radius only up to one cell's width. A 6-character cell's 610 metres covers 500, and at 60 degrees of latitude the 1.2 km side, now half as wide, still does.

A dense leaf is narrower than the radius, so downtown's block reaches 152 metres in the worst case, not 500. Twenty places at 4,000 a square km fill a circle of about 40 metres, well inside that. If it did not fit, you would read the next ring, the band of cells just outside the block. The rule comes out as one sentence: "The block proves the result only out to its edge, so I accept when the twentieth is nearer than that edge, and otherwise I read the next ring."

A search with fewer than 20 in range stops once the block's edge passes the radius, and a next page asks the same question of the fortieth.

The 3-by-3 block: the result is proven out to its edge
Westouter column
Northwest
West
Southwest
Middlethe user's column
North
The user's cell
South
Eastouter column
Northeast
East
Southeast

What it costs: nine lookups a search, 36,000 a second, all in local memory. Downtown's 840 places at about 100 nanoseconds each is under 100 microseconds, which decides nothing.

Search Without the Database

A search now goes from the load balancer to a search server, the same stateless server as before with a full cell tree in its memory. The tree gives it the nearest 20 IDs, and the record cache gives it their records, with read replicas behind that for a miss. The database has left the search path. An owner's edit goes through the same servers to the primary and into the change log, and the builder turns that log into a published file, which comes back to the search servers. The builder also clears the hour's edited places from the record cache.

The table has not gone anywhere. It takes every edit, the replicas copy it, and any file can be rebuilt from it. All it loses is the compound index and the cell ID column, because nothing searches there now and the builder works out cell IDs itself.

The first design, with what changed marked new
Read path Write path Clientsearches and edits Cell treenearest IDs, in memoryNEW Load balancerany server Record cache20 records, by IDNEW Search servers5, and they take edits Read replicasthe rare missNEW Primaryone sync standby Published filelast good one keptNEW Index buildereach hourNEW Change logevery editNEW search or edit miss edit swap clears readwriteasynccache missNEWsince the first design
Interview Pitfalls
  • Partitioning by region to "scale reads". It adds a boundary to cross and buys nothing, because copies carry reads and the bytes fit.
  • Trimming the cell ID to find neighbours, which fails at exactly the boundaries that matter.
  • Treating nine cells as always enough, when a dense leaf is smaller than the radius. The interviewer asks what proves the twentieth, and nothing does.
What Interviewers Listen For
  • Copies named instead of partitions, with the 2 GB that allows them.
  • Downtown and the country both given numbers, not adjectives.
  • The stop rule said as a sentence, which shows you know how far the block's proof reaches.

Knowledge Check

Two places share a 5-character geohash prefix, and two others share no prefix at all. What does that tell you?

  • The first pair is closer together than the second pair is
  • The first pair share a cell, and the second may still be neighbours
  • The second pair must lie at least one whole cell apart
  • The first pair lie within the radius of a user in that cell

What does the hourly rebuild cost, set against updating the index on each edit?

  • A search outage on every server for as long as the swap takes
  • An owner's save that waits until the next file is published
  • A careful staged rollout, since a bad file reaches every server
  • Results that can be an hour stale, and a builder left to run

You lower the cap on a leaf from 200 places to 50. What are you trading?

  • Fewer places checked per search, for more splits at each rebuild
  • A smaller tree in memory, for more places checked per search
  • Fresher results, for a builder that must run four times as often
  • Better cover at a cell's edge, for more neighbours to compute

When is reading the 3-by-3 block not enough to answer a search?

  • When the user stands a few metres from the edge of their cell
  • When the user's cell and a neighbour share no prefix at all
  • When the twentieth place lies further off than the block's edge
  • When the block holds many more places than the 20 asked for

You got correct