Courses / System Design Interview / Chapter 29
Module 6 · Design Problems I: Video, Q&A and Location · Chapter 29 of 49
Design a Nearby Places Service like Yelp
Builds on Back-of-the-Envelope Estimates, Databases: Choosing, Replicating and Partitioning, Distributed Caches, Distributed Message Queues, Distributed Search and Design a Maps and Navigation Service like Google Maps. Next up: Design a Ride-Hailing Service like Uber.
Part 1 · Requirements and estimates
What the service must do
Apps that show cafes, petrol pumps and clinics near you all answer one question: which places lie within a given distance of this point? This chapter designs that search for a service with twenty crore listed places.
The functional requirements are: given a point and a radius, return the places inside it, with an optional category filter, ranked and paged; return the details of one place by its id; and let owners and an admin pipeline add, change and remove places. Writing reviews, photos, map drawing, turn-by-turn routes and free-text search over names are out of scope. Routes are in the maps chapter, and text search is in the search chapter.
The non-functional requirements shape the design more. A search must answer in a few hundred milliseconds, because people run it while standing on a pavement. Searches far outnumber edits to places, so the service is read-heavy. A new place may take a few minutes to appear, so we accept eventual consistency on the write path. The service must stay up when a machine fails, and results must stay relevant: a place 100 metres away with a poor rating should not always beat a good one 300 metres away.
| Question to ask | Answer we assume |
|---|---|
| How many places? | 20 crore, listed worldwide |
| How many searches? | 10 crore a day |
| Largest radius? | 50 km; the default is 2 km |
| Results per page? | 20 |
| How fresh must edits be? | Visible within a few minutes |
| Do places move? | No, they are fixed points |
The last row separates this chapter from the next one. A cafe stays where it is for years, so the index can be built in advance and replaced in bulk. A taxi moves every few seconds, and an index of moving points needs a different update path, which a later chapter covers.
Sizing the index
Two things need sizing: the index that answers searches and the load on it. The index holds one entry per place with its id, its latitude and longitude, a spatial cell code (the next lessons explain the cell), a rating and a category. We assume 48 bytes for an entry. The search load comes from 10 crore searches a day, with the busy hour five times the daily average, and each response carries 20 results of about 300 bytes.
The script below uses the same habit as the estimates chapter: every input is a named assumption at the top, and every line prints one result. Five percent of places are assumed to change in a year, which sets the write rate.
# Inputs are assumptions for a national places service. places = 200_000_000 # listed places entry_bytes = 48 # id, lat, lon, cell, rating, category replicas = 3 # copies of the index searches_per_day = 10_00_00_000 # 10 crore searches a day peak_factor = 5 # busy hour against the daily average results_per_search = 20 result_bytes = 300 # name, address, rating, distance index_gb = places * entry_bytes / 1e9 print(f"index, one copy: {index_gb:,.1f} GB") print(f"index, {replicas} copies: {index_gb * replicas:,.1f} GB") avg_qps = searches_per_day / 86_400 print(f"searches per second, average: {avg_qps:,.0f}") print(f"searches per second, peak: {avg_qps * peak_factor:,.0f}") peak_qps = avg_qps * peak_factor mbps = peak_qps * results_per_search * result_bytes * 8 / 1e6 print(f"response bandwidth at peak: {mbps:,.0f} Mbps") new_per_day = places * 0.05 / 365 # 5% of places change each year print(f"place updates per day: {new_per_day:,.0f}") print(f"place updates per second: {new_per_day / 86_400:.2f}")
Python 3.12.10. All inputs are assumptions.
index, one copy: 9.6 GB index, 3 copies: 28.8 GB searches per second, average: 1,157 searches per second, peak: 5,787 response bandwidth at peak: 278 Mbps place updates per day: 27,397 place updates per second: 0.32
Output of the estimate.
One copy of the index is 9.6 GB, and three copies are 28.8 GB. That is small. A single large machine can hold the whole index in memory, so we shard for throughput and availability, not because the data does not fit. Searches average 1,157 a second and peak near 5,787 a second, which is 278 Mbps of responses at the busy hour. Edits are 27,397 a day, or 0.32 a second, about one every three seconds.
What the estimate decides
Peak searches per second: ≈ 5,800 /s (about 278 Mbps of responses)
Read it as steps
Twenty crore places fit in a few tens of gigabytes; the busy hour is the real pressure.
The scene gives the same arithmetic in the order a person would say it. Three decisions follow from it. First, the index lives in memory, since 29 GB across the copies is cheap and a disk seek per search would be slow. Second, the read and write paths are separate: 5,800 searches a second and one edit every three seconds have nothing in common, so edits go through a queue to an indexer that updates the search copies, as in the message queue chapter.
Third, the cost per search matters more than the number of searches. A radius query must not examine all twenty crore entries. It must narrow the candidates to the few hundred places that could be inside the circle, using a spatial index, and only then measure exact distances. The next three lessons are about that narrowing. Doing the arithmetic first told us where the difficulty is.
The index is only 9.6 GB for one copy. Why still keep three copies?
- Copies add search throughput and survive a machine failure. Capacity is not the reason, because the data would fit on one machine.
Edits arrive about once every three seconds while searches peak near 5,800 a second. What does that imply?
Part 2 · API and data model
The search call
The service has one hot call, the nearby search, and a few small ones. A search is a GET with the point, the radius and the filters in the query string. It is a read, it is safe to repeat and it can be cached, as the cache chapter explains. The sketch below shows the calls. It is a design sketch and it is not run.
GET /v1/places/search?lat=12.9716&lon=77.5946&radius_m=2000 &category=cafe&limit=20&cursor=... 200 OK { "results": [ { "id": 8841, "name": "Cafe Mango", "category": "cafe", "distance_m": 312, "rating": 4.4, "reviews": 280 } ], "next_cursor": "..." } GET /v1/places/{id} one place, full details POST /v1/places add a place (owner or import job) PUT /v1/places/{id} change a place DELETE /v1/places/{id} remove a place
API sketch, not run. Cursor paging is explained just below.
Three choices are worth stating. The distance is computed by the server and returned, so the client does not need to know how ranking weighed it. Paging uses an opaque cursor and not a page number, because the ranked list can change between two calls, and a cursor stays valid when it does. And the radius has a ceiling of 50 km: an unbounded radius lets one request ask for a crore of places.
The write calls go to a separate service. A change is stored in the place database, and an event is put on a queue so that the index builder can update the search copies a little later. The write response says only that the change was accepted, which matches the requirement that edits become visible within minutes.
The data model
The source of truth is a database table with one row per place. It holds the fields the details page needs, plus a geohash: a short text code that names the small square cell the place sits in. The fourth lesson builds it. Storing the code as a column lets an ordinary database index answer part of the search, with no special spatial extension.
import sqlite3 db = sqlite3.connect(":memory:") db.executescript(""" CREATE TABLE places ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, category TEXT NOT NULL, lat REAL NOT NULL, lon REAL NOT NULL, geohash TEXT NOT NULL, -- 7 characters, about 150 m cells rating REAL NOT NULL, reviews INTEGER NOT NULL DEFAULT 0 ); CREATE INDEX places_geohash ON places (geohash); CREATE INDEX places_cat_geohash ON places (category, geohash); """) for row in db.execute("PRAGMA index_list(places)"): print("index:", row[1]) plan = db.execute( "EXPLAIN QUERY PLAN SELECT id FROM places " "WHERE category = 'cafe' " "AND geohash >= 'tdr1w' AND geohash < 'tdr1x'" ).fetchall() detail = plan[0][3] print("plan:", detail.split(" (")[0]) print(" (" + detail.split(" (")[1])
Python 3.12.10. The table, two indexes and the query plan.
index: places_cat_geohash
index: places_geohash
plan: SEARCH places USING COVERING INDEX places_cat_geohash
(category=? AND geohash>? AND geohash<?)Output. SQLite reports its plan.
The plan line shows the query reading only an index. The category and geohash columns together answer 'cafes in this cell range' without touching the table. A geohash prefix such as tdr1w stands for a whole area, and every longer code that starts with it lies inside that area. So the condition geohash >= 'tdr1w' AND geohash < 'tdr1x' selects every place in that area, and an index on text keeps such a range cheap.
The index in a real service is a copy of this table's useful columns, held in memory in a structure shaped for spatial queries. The database remains the record, and the index can always be rebuilt from it. That is also how a new index version is rolled out: build it beside the old one, check it, and switch.
Spatial support in databases
Many databases already have spatial support, so it is fair to ask why a service would build its own index. PostGIS, the spatial extension of PostgreSQL, offers ST_DWithin, which returns true when two geometries are within a given distance. Its documentation says the call includes a bounding box comparison that uses any available index, and the exact distance test runs only on what remains. For a geography type the distance is in metres.
Redis offers a geospatial index too. Its GEOADD command stores each item in a sorted set, using a geohash whose latitude and longitude bits are interleaved into one 52-bit integer. Its documentation limits latitudes to about plus and minus 85.05112878 degrees, and notes that distances use the haversine formula on a sphere, with an error of up to 0.5 percent in the worst case.
These are good answers for a modest data set, and a design can say so. The reasons to build more are scale and control: ranking that mixes rating, distance and freshness, sharding by region, and a copy of the index that is exactly the shape the search needs. Whatever the engine, the ideas are the ones in the next lessons: cells, neighbours and an exact check at the end.
Why does the search call use a cursor instead of a page number?
- The ranked list can change between calls, for example when a place is added. A cursor stays valid when that happens, and a page number can repeat or skip results.
What does the geohash column let an ordinary database index do?
- It turns a map area into a text range. Places in an area share the code's prefix, so a range condition on the text column selects them.
Why is the place table still needed if the search uses an in-memory index?
- The table is the source of truth. The index is a copy shaped for fast search, and it can be rebuilt from the table at any time.
Part 3 · High-level design
Search path and write path
The design has two paths that meet only at the place store. The search path takes a point and a radius, finds the index shards that could hold matching places, collects candidates from them, ranks them and returns a page. The write path takes an edit, saves it in the store, and updates the index shards afterwards through a queue.
Keeping them apart has a practical benefit. The index shards serve only reads while the indexer updates them in small batches, so searches never wait for a write, and a flood of imports does not slow searches down. The price is the delay noted in the requirements: a new place is searchable after the indexer has applied it, usually within seconds or minutes.
The components are few. A gateway checks limits and routes requests. A ranker asks shards for candidates, merges them, scores them and builds the response. The index shards each hold part of the spatial index in memory. The place store is the database of record. The indexer reads edit events from the queue and applies them to the shards. A cache in front of the ranker holds popular searches, since many people ask for 'cafes near this station'.
How a search travels
Watch for one search reaching only the shards that cover its area
Read it as steps
A search fans out to the index shards that cover the area, then the ranker merges and hydrates.
The scene shows the scatter-gather pattern that the search chapter also uses: the ranker sends the same question to several shards and merges what comes back. Here it asks only the shards whose cells touch the circle, so most of the cluster stays idle for a given search. The scene's hit counts are an illustration, not measurements.
Notice what the shards return. They send ids, positions and the few fields ranking needs, and the ranker fetches full details from the store for the twenty it keeps. Moving twenty rich rows is far cheaper than moving every candidate's details, and the hydration step can use the cache from the earlier chapter.
Sharding the index, and where it goes wrong
There are two ways to split the index. Sharding by region gives each shard the places in a range of cells, as in the scene, so a search usually touches one or two shards. This is efficient, but density varies hugely. One shard holding a metro area carries far more places and far more searches than one holding a desert, so a fixed split leaves hot shards. The remedy is to split by load and not by area: dense regions are divided into several shards, and sparse regions are merged, with a small map from cell range to shard.
Sharding by place id spreads places evenly, so no shard is hot, but every shard may hold matches for any search, so every search goes to every shard. At 5,800 searches a second and many shards, that multiplies the work. Region sharding wins for this workload because the question is always local. Placing replicas of the same region on different machines gives the throughput and the failure tolerance that the estimate asked for.
A third concern is the busy centre of a city, where one cell holds thousands of places. A search there returns many more candidates than a search in a village, so it takes longer. The ranker asks each shard for its nearest candidates first and caps how many it takes, so a dense cell cannot make one search slow. Queries that cover dense areas are exactly the ones to watch in monitoring.
Why are the search path and the write path kept apart?
- Index shards then serve only reads, so searches never wait for writes. The cost is that a new place appears after the indexer applies it.
Why can sharding by region produce a hot shard?
- Places are not spread evenly. A shard that holds a dense city centre gets far more places and searches than one holding empty land, so dense regions must be split further.
What is the drawback of sharding by place id for this service?
- Every shard may hold a match for any search, so every search goes to every shard. The work per search grows with the number of shards.
Part 4 · Deep dive: geohash
Cells and codes
A geohash turns a latitude and longitude into a short string. It repeatedly halves the world: the first bit says whether the longitude is in the western or eastern half, the second whether the latitude is in the southern or northern half, then the longitude is halved again, and so on, alternating. Every five bits are written as one character of a 32-letter alphabet. Each added character shrinks the cell, and a longer code names a smaller cell inside the one named by its prefix.
The encoder is short. The loop keeps a low and a high value for latitude and longitude, and decides one bit at a time which half the point lies in.
BASE32 = "0123456789bcdefghjkmnpqrstuvwxyz" def encode(lat, lon, length=7): lo, hi = [-90.0, -180.0], [90.0, 180.0] # [lat, lon] ranges out, bits, ch, axis = [], 0, 0, 1 # longitude bit first while len(out) < length: v = lon if axis else lat mid = (lo[axis] + hi[axis]) / 2 ch <<= 1 if v >= mid: ch |= 1 lo[axis] = mid else: hi[axis] = mid axis ^= 1 bits += 1 if bits == 5: out.append(BASE32[ch]) bits, ch = 0, 0 return "".join(out)
Python 3.12.10. Save this block and the next one together as geohash.py.
To go the other way, bounds replays the bits of a code and returns the square it names. neighbours finds the eight cells around a cell by stepping one cell width or height from its centre and encoding the result, wrapping the longitude at the date line.
def bounds(code): lo, hi = [-90.0, -180.0], [90.0, 180.0] axis = 1 for c in code: v = BASE32.index(c) for shift in (4, 3, 2, 1, 0): mid = (lo[axis] + hi[axis]) / 2 if (v >> shift) & 1: lo[axis] = mid else: hi[axis] = mid axis ^= 1 return lo[0], hi[0], lo[1], hi[1] # lat_lo, lat_hi, lon_lo, lon_hi def neighbours(code): la0, la1, lo0, lo1 = bounds(code) h, w = la1 - la0, lo1 - lo0 clat, clon = (la0 + la1) / 2, (lo0 + lo1) / 2 out = set() for dy in (-1, 0, 1): for dx in (-1, 0, 1): lat = clat + dy * h if (dy or dx) and -90 < lat < 90: lon = (clon + dx * w + 180) % 360 - 180 out.add(encode(lat, lon, len(code))) return sorted(out - {code})
Decoding a code into its cell, and the eight neighbouring cells.
How big is a cell
Cell size depends only on the code's length. The script below prints the code for one invented point in Bengaluru at lengths 3 to 8, with each cell's size in degrees and an approximate size in metres. Metres per degree of longitude shrink with the cosine of the latitude, so the east-west size is computed at the point's latitude.
import math from geohash import BASE32, encode, bounds, neighbours # A point in Bengaluru (invented) and the cell sizes around it. lat, lon = 12.9716, 77.5946 print("length cell (lat x lon, degrees) about (m x m)") for n in range(3, 9): code = encode(lat, lon, n) la0, la1, lo0, lo1 = bounds(code) m_lat = (la1 - la0) * 111_320 m_lon = (lo1 - lo0) * 111_320 * math.cos(math.radians(lat)) print(f"{n:>4} {code:<9} {la1-la0:.5f} x {lo1-lo0:.5f} " f"{m_lat:,.0f} x {m_lon:,.0f}") code = encode(lat, lon, 6) print("cell:", code) print("neighbours:", *neighbours(code))
Save as sizes.py, next to geohash.py.
length cell (lat x lon, degrees) about (m x m) 3 tdr 1.40625 x 1.40625 156,544 x 152,549 4 tdr1 0.17578 x 0.35156 19,568 x 38,137 5 tdr1v 0.04395 x 0.04395 4,892 x 4,767 6 tdr1v9 0.00549 x 0.01099 611 x 1,192 7 tdr1v9q 0.00137 x 0.00137 153 x 149 8 tdr1v9qt 0.00017 x 0.00034 19 x 37 cell: tdr1v9 neighbours: tdr1v2 tdr1v3 tdr1v6 tdr1v8 tdr1vb tdr1vc tdr1vd tdr1vf
Output. Each row is the point's code at one length.
A length of 7 gives cells about 150 metres on a side, and a length of 6 gives cells about 600 by 1,200 metres. The shape alternates because five bits cannot split evenly between the two axes: odd lengths give a square cell and even lengths give a cell twice as wide as it is tall. A length of 5 is about 5 km, a sensible grain for a search radius of a few kilometres.
The cell tdr1v9 has eight neighbours, all printed above, and here they all share the prefix tdr1v. That is luck of position. A cell at the edge of a larger cell has neighbours whose codes differ early, and the last lesson returns to that point: neighbours in space do not always share a long prefix.
Which prefix length to search with follows from the radius and the sizes printed above, which are for a point near Bengaluru. The rule is to take the longest prefix whose cell is still at least as large as the radius on its smaller side, so that the circle touches at most the cell and its eight neighbours. For the default 2 km radius that is 5 characters, whose cells are about 4.8 km on the smaller side, because 6 characters give only 611 metres. For the largest 50 km radius it is 3 characters, whose cells are about 152 km, because 4 characters give only 19.6 km. The table stores 7 characters, which is finer than any search needs, and a search reads the shorter prefix of the stored code with the range condition from the second lesson, so one column serves every radius.
Searching by prefix
A geohash prefix selects an area, so a sorted list of codes can answer area queries with a range scan. The script indexes 1 lakh invented points over Bengaluru by their 8-character codes in a sorted list, then reads the points in one 6-character cell and in its eight neighbours using a binary search for the start and end of each prefix.
import bisect import random from geohash import encode, neighbours lat, lon = 12.9716, 77.5946 rnd = random.Random(7) pts = [(rnd.uniform(12.85, 13.10), rnd.uniform(77.45, 77.75)) for _ in range(100_000)] index = sorted((encode(la, lo, 8), i) for i, (la, lo) in enumerate(pts)) def by_prefix(prefix): a = bisect.bisect_left(index, (prefix, -1)) b = bisect.bisect_left(index, (prefix + "~", -1)) return [i for _, i in index[a:b]] cell = encode(lat, lon, 6) inside = by_prefix(cell) around = [i for c in neighbours(cell) for i in by_prefix(c)] print("points in the cell:", len(inside)) print("points in the 8 neighbours:", len(around)) print("rows read for a 5-character prefix:", len(by_prefix(cell[:5])))
Save as prefix.py. A sorted list and binary search stand in for a database index.
points in the cell: 69 points in the 8 neighbours: 670 rows read for a 5-character prefix: 2640
Output of the script.
The cell holds 69 points and its neighbours 670, so a search around that point looks at 739 candidates out of 1 lakh and then measures exact distances on those. A shorter 5-character prefix reads 2,640 points, which is the same trade the cells make: larger cells mean fewer lookups and more candidates to filter.
Geohash has strengths and a weakness. It is simple, it works with any ordered index, it can be stored in a plain text column, and Redis uses the same idea. Its weakness is that cells are fixed in size, so a dense centre puts thousands of points in one cell while a village cell holds none, and cells grow narrower towards the poles. The next lesson looks at a structure that adapts to density.
What does one more character in a geohash do to the cell?
- It shrinks the cell. The new cell sits inside the old one, and five more bits of position are given.
From the run, about how big is a cell with a 7-character code?
- About 153 by 149 metres at that latitude, so roughly 150 metres a side.
Part 5 · Deep dive: quadtrees and other cell systems
A quadtree that follows the data
A quadtree also splits space into squares, but only where there is data. It starts with one square covering the whole area. When a square holds more than a set number of points, called its capacity, it splits into four equal squares and hands its points to them. A dense centre keeps splitting, and a quiet suburb stays one big square. The squares that hold points directly are the leaves.
The code uses a capacity of 100 points, and each node knows its bounds in latitude and longitude. The haversine_m function in the first block gives distances in metres on a sphere.
import math def haversine_m(la1, lo1, la2, lo2): """Great-circle distance in metres on a sphere of mean radius.""" p1, p2 = math.radians(la1), math.radians(la2) a = (math.sin((p2 - p1) / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(math.radians(lo2 - lo1) / 2) ** 2) return 2 * 6_371_008.8 * math.asin(math.sqrt(a))
Python 3.12.10. Save as geo.py.
import math from geo import haversine_m CAP = 100 # a leaf splits when it would hold more than this class Node: def __init__(self, la0, la1, lo0, lo1, depth=0): self.b = (la0, la1, lo0, lo1) self.depth = depth self.pts = [] # (lat, lon, id) while a leaf self.kids = None def insert(self, p): if self.kids: return self.kids[self._which(p)].insert(p) self.pts.append(p) if len(self.pts) > CAP and self.depth < 24: self._split() def _which(self, p): la0, la1, lo0, lo1 = self.b return (p[0] >= (la0 + la1) / 2) * 2 + (p[1] >= (lo0 + lo1) / 2)
Save this block and the next two together as quadtree.py.
def _split(self): la0, la1, lo0, lo1 = self.b ma, mo = (la0 + la1) / 2, (lo0 + lo1) / 2 d = self.depth + 1 self.kids = [Node(la0, ma, lo0, mo, d), # south-west Node(la0, ma, mo, lo1, d), # south-east Node(ma, la1, lo0, mo, d), # north-west Node(ma, la1, mo, lo1, d)] # north-east pts, self.pts = self.pts, [] for p in pts: self.kids[self._which(p)].insert(p)
Continues the Node class: splitting a full leaf.
Insertion walks down to the right leaf and appends the point. If the leaf is now over capacity, it splits, and the points are pushed into the four new children. A guard stops splitting at depth 24, in case many places share the same coordinates.
Radius search on the tree
A radius search works in two steps. First, the circle is wrapped in a bounding box, and the tree is walked, skipping every square that does not touch the box. The leaves that do touch it give the candidates. Second, exact distances are measured on the candidates with the haversine function. The box is a quick test, and the circle is the true one.
def search(node, box, stats, out): la0, la1, lo0, lo1 = node.b if la1 < box[0] or la0 > box[1] or lo1 < box[2] or lo0 > box[3]: return # cell does not touch the box stats["nodes"] += 1 if node.kids: for k in node.kids: search(k, box, stats, out) else: stats["checked"] += len(node.pts) out.extend(node.pts) def radius(root, lat, lon, r_m): dlat = r_m / 111_320 dlon = r_m / (111_320 * math.cos(math.radians(lat))) box = (lat - dlat, lat + dlat, lon - dlon, lon + dlon) stats, cand = {"nodes": 0, "checked": 0}, [] search(root, box, stats, cand) hits = [p for p in cand if haversine_m(lat, lon, p[0], p[1]) <= r_m] return hits, stats
Continues quadtree.py: walk the tree for a box, then filter by distance.
The next script puts 60,000 invented places into the tree: three dense neighbourhoods hold three quarters of them and the rest are spread across the city. It then searches 500 metres around a point in a dense area and around a point in a sparse one, and compares each answer with a brute-force scan of all points.
import random from geo import haversine_m from quadtree import Node, radius rnd = random.Random(11) centres = [(12.97, 77.59), (13.03, 77.70), (12.91, 77.50)] pts = [] for i in range(60_000): if i % 4: # three dense neighbourhoods c = rnd.choice(centres) pts.append((rnd.gauss(c[0], 0.012), rnd.gauss(c[1], 0.012), i)) else: # and places spread over the whole city pts.append((rnd.uniform(12.80, 13.15), rnd.uniform(77.35, 77.85), i)) root = Node(12.5, 13.5, 77.0, 78.0) for p in pts: root.insert(p)
Save this block and the next together as quad_run.py.
def leaves(n): return [n] if not n.kids else [x for k in n.kids for x in leaves(k)] ls = leaves(root) print("leaves:", len(ls), " depth:", min(l.depth for l in ls), "to", max(l.depth for l in ls), " biggest leaf:", max(len(l.pts) for l in ls)) probes = [("dense", centres[0]), ("sparse", (12.82, 77.40))] for name, (la, lo) in probes: hits, st = radius(root, la, lo, 500) brute = [p for p in pts if haversine_m(la, lo, p[0], p[1]) <= 500] print(f"{name}: hits {len(hits)} (brute force {len(brute)})") print(f" nodes visited {st['nodes']},", f"points checked {st['checked']} of {len(pts)}")
Continues quad_run.py: count leaves, then query and compare.
S2 and H3, and when to choose which
Geohash and quadtrees are the simple end of a family of cell systems. Google's S2 library divides the sphere into cells that form a hierarchy of 31 levels, numbered 0 to 30, and its leaf cells are about 1 cm across. Cells are numbered along a space-filling curve built from six Hilbert curves, so cells with nearby ids are usually near each other in space. That locality is what lets a range scan over ids find the places near a point.
H3 is Uber's hexagonal grid. Its blog post explains why hexagons: a hexagon has one distance from its centre to every neighbour's centre, where a square has two and a triangle has three, which makes smoothing and radius questions simpler. H3 has resolutions 0 to 15. Its documentation lists an average edge of about 200 metres at resolution 9, where the world has 4,842,432,842 cells, and about 0.58 metres at resolution 15.
For a nearby-places service, the choice is practical. Geohash is easiest, works in a plain text index and suits modest scale. A quadtree adapts to uneven density but is a structure to build and keep in memory. S2 and H3 give uniform treatment of the globe and better neighbour handling, at the cost of a library. A design should state the choice and the reason: for example, geohash for a first version, with the prefix length chosen from the search radius as the fourth lesson shows, and a move to cells of equal area later if the poles or the cell borders cause trouble.
Why does a quadtree handle a dense city centre better than fixed geohash cells?
- It splits a square only when it holds too many points, so dense areas get small squares and sparse areas stay large.
From the run, how many points did the dense 500 metre query examine, out of 60,000?
- 1,787 points. The sparse query examined only 84. The work depends on the nearby data and not on the whole set.
What property of a hexagonal grid does the H3 post give as its reason for hexagons?
- A hexagon has a single distance from its centre to each neighbour's centre, where a square has two, which simplifies analysis across neighbours.
Part 6 · Ranking, borders, caching and failures
Ranking by distance and rating
Candidates inside the radius still have to be ordered. Sorting only by distance puts a poor place first because it is next door, and sorting only by rating ranks a place with two reviews above a loved one. A usual compromise is a score that blends how near a place is with how good it is.
A rating from two reviews says little, so the score first pulls a rating towards an assumed average. The adjusted rating is the rating times the number of reviews, plus the prior average times a prior weight, all divided by the reviews plus that weight. With few reviews it stays near the prior, and with many it stays near the rating. The score is 0.6 times the adjusted rating over 5, plus 0.4 times a nearness value that falls from 1 at the user to 0 at the radius. The weights are assumptions to tune against real behaviour.
R_M = 2000 # search radius in metres PRIOR, PRIOR_N = 3.8, 20 # assumed average rating, and its weight def adjusted(rating, reviews): """Pull a rating towards the prior when there are few reviews.""" return (rating * reviews + PRIOR * PRIOR_N) / (reviews + PRIOR_N) def score(rating, reviews, dist): near = 1 - dist / R_M # 1 at the user, 0 at the radius return 0.6 * adjusted(rating, reviews) / 5 + 0.4 * near # name, distance in metres, rating, number of reviews (all invented) places = [("Cafe A", 150, 4.2, 600), ("Cafe B", 300, 5.0, 2), ("Cafe C", 900, 4.8, 800), ("Cafe D", 120, 3.1, 400), ("Cafe E", 1800, 4.9, 500)] print("name dist rating reviews adjusted score") ranked = sorted(places, key=lambda p: -score(p[2], p[3], p[1])) for n, d, r, c in ranked: print(f"{n} {d:5d} {r:5.1f} {c:6d} {adjusted(r, c):7.2f} " f"{score(r, c, d):.3f}")
Python 3.12.10. Invented places with a distance, rating and review count.
name dist rating reviews adjusted score Cafe A 150 4.2 600 4.19 0.872 Cafe B 300 5.0 2 3.91 0.809 Cafe C 900 4.8 800 4.78 0.793 Cafe D 120 3.1 400 3.13 0.752 Cafe E 1800 4.9 500 4.86 0.623
Output, best first.
Cafe B has a perfect 5.0 from two reviews, and its adjusted rating is 3.91, so it ranks second and not first. Cafe C is 900 metres away with 800 reviews at 4.8, and it ranks third, above the nearer but poorly rated Cafe D. Cafe E has a 4.9 rating but is 1,800 metres away, so it comes last. The weights decide these outcomes, so a real service would measure them against clicks and visits.
The border problem
Cells have borders, and a user can stand beside one. A search that looks only at the user's own cell misses a place that is 30 metres away on the other side of the edge. The script puts a user 10 metres west of a cell's eastern edge and a cafe 20 metres east of it, builds a small index by cell and searches with and without the eight neighbours.
import math from geohash import encode, bounds, neighbours from geo import haversine_m # Put a user 10 m west of a cell edge and a cafe 20 m east of it. cell = encode(12.9716, 77.5946, 7) la0, la1, lo0, lo1 = bounds(cell) lat = (la0 + la1) / 2 m_per_deg_lon = 111_320 * math.cos(math.radians(lat)) user = (lat, lo1 - 10 / m_per_deg_lon) cafe = (lat, lo1 + 20 / m_per_deg_lon) print("distance between them (m):", round(haversine_m(*user, *cafe), 1)) index = {} # cell -> places in it index.setdefault(encode(*cafe, 7), []).append("Cafe Mango") mine = encode(*user, 7) print("user cell:", mine, " cafe cell:", encode(*cafe, 7)) print("own cell only:", index.get(mine, [])) found = [p for c in [mine, *neighbours(mine)] for p in index.get(c, [])] print("own cell and 8 neighbours:", found)
Python 3.12.10. Uses geohash.py and geo.py from earlier.
distance between them (m): 30.0 user cell: tdr1v9q cafe cell: tdr1v9r own cell only: [] own cell and 8 neighbours: ['Cafe Mango']
Output of the script.
The two points are 30 metres apart but sit in different cells, tdr1v9q and tdr1v9r. Searching the own cell returns nothing, and searching the cell plus its eight neighbours finds the cafe. The rule for a radius search is to cover the circle, not only the point: choose a cell side at least as big as the radius, so the circle touches at most nine cells, and read all of them.
The same logic applies to a quadtree, where the box walk already visits every square that touches the box, and to Redis, whose documentation says it checks the nine areas needed to cover the shape. A related trap is that two neighbouring cells can have codes with little in common, so a single prefix scan cannot replace the neighbour step.
Caching, scale and failures
Many searches repeat. People near the same station search the same cells for the same category. A cache keyed by the cell code, the category and the radius bucket can hold a result list for a short time, so the 5,800 peak searches a second hit the shards far less. Rounding the user's position to a cell is what makes the key shared, and the staleness it adds, a minute or so, is acceptable for places.
Failures are handled by replication and by degrading quality. When a shard replica fails, the ranker retries another replica of the same region. If a whole region is slow, the ranker can return results from the other shards after a deadline, and mark them partial. If the indexer falls behind, searches stay correct for old data, and its lag is a number to alert on. If the place store is down, searches still run from the index, and only the detail fetches fail; the ranker can answer with the fields the shards carry.
Trade-offs and extensions
The trade-offs here are: finer cells mean fewer candidates but more cells to read; caching raises speed and adds staleness; ranking weights are assumptions that real data must tune; and a text-index design is simple but gives up the equal-area cells of S2 or H3. Extensions follow naturally: filters such as open now, personalised ranking, and a map view that asks for all places inside the screen's box, which is the same index queried with a rectangle instead of a circle.
Why must a radius search look at neighbouring cells as well as the user's cell?
- A place just across a cell edge is near the user but in another cell. In the run a cafe 30 metres away was missed until the eight neighbours were read.
Why does the ranking script pull a rating towards a prior average?
- A rating from very few reviews is unreliable. In the run, a 5.0 from two reviews adjusted to 3.91 and ranked below a place with 4.2 from 600 reviews.
How can the service keep working when the place store is down?
- Searches run from the in-memory index, which carries the fields ranking needs. Only the detail pages that need the store fail.
| Term | Meaning |
|---|---|
| Geohash | A text code naming a cell; a longer code is a smaller cell inside the shorter one's cell |
| Quadtree | A tree that splits a square into four when it holds too many points |
| Capacity | The most points a quadtree leaf holds before it splits |
| Scatter-gather | Send a query to several shards, then merge the answers |
| Hot shard |
All chapters · Previous: Design a Maps and Navigation Service like Google Maps