Course contents

17. Real-World System Design Lesson 14 of 20

Maps and Location Platform

Design a maps platform end to end: tiles through a CDN, routing on precomputed hierarchies, a live traffic stream, ETAs, and what fails.

25 minAdvanced11 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Tiles are shared, immutable and skewed: pre-render them and serve them through a CDN.
  • A cache holding a small fraction of tiles answers most requests and keeps serving hits when the origin is down.
  • Contraction hierarchies move routing work offline: shortcut edges plus an upward bidirectional search answer in milliseconds.
  • GPS probes are a write-heavy stream: a topic fans them out to map matching (live speeds) and an archive (history).
  • ETAs combine live speeds where fresh with historical profiles where not; a pipeline outage shows up as stale data, not errors.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A maps and location platform answers three kinds of question: what does this area look like (map tiles), how do I get from A to B (routing), and when will I arrive (ETA from live and historical traffic). Each has a different load profile, so a good design treats them as separate subsystems that share data: a read-heavy static content system, a CPU-heavy query engine and a write-heavy telemetry stream.

Why it exists

Doing any of the three naively fails at scale. Rendering tiles on demand from one region overloads the renderer and adds a cross-continent round trip to every pan. Running Dijkstra per route on a continental graph costs seconds of CPU. Ignoring live traffic gives the shortest route, not the fastest. The case study is about deciding, for each subsystem, what to compute ahead of time and what to compute per request.

How it works

Requirements and estimates. Functional: show a pannable, zoomable map; compute routes for driving (and walking, cycling, transit); show ETAs with live traffic; ingest location updates from navigating devices. Non-functional: tiles fast everywhere (well under 100 ms at the edge), routes in a fraction of a second, ETAs that reflect current conditions within minutes, high availability for viewing even when other parts fail. An illustrative estimate: 50 M daily users × 20 map views × 20 tiles ≈ 20 billion tile requests per day, about 230 k/s on average and several times that at peak; probes from navigating devices every few seconds add billions of small writes per day. These numbers are illustrative, not measurements of any product.

Tiles. The world is cut into a quadtree of tiles addressed as z/x/y: zoom level z has 4^z tiles. Modern clients mostly use vector tiles (geometry plus attributes, styled on the device), which are smaller than raster images and let the client restyle without new downloads. Tiles are generated in a batch pipeline from the map database, written to object storage under versioned paths, and served through a CDN. Demand is extremely skewed (city centres, common zoom levels), so an edge cache holding a small fraction of tiles answers most requests; in the lesson’s simulation, an LRU of 10% of tiles answers about 70%. Low zoom levels are few and hot; high zoom levels over oceans and deserts are many and cold, and can be generated lazily or stored as a shared "empty" tile.

Routing. The road network is a weighted directed graph (intersections as nodes, road segments as edges, travel time as weight). Dijkstra’s algorithm explores outward until it reaches the destination; on a continent that settles millions of nodes. Contraction hierarchies (CH) precompute an ordering of nodes by importance and add shortcut edges so that contracting unimportant nodes preserves shortest-path distances. A query runs a bidirectional search in which each side only relaxes edges towards more important nodes; the searches meet near the top of the hierarchy after settling hundreds to a few thousand nodes. Customizable route planning (CRP) and customizable CH split preprocessing into a slow, metric-independent phase (graph partitioning or node ordering) and a fast customization phase that applies new edge weights, which is what makes live traffic practical. Open-source engines such as OSRM, Valhalla and GraphHopper implement variants of these ideas.

Live traffic. Navigating devices send GPS probes (position, time, heading, speed). They land on a durable stream (a log or topic) partitioned by region or road segment. Map matching snaps noisy points to the most likely road segments (typically with a hidden Markov model over candidate segments) and aggregates per-segment speeds over short windows into a live speed store. A second consumer archives every probe to build historical speed profiles (per segment, weekday and time of day) and to train ETA models. Location data is personal: aggregate early, drop identifiers, and keep raw traces only as long as needed.

ETA. The arrival time is the sum of segment travel times along the route, plus turn and intersection costs. Segments with fresh live data use it; others use the historical profile. Production systems add a learned correction for effects the sum misses (traffic lights, turns, how conditions will evolve during a long trip).

When to use it

This decomposition fits any product built on geography: navigation, delivery and logistics, ride-hailing dispatch (which also needs a geospatial index of moving vehicles), real-estate and travel maps. The tile part alone fits any large static, hierarchical image or geometry set (satellite imagery, game worlds, very large documents).

