Courses / System Design Interview / Chapter 28
Module 6 · Design Problems I: Video, Q&A and Location · Chapter 28 of 49
Design a Maps and Navigation Service like Google Maps
Builds on Back-of-the-Envelope Estimates, Content Delivery Networks and Distributed Message Queues. Next up: Design a Nearby Places Service like Yelp.
Part 1 · Requirements and estimates
What the service must do
A maps service shows a map of the world that you can pan and zoom, finds a route between two places, and tells you how long it will take given the traffic right now. This chapter designs those three things for cars, with the focus on how routes are computed and how live traffic feeds them.
The functional requirements are: show map tiles for any area at any zoom level; compute the fastest driving route between two points; estimate the travel time using current traffic; and guide a driver turn by turn, rerouting when they leave the route. Searching for a place by name, public transport, walking and street-level photos are out of scope.
The non-functional requirements are about speed and scale. Map tiles must appear within a few hundred milliseconds, so scrolling feels continuous. A route should come back in about a second, even across a country. Traffic must be fresh to within a few minutes. The service must keep working when one data centre is down, and a phone with a poor signal should still show a map it has already seen.
| Question to ask | Answer we assume |
|---|---|
| Which travel modes? | Driving only |
| How big is the road network? | A country: crores of road segments |
| How fresh is traffic? | Updated every few minutes |
| Do we store individual trips? | No, only aggregated speeds per road segment |
| Are maps available offline? | Out of scope |
The fourth row is a design stance, not a technical limit. Location trails are personal data, so the traffic system should turn pings into per-segment averages quickly and keep the individual points no longer than needed.
Estimating location pings
Maps are mostly read-only, and the map data changes slowly, so the interesting estimate is the stream that goes the other way: location pings from phones that are navigating. Each ping is a small message with an anonymous id, a position, a speed and a time. The traffic service turns those pings into the speed of each road segment.
The inputs are assumptions chosen for a large national service: fifty lakh phones navigating at the busiest hour, a ping every five seconds and about 60 bytes per ping.
# Inputs are assumptions for a national navigation service. navigating = 50_00_000 # phones navigating at the busiest hour ping_every_s = 5 # seconds between location pings ping_bytes = 60 # id, lat, lon, speed and time route_requests_per_trip = 2 # first route plus one reroute, on average trip_minutes = 30 pings_per_s = navigating / ping_every_s print(f"pings per second: {pings_per_s:,.0f}") mbps = pings_per_s * ping_bytes * 8 / 1e6 print(f"ingest bandwidth: {mbps:,.0f} Mbps") per_day = pings_per_s * 3600 * 10 # about ten busy hours a day print(f"pings per day (10 busy hours): {per_day:,.0f}") print(f"raw ping storage per day: {per_day * ping_bytes / 1e12:.1f} TB") trips_per_s = navigating / (trip_minutes * 60) print(f"route requests per second: " f"{trips_per_s * route_requests_per_trip:,.0f}")
Python 3.12.10. All inputs are assumptions.
pings per second: 1,000,000 ingest bandwidth: 480 Mbps pings per day (10 busy hours): 36,000,000,000 raw ping storage per day: 2.2 TB route requests per second: 5,556
Output of the estimate.
The service receives ten lakh pings a second, which is 480 Mbps of payload, and 3,600 crore pings in ten busy hours. Raw storage would be about 2.2 TB a day if every ping were kept. Route requests are far fewer: with trips of about thirty minutes and two requests per trip, one for the first route and one for a reroute, it is about 5,556 requests a second.
The imbalance is the main fact of the design: pings arrive a hundred and eighty times more often than route requests. Pings are small, but they are many, so the ingest path must be a stream-processing pipeline that aggregates early, and not a database that writes each one.
What the estimate decides
Raw ping bytes per day: ≈ 2.2 TB (before any aggregation)
Read it as steps
Fifty lakh phones pinging every five seconds is ten lakh writes a second.
The scene gives the arithmetic in the order a person would say it. It shows two things. First, the ingest rate of ten lakh messages a second is well beyond a single database, so pings go through a message queue and are aggregated in memory before anything is stored. Second, the bandwidth is modest, about 480 Mbps, so the work is in the number of messages and not their size.
The estimate also settles what is kept. A raw ping is useful for a few minutes, to compute the speed of the segment it is on. After that, the aggregate, one number per segment per five minutes, is enough, and it is far smaller, since each aggregate stands for many pings. Storing only aggregates is both cheaper and kinder to privacy.
Pings arrive about 180 times more often than route requests. What does that imply for the ingest path?
- It cannot be a database write per ping. Pings go through a queue and are aggregated in memory, and only the aggregates are stored.
Why is bandwidth not the main problem at 480 Mbps?
- The pings are tiny. The challenge is the message count, ten lakh a second, not the bytes.
Part 2 · API and data model: tiles, road graph and segments
Map tiles
A world map at street detail is far too large to send, so the map is cut into tiles, small square pictures or vector blocks, and the phone fetches only the ones in view. Each tile is named by three numbers: a zoom level z, and a column x and a row y. At zoom 0 one tile covers the world. Every zoom step splits each tile into four, so zoom z has 2^z columns and 2^z rows, which is 4^z tiles in all.
The common scheme, documented on the OpenStreetMap wiki as slippy map tilenames, uses the Web Mercator projection, a flat map of the globe that is a square between latitudes of about plus and minus 85.05 degrees. Its tiles are 256 by 256 pixels. Turning a latitude and longitude into a tile is a short formula, and the script below applies it to a point in Mumbai at several zoom levels.
import math def tile_for(lat, lon, zoom): n = 2 ** zoom x = int((lon + 180.0) / 360.0 * n) y = int((1.0 - math.asinh(math.tan(math.radians(lat))) / math.pi) / 2.0 * n) return x, y def tile_corner(x, y, zoom): """North-west corner (lat, lon) of a tile.""" n = 2 ** zoom lon = x / n * 360.0 - 180.0 lat = math.degrees(math.atan(math.sinh(math.pi * (1 - 2 * y / n)))) return lat, lon
Python 3.12.10. The two conversions between a point and a tile.
mumbai = (19.0760, 72.8777) print("zoom tiles in the world tile x/y for the point path") for z in (0, 4, 8, 12, 15, 17): x, y = tile_for(*mumbai, z) print(f"{z:>4} {4 ** z:>18,} {x:>6} {y:>6} /tiles/{z}/{x}/{y}") x, y = tile_for(*mumbai, 15) lat, lon = tile_corner(x, y, 15) lat2, lon2 = tile_corner(x + 1, y + 1, 15) print(f"zoom 15 tile spans lat {lat:.4f}..{lat2:.4f}," f" lon {lon:.4f}..{lon2:.4f}")
Print the tile for one point at six zoom levels.
zoom tiles in the world tile x/y for the point path 0 1 0 0 /tiles/0/0/0 4 256 11 7 /tiles/4/11/7 8 65,536 179 114 /tiles/8/179/114 12 16,777,216 2877 1826 /tiles/12/2877/1826 15 1,073,741,824 23017 14614 /tiles/15/23017/14614 17 17,179,869,184 92069 58458 /tiles/17/92069/58458 zoom 15 tile spans lat 19.0829..19.0725, lon 72.8723..72.8833
Output of the script.
At zoom 15 there are over a hundred crore tiles in the world, and the tile holding the point is 15/23017/14614. It spans about 0.011 degrees on each side, which is roughly 1.2 km, so each of its 256 pixels is about 4.5 metres.
The API
The tile request is the simplest call in the service, and the busiest. It is a plain GET of a URL that contains the three numbers, and the response never changes until the map data is rebuilt. That makes tiles ideal for a CDN, as in the cdn chapter: each tile is a static file with a long cache lifetime, and the origin is an object store.
| Call | What it does | Notes |
|---|---|---|
GET /tiles/{z}/{x}/{y} | Returns one map tile | Static, cached for days at the edge |
POST /routes | Takes an origin, a destination and a mode; returns the route, its distance and its ETA | A computed result, so not cached widely |
POST /pings | Takes a batch of anonymous location points | Write-only; the caller needs no answer |
GET /routes/{id}/eta | Returns the current estimate for a route being driven | Cheap, polled by the app |
Notice that pings travel in batches. The phone gathers a few points and sends them together, which saves battery and cuts the request rate, at the cost of a few seconds of delay. The trade-off comes from the numbers in the first lesson: ten lakh pings a second is easier to absorb when each request carries several.
A route response holds an ordered list of road segments, a polyline for drawing, a list of turns and an ETA. The routing service computes it, and a short-lived copy may be kept for the reroute check described in the last lesson.
The road graph
Routing works on a graph: a set of nodes, which are junctions and road ends, and edges, which are the road segments between them. A two-way road is stored as two directed edges, one per direction, so that one-way streets and different speeds in each direction fit the same table. Each segment has a length, a speed limit and a road class.
Live data is kept in a separate table keyed by segment and a five-minute window, because it changes constantly while the graph itself changes only when roads do. A query combines both: it uses the live speed when one exists and falls back to the speed limit.
import sqlite3 db = sqlite3.connect(":memory:") db.executescript(""" CREATE TABLE node (id INTEGER PRIMARY KEY, lat REAL NOT NULL, lon REAL NOT NULL); CREATE TABLE segment ( id INTEGER PRIMARY KEY, from_node INTEGER NOT NULL REFERENCES node(id), to_node INTEGER NOT NULL REFERENCES node(id), length_m REAL NOT NULL, limit_kmh INTEGER NOT NULL, road_class TEXT NOT NULL); -- one row per direction CREATE INDEX segment_out ON segment (from_node); CREATE TABLE segment_speed ( -- live data, one row per bucket segment_id INTEGER NOT NULL REFERENCES segment(id), bucket TEXT NOT NULL, -- start of a 5-minute window avg_kmh REAL NOT NULL, samples INTEGER NOT NULL, PRIMARY KEY (segment_id, bucket)); """)
Nodes, segments and live speeds.
db.executemany("INSERT INTO node VALUES (?,?,?)", [(1, 19.07, 72.87), (2, 19.08, 72.88), (3, 19.09, 72.88)]) db.executemany("INSERT INTO segment VALUES (?,?,?,?,?,?)", [(1, 1, 2, 1500, 40, "primary"), (2, 2, 3, 1100, 40, "primary"), (3, 2, 1, 1500, 40, "primary")]) db.execute("INSERT INTO segment_speed" " VALUES (1, '2026-11-22T09:00', 18.5, 42)") for row in db.execute(""" SELECT s.id, s.from_node, s.to_node, s.length_m, ROUND(s.length_m / 1000.0 / COALESCE(v.avg_kmh, s.limit_kmh) * 3600) AS seconds FROM segment s LEFT JOIN segment_speed v ON v.segment_id = s.id AND v.bucket = '2026-11-22T09:00' WHERE s.from_node = 2 OR s.id = 1 ORDER BY s.id"""): print(row)
Segment 1 has a live speed; the others use the limit.
(1, 1, 2, 1500.0, 292.0) (2, 2, 3, 1100.0, 99.0) (3, 2, 1, 1500.0, 135.0)
Output of the script: id, from, to, metres, seconds.
Segment 1 is 1,500 metres. At its limit of 40 km/h it would take 135 seconds, which is what segment 3, the same length without live data, shows. Segment 1 has a live average of 18.5 km/h and takes 292 seconds, more than twice as long. This is how a slow road changes the answer without any change to the map.
Part 3 · High-level design: tiles, routing and traffic
Three services and an offline pipeline
The system divides cleanly into three services, because their loads and data are so different. The tile service serves static map pictures. The routing service holds the road graph and answers route queries. The traffic service ingests pings and keeps the current speed of each segment. A fourth part, an offline pipeline, builds the tiles and the graph from map data and runs on a schedule, not on request.
The tile service is mostly a CDN. The pipeline renders every tile and writes it to an object store, and the CDN caches tiles at the edge. Because tiles are static, nearly every request ends at the edge, and the origin sees only the first request for each tile in each region. The pipeline runs when the map data changes, say weekly, and new tiles are published under new versions so that old and new never mix.
The routing service loads the road graph into memory, since a route query follows many edges and cannot wait on a disk. A country's graph is large, so it is divided by region, and a route that crosses regions combines answers from more than one. Several identical copies of each region serve the requests, behind a load balancer, which gives both capacity and availability.
How a request travels
Watch for tiles, routes and pings using three separate paths
Read it as steps
Tiles come from the CDN, routes from the routing service, and pings flow into the traffic service.
The scene shows that the three services share nothing on the request path. A map view never touches the routing service, and a ping never touches the tile store. This separation lets each be scaled and failed over on its own: the CDN grows with viewers, the routing service with route requests, and the traffic pipeline with the number of navigating phones.
The only coupling is that the routing service reads speeds from the traffic service. The coupling is one-way and tolerant of delay: if the traffic service is slow or down, routing falls back to the speed limits and the routes are still correct, only less accurate. Designing a dependency so that its failure degrades quality and does not stop service is worth doing wherever it is possible.
The traffic path in more detail
Pings reach the API gateway in batches and are appended to a message queue, partitioned by geographic region so that all pings for an area go to the same consumer. The consumers do three jobs. They map-match each ping, which is to snap a noisy GPS point to the road segment the phone is most likely on. They add the speed to a running window for that segment. And every few minutes they publish the segment's aggregate to the store that the routing service reads.
Map matching is a hard problem of its own, since GPS error of several metres can place a phone on a parallel road, and the course does not build it. The ETA lesson assumes it is done and starts from a speed per segment.
A few supporting parts complete the picture. A geocoder turns an address into a point, and it is outside our scope. A cache holds recently computed routes for the short time a reroute check might reuse them. And monitoring watches the age of the traffic data, because stale traffic is a silent failure: routes would still be returned but would be wrong.
Why is the routing graph held in memory?
- A route query touches many edges. Reading each from disk would be far too slow for a one second answer.
What happens to routing if the traffic service is down?
- It falls back to the speed limits. Routes are still valid but less accurate.
Why are pings partitioned by region in the queue?
- All pings for an area then reach one consumer, which can keep the speed windows for its segments in memory without coordination.
Part 4 · Deep dive: routing
Shortest paths with Dijkstra
Finding the fastest route is a shortest path problem on the road graph, where an edge's weight is the time to cross it. Dijkstra's algorithm solves it when every weight is positive. It keeps the best known distance to each node and a min-heap, a structure that always yields the smallest entry first. It repeatedly takes the node with the smallest distance, calls it settled because no cheaper route to it can exist, and tries to improve the distances of its neighbours.
Watch for T's distance dropping when a cheaper route appears
Read it as steps
Dijkstra settles the closest junction first and updates a distance when a cheaper route appears.
In the scene, B is settled before A because 2 is smaller than 4, and T first receives a distance of 11 through C. When D is settled at 9, the edge from D to T gives 9 plus 1, which is 10, so T's distance drops. The algorithm stops when the destination is settled, and the cheapest route is S, B, D, T for a cost of 10.
The algorithm is correct because it settles nodes in order of distance, and with positive weights a node settled later cannot lead to a cheaper route to one settled earlier. Its cost is what matters for maps: it explores outward from the origin in all directions, like a ripple, until it reaches the destination, so a long route settles a huge part of the graph.
Dijkstra and bidirectional search
Bidirectional search cuts that ripple down. It runs one search from the origin and one backward from the destination, alternating between them, and stops when the two meet and no better meeting point can exist. Two small ripples cover less area than one large one, since the area grows with the square of the radius. The code below has both: a grid of streets with random travel times, dijkstra and bidirectional, each returning the distance and the number of nodes it settled.
import heapq, random def grid(rows, cols, seed): """A rows x cols street grid; node id = r * cols + c; undirected.""" rnd = random.Random(seed) adj = {r * cols + c: {} for r in range(rows) for c in range(cols)} for r in range(rows): for c in range(cols): a = r * cols + c for dr, dc in ((0, 1), (1, 0)): if r + dr < rows and c + dc < cols: b = (r + dr) * cols + c + dc adj[a][b] = adj[b][a] = rnd.randint(1, 9) return adj def dijkstra(adj, s, t): """Returns (distance, number of nodes settled).""" dist, heap, done = {s: 0}, [(0, s)], set() while heap: d, u = heapq.heappop(heap) if u in done: continue done.add(u) if u == t: return d, len(done) for v, w in adj[u].items(): if d + w < dist.get(v, 1e18): dist[v] = d + w heapq.heappush(heap, (d + w, v)) return None, len(done)
Save the two blocks as routing.py. A street grid, and Dijkstra with a heap.
def bidirectional(adj, s, t): if s == t: return 0, 1 dist = ({s: 0}, {t: 0}) heap = ([(0, s)], [(0, t)]) done = (set(), set()) best = 1e18 side = 0 while heap[0] and heap[1]: if heap[0][0][0] + heap[1][0][0] >= best: break side = 0 if len(done[0]) <= len(done[1]) else 1 d, u = heapq.heappop(heap[side]) if u in done[side]: continue done[side].add(u) for v, w in adj[u].items(): nd = d + w if nd < dist[side].get(v, 1e18): dist[side][v] = nd heapq.heappush(heap[side], (nd, v)) if v in dist[1 - side]: best = min(best, nd + dist[1 - side][v]) return best, len(done[0]) + len(done[1])
Bidirectional search: stop when the sides cannot improve.
The next script builds a 30-node grid and a 1,600-node grid, and averages the nodes settled over 200 random pairs on each. It also checks that both methods return the same distance.
import random from routing import grid, dijkstra, bidirectional g = grid(5, 6, seed=11) # 30 nodes print("nodes:", len(g), "edges:", sum(len(v) for v in g.values()) // 2) print("corner to corner:", dijkstra(g, 0, 29), bidirectional(g, 0, 29)) rnd = random.Random(5) pairs = [(rnd.randrange(30), rnd.randrange(30)) for _ in range(200)] for name, f in (("dijkstra", dijkstra), ("bidirectional", bidirectional)): settled = [f(g, s, t)[1] for s, t in pairs] print(f"{name:<14} average settled on 30 nodes:" f" {sum(settled) / len(settled):.1f}") big = grid(40, 40, seed=11) # 1,600 nodes pairs = [(rnd.randrange(1600), rnd.randrange(1600)) for _ in range(200)] for name, f in (("dijkstra", dijkstra), ("bidirectional", bidirectional)): res = [f(big, s, t) for s, t in pairs] print(f"{name:<14} average settled on 1,600 nodes:" f" {sum(r[1] for r in res) / len(res):.1f}") same = all(dijkstra(big, s, t)[0] == bidirectional(big, s, t)[0] for s, t in pairs) print("same distances on all 200 pairs:", same)
Seeded random pairs, so the output repeats.
Shortcuts: contraction hierarchies
On the 30-node grid, corner to corner took Dijkstra 24 settled nodes and the bidirectional search 17. On average, Dijkstra settled 15.8 nodes and the bidirectional search 10.1. On the 1,600-node grid they settled 777.1 and 496.9, about a third fewer. That is a real gain, but the cost still grows with the distance. A national road network has crores of nodes, and a route across it would still settle a huge number.
The remedy is to do work in advance. Contraction hierarchies, described in Robert Geisberger's 2008 thesis from Karlsruhe, order the nodes by importance and contract them one at a time, least important first. Removing a node could lengthen some shortest paths, so for each pair of its neighbours the process adds a shortcut edge whose weight is the distance through the removed node, but only when no other path is as short. A small search from one neighbour that is not allowed to pass through the removed node, called a witness search, finds out whether such a path exists. After all nodes are contracted, a query searches upward only, from both ends, towards more important nodes, and the two searches meet near the top of the hierarchy.
import heapq def witness(adj, s, skip, limit): """Distances from s, never passing through `skip`, up to `limit`.""" dist, heap = {s: 0}, [(0, s)] while heap: d, u = heapq.heappop(heap) if d > dist[u] or d > limit: continue for v, w in adj[u].items(): if v != skip and d + w < dist.get(v, 1e18): dist[v] = d + w heapq.heappush(heap, (d + w, v)) return dist def shortcuts_needed(adj, v): out = [] nb = list(adj[v].items()) for i, (u, wu) in enumerate(nb): for x, wx in nb[i + 1:]: via = wu + wx if witness(adj, u, v, via).get(x, 1e18) > via: out.append((u, x, via)) return out
Save the next three blocks together as ch.py. A witness search, then the shortcuts needed when node v is removed.
def contract(adj): """Returns (up graph, rank, number of shortcuts added).""" adj = {u: dict(n) for u, n in adj.items()} heap = [(len(shortcuts_needed(adj, v)) - len(adj[v]), v) for v in adj] heapq.heapify(heap) up, rank, added = {}, {}, 0 while heap: p, v = heapq.heappop(heap) now = len(shortcuts_needed(adj, v)) - len(adj[v]) if heap and now > heap[0][0]: heapq.heappush(heap, (now, v)) # priority grew: retry continue rank[v] = len(rank) up[v] = dict(adj[v]) # all still-uncontracted for u, x, w in shortcuts_needed(adj, v): if w < adj[u].get(x, 1e18): adj[u][x] = adj[x][u] = w added += 1 for u in adj[v]: del adj[u][v] del adj[v] return up, rank, added
Contract nodes in order of how few shortcuts they cost.
Querying a hierarchy
The contract function records, for each node, the edges it had to nodes not yet contracted, which are the more important ones. A query then runs an ordinary Dijkstra search from each end that follows only those upward edges. The two searches reach a common node near the top, and the best sum of the two distances over all common nodes is the answer.
def ch_query(up, s, t): """Upward-only searches from both ends: (distance, settled).""" dists, settled = [], 0 for src in (s, t): dist, heap = {src: 0}, [(0, src)] done = set() while heap: d, u = heapq.heappop(heap) if u in done: continue done.add(u) for v, w in up[u].items(): if d + w < dist.get(v, 1e18): dist[v] = d + w heapq.heappush(heap, (d + w, v)) dists.append(dist) settled += len(done) meet = set(dists[0]) & set(dists[1]) return min(dists[0][m] + dists[1][m] for m in meet), settled
A query searches upward from both ends and meets.
import random, time from routing import grid, dijkstra from ch import contract, ch_query g = grid(40, 40, seed=11) t0 = time.perf_counter() up, rank, added = contract(g) prep = time.perf_counter() - t0 edges = sum(len(v) for v in g.values()) // 2 print(f"nodes {len(g)}, edges {edges}, shortcuts added {added}" f" (prep {prep:.1f}s on this machine)") rnd = random.Random(5) pairs = [(rnd.randrange(1600), rnd.randrange(1600)) for _ in range(200)] ok = all(ch_query(up, s, t)[0] == dijkstra(g, s, t)[0] for s, t in pairs) print("same distances as Dijkstra on 200 pairs:", ok) a = sum(dijkstra(g, s, t)[1] for s, t in pairs) / 200 b = sum(ch_query(up, s, t)[1] for s, t in pairs) / 200 print(f"average settled: dijkstra {a:.1f}, hierarchy {b:.1f}")
Check against Dijkstra on 200 pairs.
nodes 1600, edges 3120, shortcuts added 3617 (prep 1.1s on this machine) same distances as Dijkstra on 200 pairs: True average settled: dijkstra 804.1, hierarchy 257.1
The preparation time is on this machine and varies.
Preparation added 3,617 shortcuts to a graph of 3,120 edges and took about a second. Queries then settled 257.1 nodes on average against 804.1 for plain Dijkstra, and every answer matched. The 200 pairs differ from the earlier script's, so Dijkstra's average is 804.1 here and not 777.1. A street grid has no highways to climb, so the gain here is smaller than a real road network would give, and this course does not measure one. The OSRM routing engine offers two algorithms, contraction hierarchies and multi-level Dijkstra, and its README recommends the second by default, keeping the first for special cases such as very large distance matrices.
Part 5 · Deep dive: ETAs from live traffic
From pings to segment speeds
An ETA, estimated time of arrival, is the sum of the times to cross each road segment on the route. For one segment the time is its length divided by its current speed, so everything depends on knowing that speed. The traffic service estimates it from the pings of phones that were on the segment during the last few minutes.
Averaging the speeds looks natural, but it has two weaknesses. Phones that are parked beside the road, or stuck at a junction, report a speed of zero and drag the mean down, so a sturdier summary is better. The median, the middle value of the sorted speeds, ignores a few extreme points. And a quiet street may have only one or two pings in a window, too few to trust, so the service needs a rule for too few samples: fall back to the speed limit, or to the typical speed for that hour.
The script below makes four segments of a route. Three have forty pings drawn around the true current speed, with a few zero readings added to the first. The fourth, a quiet street, has only three. It prints the median, the plain mean and the speed used, then adds up the time along the route.
import random, statistics from collections import defaultdict rnd = random.Random(21) # name: (length in metres, limit in km/h, true current speed km/h) SEGMENTS = {"s1": (1500, 40, 38), "s2": (1100, 40, 12), "s3": (2000, 60, 55), "s4": (800, 30, 30)} MIN_SAMPLES = 5 pings = defaultdict(list) # segment -> speeds seen in the window for seg, (_, _, true) in SEGMENTS.items(): n = 40 if seg != "s4" else 3 # s4 is a quiet street pings[seg] += [max(1, rnd.gauss(true, 4)) for _ in range(n)] pings["s1"] += [0.0] * 3 # parked phones report 0 km/h
Invented segments and noisy pings, seeded.
def speed_for(seg): p = pings[seg] if len(p) < MIN_SAMPLES: return SEGMENTS[seg][1], "limit" # too few: fall back return statistics.median(p), f"median of {len(p)}" def eta(path): total = 0.0 for seg in path: kmh, _ = speed_for(seg) total += SEGMENTS[seg][0] / 1000 / kmh * 3600 return total for seg in SEGMENTS: kmh, how = speed_for(seg) mean = statistics.mean(pings[seg]) print(f"{seg}: {kmh:5.1f} km/h ({how}); plain mean {mean:5.1f}") path = ["s1", "s2", "s3", "s4"] free = sum(SEGMENTS[s][0] / 1000 / SEGMENTS[s][1] * 3600 for s in path) live = eta(path) print(f"free-flow {free / 60:.1f} min, live ETA {live / 60:.1f} min")
Median speed, a fallback, and the ETA along the route.
Reading the result
s1: 38.4 km/h (median of 43); plain mean 36.3 s2: 12.0 km/h (median of 40); plain mean 11.5 s3: 55.6 km/h (median of 40); plain mean 55.4 s4: 30.0 km/h (limit); plain mean 30.6 free-flow 7.5 min, live ETA 11.6 min
Python 3.12.10. Seeded, so the numbers repeat.
Segment s1 has 43 pings, three of which are zeros. The median is 38.4 km/h and the plain mean 36.3, so the zeros pulled the mean down by about two km/h. Segment s2 is the congested one, at a median of 12.0 against a limit of 40. Segment s4 had only three pings, so the service used its limit of 30 km/h. The route that takes 7.5 minutes at the speed limits takes 11.6 minutes with the live speeds, and that difference is what the driver is told.
Real systems add more. They keep historical profiles, the typical speed of a segment at each hour of each weekday, to fill gaps and to predict conditions ahead, since a route that starts now will reach its later segments minutes or hours from now. An accurate ETA uses the traffic expected when the driver arrives at each segment, not the traffic right now. And they report uncertainty, so that a long trip can be shown as a range.
Other effects are real but left out here: the time spent waiting at traffic lights and turning across traffic, which is added per turn, and temporary events such as an accident or a closure, which come from a separate feed and override the speeds.
Feeding speeds into routing
Routing uses the speeds as edge weights, so the weight of a segment is its time and not its length. A graph that serves live traffic therefore changes every few minutes, and that interacts with the previous lesson. Shortcuts in a contraction hierarchy are sums of the weights of the edges they replace, so when the weights change the shortcuts are out of date. A service has two choices: rebuild the hierarchy, which is expensive, or use a method whose preparation separates the shape of the graph from the weights, so that only a small part must be redone when the weights change. This course does not build the second approach.
One compromise is to mix two kinds of data. The big, slow structure is prepared on the free-flow times, and the live speeds adjust the weights only along the candidate routes that come out of the search. The result is a good route found quickly, plus an ETA computed from live speeds.
Freshness needs watching. Each segment's aggregate carries a timestamp and a sample count, and the service should treat an aggregate older than a few windows as missing. Without that rule, a road that loses its pings, because a sensor outage hides it, would keep showing the last speed it had, even if that was the speed of a jam that cleared an hour ago.
Why use the median of the pings and not the mean?
- A few parked phones reporting zero pull the mean down. The median ignores extreme values. In the run it was 38.4 km/h against a mean of 36.3.
What should the service do for a segment with only three pings in the window?
- Fall back to the speed limit or the historical speed for that hour. Three points are too few to trust.
Why is an ETA based only on current traffic often wrong for a long trip?
- The driver reaches later segments later, under traffic that will have changed. Historical profiles help predict it.
Part 6 · Rerouting, region partitioning and failures
Noticing that a driver left the route
During navigation the phone compares each position with the route it was given. A driver who misses a turn drifts away from the planned segments, and a new route is needed from the current position. The decision must be careful in both directions: too eager and every GPS wobble triggers a reroute, too slow and the app keeps saying turn around along a road the driver has chosen.
A simple rule works well. Measure the distance to the route, the shortest distance from the phone to any segment of the polyline. If it exceeds a threshold, say 50 metres, for three pings in a row, ask for a new route. The script converts degrees to metres with a flat-earth approximation that is good over short distances, and computes the distance from a point to each line segment.
from math import cos, hypot, radians M_PER_DEG = 111_320 # metres per degree of latitude, approx. def to_xy(lat, lon, lat0): return (lon * M_PER_DEG * cos(radians(lat0)), lat * M_PER_DEG) def dist_to_segment(p, a, b): ax, ay, bx, by, px, py = *a, *b, *p dx, dy = bx - ax, by - ay t = 0 if dx == dy == 0 else max(0, min(1, ((px - ax) * dx + (py - ay) * dy) / (dx * dx + dy * dy))) return hypot(px - (ax + t * dx), py - (ay + t * dy)) route = [(19.0700, 72.8700), (19.0700, 72.8800), (19.0800, 72.8800)] xy = [to_xy(la, lo, 19.07) for la, lo in route] def off_route_m(lat, lon): p = to_xy(lat, lon, 19.07) return min(dist_to_segment(p, xy[i], xy[i + 1]) for i in range(len(xy) - 1))
Distance from a point to a polyline, in metres.
PINGS = [(19.0701, 72.8720), (19.0699, 72.8750), (19.0690, 72.8790), (19.0680, 72.8805), (19.0672, 72.8815), (19.0665, 72.8830)] strikes = 0 for lat, lon in PINGS: d = off_route_m(lat, lon) strikes = strikes + 1 if d > 50 else 0 action = "REROUTE" if strikes >= 3 else "" print(f"({lat}, {lon}) {d:6.1f} m off route {action}")
Three strikes at more than 50 m trigger a reroute.
(19.0701, 72.872) 11.1 m off route (19.0699, 72.875) 11.1 m off route (19.069, 72.879) 111.3 m off route (19.068, 72.8805) 228.8 m off route (19.0672, 72.8815) 349.4 m off route REROUTE (19.0665, 72.883) 501.4 m off route REROUTE
Python 3.12.10. Invented route and pings.
The first two pings are 11.1 metres from the route, which is ordinary GPS error. The third is 111.3 metres away, and the fourth 228.8, and at the fifth, 349.4 metres off, the third strike fires and the app asks for a new route. A single bad point does not reroute, which is why the counter resets to zero when a ping is back on the route.
Partitioning by region
A national graph in one process is both a memory problem and an availability problem. The usual answer is to partition by region: cut the map into areas, each served by its own group of routing servers holding that area's graph. A request inside one region is answered by one group. A route between regions is trickier, since the best path may cross a border several times.
The standard approach is to mark the border nodes, the junctions where roads cross from one region to another, and precompute the distances between the border nodes of each region. A cross-region query then has three parts: from the origin to the borders of its region, across the precomputed border-to-border distances, and from the borders of the destination region to the destination. Each part runs on one group, and a coordinator combines them. This course describes the method and does not build it.
The tile service is partitioned too, but for free: a tile's name z/x/y already says which tile it is, and the object store spreads tiles across its machines. Pings are partitioned by region in the queue, as in the design lesson, so each traffic consumer owns the speeds of its area.
The cost of partitioning is the border. Routes near a boundary may be slightly worse if the border nodes are chosen badly, and the code that combines regions is complex. The benefit is that a failure takes out one region, not the whole service.
Failures and trade-offs
| Failure | What the user sees | Response |
|---|---|---|
| A routing server dies | Some requests fail | The load balancer sends them to another copy of that region |
| A whole region is down | No routes there | Serve a cached route if one exists; fail clearly otherwise |
| The traffic service lags | ETAs are too optimistic | Treat old aggregates as missing and fall back to limits |
| Bad GPS in a tunnel | The blue dot freezes | Dead-reckon from the last speed and heading for a short time |
| A new tile build is faulty | Wrong roads on the map | Tiles are versioned, so point the CDN back to the previous version |
| A road closes | Routes pass through it | A closure feed overrides speeds and removes the edge |
Three trade-offs run through the whole design. Precomputed structures, tiles and hierarchies, make queries fast and updates slow. Live data makes answers accurate and the system more complex. And aggregating early saves storage and protects privacy, at the cost of not being able to ask new questions of the raw points later.
Several extensions use the same parts. Alternative routes come from penalising edges used by the best route and searching again. Avoiding tolls is a filter on edge attributes. Traffic prediction adds a model on the historical profiles. Each extension changes one part and leaves the others as they are, which is what the three-service split was for.