When not to

  • Small, regional or internal maps: a hosted map provider or a single tile server with a CDN is enough; building routing and traffic is not justified.
  • If you only need distance estimates (e.g. "within 5 km"), straight-line or cached travel-time matrices may do without a routing engine.
  • Highly dynamic graphs where edge weights change every second for most edges make pure CH preprocessing a poor fit; use customizable approaches or accept slower queries.

Trade-offs

Choice You gain You pay
Pre-rendered tiles behind a CDN Low latency everywhere, origin protected, survives origin outages for hot tiles Batch pipeline, storage for every zoom level, re-generation when map data changes
Vector instead of raster tiles Fewer bytes, client-side styling, crisp rotation and zoom Client rendering cost, more complex clients
Contraction hierarchies Millisecond queries on continental graphs Hours of preprocessing; live weights need a customizable variant
Stream pipeline for probes Ingestion decoupled from processing, fan-out to many uses Lag and stale data under failure; at-least-once processing needs idempotence
Live speeds with historical fallback ETAs reflect current traffic Freshness thresholds to tune; sparse roads rely on history

Alternatives

  • On-demand tile rendering with a render cache: less storage, more CPU and cold-start latency; reasonable for rarely viewed zoom levels.
  • A* with a good heuristic, or ALT (landmarks): faster than Dijkstra with lighter preprocessing, but much slower than CH on long routes.
  • Precomputed distance matrices for a fixed set of points (warehouses, stores): instant lookups, useless for arbitrary origins.
  • Batch traffic (hourly aggregates only): far simpler, but blind to incidents.

Failure modes

  • Origin outage: cache hits keep working; misses fail. Long TTLs on versioned URLs and stale-if-error turn most of the remaining errors into slightly old tiles.
  • Cache cold start or purge: purging all tiles after a style change sends the full request rate to the origin. Version URLs and roll out gradually instead of purging.
  • Routing preprocessing fails or lags: keep serving the previous graph version; a new road missing for a day is better than no routing.
  • Traffic pipeline lag: consumers fall behind and live speeds go stale; ETAs silently degrade to history. Alert on consumer lag and data age, size consumers for catch-up, and skip probes too old to matter.
  • Bad probe data: GPS drift, tunnels and parked phones create phantom jams. Filter and require a minimum number of distinct probes before trusting a live speed.

In production

Tiles are served from object storage through multiple CDN layers (edge and regional shield), with cache keys including the data version. Routing servers hold the preprocessed graph for a region in memory and are replicated behind load balancers; cross-region trips use overlay graphs or partition-aware algorithms. The probe stream is partitioned so that one segment’s probes land on one consumer, which keeps aggregation local. Dashboards track tile hit ratio and origin load, route latency per region, consumer lag and the age of live speed data, because a stale traffic layer produces no errors at all.

Common misconceptions

  • "Routing is just Dijkstra." Correct, but far too slow per request at continental scale; production engines rely on preprocessing.
  • "A CDN only helps latency." It also caps origin load and keeps serving hot content when the origin fails.
  • "No traffic data means no traffic." It means unknown; fall back to historical profiles.
  • "A stream pipeline outage causes errors." Usually it causes stale data, which is quieter and must be monitored explicitly.

Interview angle

Start with requirements and a tile estimate, then split the system into tiles, routing and traffic. Interviewers look for: the quadtree tile scheme and why a CDN fits; that you know plain Dijkstra does not scale and can name a preprocessing technique (CH, CRP, A* with landmarks) and its cost; how live traffic gets from phones to edge weights (stream, map matching, aggregation); how ETAs fall back when data is missing; and how each part degrades under failure. Mention privacy of location data unprompted.

Model assumptions

Simulated parts are a simplified model, not a benchmark. Tiles: 10,000 distinct tiles requested with Zipf(1) popularity and Poisson arrivals; the tile store has 16 connections and a 40 ms mean read (lognormal, cv 0.4, about 400 reads/s); the CDN edge is a server with a 1,000-tile LRU cache that fills on misses; network hops are fixed (viewer → origin region 50 ms, viewer → edge 10 ms, edge → origin 40 ms). Routing: the route service has 8 workers; a plain Dijkstra search is modelled as 1.5 s of work per route and a hierarchy query as 8 ms, both illustrative. Traffic: probes arrive at 200/s on a topic that copies each one to a map-matching and an archive subscription; map matching has 4 slots at 15 ms per probe (12 slots after scale-out), the archiver 4 slots at 5 ms; unacknowledged messages are redelivered. The contraction-hierarchy query and the ETA lookup are scripted illustrations (packets only, not simulated). Utilisation is the fraction of busy workers or connections, not CPU; all numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. What a maps platform must do

    Three jobs, with very different shapes. Show the map: a phone screen needs a dozen or two 256 px (or 512 px vector) tiles per view, and every pan or zoom asks for more. Find a route between two points on a road graph with hundreds of millions of edges. Predict the arrival time from live traffic, which phones themselves report.

    Illustrative estimate: 50 M daily users × 20 map views × 20 tiles ≈ 20 billion tile requests a day, about 230 k/s on average and several times that at peak. Tiles are read-only and identical for everyone, which decides most of the design. This scene runs the tile path in the simulation at a scaled-down 250 req/s: viewers in another region call one tile server, which reads tiles from the store. The store is about 60% busy.

    Scene: Map viewers request tiles from a single tile server 50 ms away, which reads them from the tile store. At 250 requests per second the store is about 60% busy and nothing fails.

    Key idea: Split the problem by access pattern: read-heavy static tiles, CPU-heavy routing, write-heavy traffic telemetry.

  2. 2. Evening peak: the tile store gives out

    Traffic rises to 600 tile requests per second. The store can read about 400 per second; its connections are all busy and queries queue for them. The tile server’s workers sit waiting on those reads, its own queue fills, and it rejects about a third of requests (503). Median latency climbs past 700 ms.

    Every viewer is also paying a 50 ms network trip each way to the one region the server lives in, for data that never changes. Both problems have the same fix.

    Scene: Tile traffic rises to 600 requests per second. The tile store is saturated, the tile server backs up and rejects about a third of requests, and median latency climbs above 700 ms.

    Key idea: Serving identical, immutable data from one origin wastes both origin capacity and network distance.

  3. 3. Pre-rendered tiles behind a CDN

    Tiles are pre-rendered into object storage and served through a CDN. Viewers now reach an edge 10 ms away. The edge keeps the 1,000 most recently used tiles (10% of them) and only fetches a miss from the origin store, then caches it.

    Tile popularity is extremely skewed: city centres at common zoom levels are requested constantly, open ocean almost never. With this Zipf-shaped demand the small edge cache answers roughly 70% of requests in the simulation, so the store sees only the misses, about a third of the traffic, and runs at under half its capacity with no queueing. Median latency falls from over 100 ms to a few tens of milliseconds.

    Scene: Viewers call a CDN edge 10 ms away. The edge cache answers about 70% of tile requests; misses are fetched from the tile store 40 ms away and cached. The store is under half busy and nothing fails.

    Key idea: Immutable, skewed, shared data is the ideal CDN workload: a cache holding a small fraction of tiles absorbs most requests.

  4. 4. The tile store goes down

    One second in, the tile store fails. Every cache miss now fails, but cache hits never touch the origin, so the edge keeps serving the popular tiles. The error rate jumps to about the miss ratio (roughly 30%), not to 100%: users see the map, with gaps where rarer tiles should be.

    Production CDNs push this further with long TTLs on versioned tile URLs and *stale-if-error*: an expired copy is served rather than an error while the origin is unreachable.

    Scene: The tile store goes offline. Requests for cached tiles still succeed at the edge; only cache misses fail, so about 30% of tile requests fail instead of all of them.

    Key idea: A cache in front of the origin is also a failure buffer: hits survive an origin outage.

  5. 5. Routing: a plain shortest-path search is too slow

    The store is back. Next: routes. A routing service answers *“fastest way from A to B”* on a road graph. A plain Dijkstra search explores every road closer than the destination; across a continent that is millions of nodes and, in this illustration, about 1.5 seconds of CPU per route.

    Eight workers then manage about 5 routes per second, and we are asking for 10. The queue fills and route requests are rejected. More machines would help linearly, but the work per query is the real problem.

    Scene: Route requests arrive at 10 per second at a routing service that spends about 1.5 seconds per route. It is saturated and rejects many route requests; tiles keep working.

    Key idea: Shortest-path search on a continental graph is too expensive to run from scratch per request.

  6. 6. Precompute a hierarchy, query it in milliseconds

    Road networks have structure: long trips use motorways. Contraction hierarchies (and relatives such as customizable route planning) exploit it. Offline, a preprocessing job ranks nodes by importance and adds shortcut edges that skip over the unimportant ones. At query time the search runs from both ends at once, only upward in the ranking, and meets in the middle after settling a few hundred to a few thousand nodes instead of millions.

    The packets here are a scripted illustration of one query: two small searches against the precomputed graph. In the simulation the work per route drops to 8 ms; the routing service is now nearly idle and route latency is about 50 ms, mostly network.

    Scene: An offline preprocessing job writes shortcut edges into the road graph. A route query searches upward from both ends of the trip and meets in the middle. Each route now takes about 8 ms of work and no route request fails.

    Key idea: Move work from query time to preprocessing time: hours of offline work buy millisecond queries.

  7. 7. Phones report traffic: a write-heavy stream

    Fastest is not shortest: you need current speeds. Phones with navigation open send GPS probes every few seconds, here 200 per second (billions a day in production). They go into a probe stream, a topic with two subscriptions.

    Map matching snaps each noisy GPS point onto a road segment and updates that segment’s live speed. The archive keeps every probe for historical speed profiles and model training. Each probe becomes two messages; both consumers keep up, so the queues stay near empty.

    Scene: GPS probes arrive at 200 per second on a probe stream topic. Each probe is copied to a map-matching subscription and an archive subscription; both workers keep up and the queues stay near empty.

    Key idea: Traffic data is an append-only stream: decouple ingestion from processing with a log or topic, and fan out to each use.

  8. 8. ETA: live speeds where fresh, history where not

    An arrival time is the sum of the travel times of the route’s segments. The ETA service reads live speeds for segments with recent probes and falls back to historical speed profiles (this segment, this weekday, this time of day) where live data is missing or stale. Production systems add a learned correction on top, for turns, traffic lights and how traffic will change during the trip.

    This lookup is a scripted illustration: the route service asks the ETA service, which reads live speeds first and history second, then answers.

    Scene: The routing service asks the ETA service for an arrival time. The ETA service reads live speeds, then historical speed profiles, and answers.

    Key idea: ETA quality depends on data freshness; always have a historical fallback for segments without live data.

  9. 9. Map matching stops: traffic goes stale

    One second in, the map-matching workers crash. Nothing upstream notices: phones keep publishing, the topic keeps accepting, and the archive keeps up. But the matching subscription grows by about 200 messages per second and live speeds stop updating.

    Routes and tiles keep working; that is the payoff of decoupling. The cost is quality: as live speeds age past the freshness limit, the ETA service falls back to history, and a traffic jam that formed after the crash is invisible.

    Scene: The map-matching worker crashes. Probes keep arriving and the archive keeps up, but the matching subscription backlog grows steadily. Tile and route requests are unaffected.

    Key idea: A buffered pipeline turns a consumer outage into growing lag and stale data instead of errors.

  10. 10. Recover, scale out, drain the backlog

    The workers restart half a second in and are scaled to three times the consumers. They now process about 800 probes per second against 200 arriving, so the backlog of about 900 messages drains within a couple of seconds and live speeds become fresh again.

    Two design choices make this safe. Old probes are worth little: a real pipeline may skip probes older than a few minutes rather than replay them in order. And matching should be idempotent per probe, because at-least-once delivery redelivers the messages that were in progress during the crash.

    Scene: Map matching recovers with three times as many consumers and drains the backlog in a few seconds; the matching subscription returns to near empty.

    Key idea: Size consumers for catch-up, not just steady state: recovery needs spare throughput above the arrival rate.

  11. 11. The design and its trade-offs

    Three subsystems, three strategies. Tiles: precompute and cache everywhere; the cost is storage, re-rendering when map data changes, and cache invalidation (versioned URLs make it a non-problem). Routing: precompute a hierarchy; the cost is preprocessing time and the difficulty of applying live traffic, which is why customizable variants separate the graph structure from the edge weights. Traffic: stream processing; the cost is lag under failure and the need to reason about freshness.

    Other decisions in an interview: partition the routing graph by region (cross-region trips need care), keep tiles vector rather than raster to cut bytes and allow client styling, and treat location data as sensitive: aggregate probes and drop identifiers early.

    Scene: The full design: tiles through a CDN edge cache, routing on a precomputed hierarchy, and a live traffic stream feeding live speeds and history for ETAs. All components are healthy.

    Key idea: Maps are a precomputation story: decide what to compute ahead of time, what live, and what to do when live data is missing.