Skip to content

Design Maps and Navigation (Google Maps)

Advanced 40 min read Part 17 of 18

Design Google Maps: tiles on a CDN, road-graph routing with Dijkstra, A* and contraction hierarchies, live traffic and ETA, geocoding and offline maps.

The Problem#

A maps and navigation product such as Google Maps, Apple Maps, Waze, HERE WeGo, or one built on OpenStreetMap data does several very different jobs behind one screen:

  1. Shows the map. It draws streets, buildings, labels and terrain for any part of the world at any zoom level, and pans and zooms smoothly on a phone.
  2. Finds places. It turns "1600 Amphitheatre Parkway" or "coffee near me" into coordinates (geocoding), and turns a tapped point back into an address (reverse geocoding).
  3. Plans routes. It finds the fastest way from A to B over a road network with hundreds of millions of segments, in milliseconds, considering one-way streets, turn restrictions and current traffic.
  4. Predicts arrival time. It estimates how long the trip will take, using live traffic derived from millions of phones reporting their speed, plus historical patterns.
  5. Navigates. It guides the driver turn by turn, detects when they leave the route, re-routes, and updates the ETA as conditions change.
  6. Works offline. It lets users download a region and keep viewing, searching and routing without a connection.

Each job has a different shape. Map display is a static-content distribution problem: precomputed tiles served from a CDN. Routing is an algorithmic problem on a huge graph, where the naive textbook algorithm is thousands of times too slow. Traffic is a stream-processing problem: millions of noisy GPS points per second, cleaned, snapped to roads and aggregated into speeds. Geocoding is a search problem with messy human input. Offline maps is a packaging and synchronisation problem.

Analogy. Think of a national road atlas, a team of traffic reporters, and a very fast navigator. The atlas is printed in pages at several scales: one page for the whole country, many pages for each city. You never redraw it for each reader; you print copies and hand them out at petrol stations everywhere. Those are the map tiles and the CDN. The navigator does not try every possible road from your house; they know the motorways, so they plan "local streets to the nearest motorway, motorway across the country, local streets at the end", which is the idea behind contraction hierarchies. The traffic reporters are thousands of drivers radioing in their speed every few seconds; a control room snaps each report to a road, averages them, and marks roads red or green on the shared atlas. That is the traffic pipeline. The address index at the back of the atlas, where you look up a street name to find its page and grid square, is geocoding. And tearing out the pages for your holiday region before you leave is offline maps.

Interviewers use this problem to see whether a candidate can:

  • Decompose a big product into subsystems with very different requirements.
  • Explain why naive shortest-path search fails at continental scale, and what production routing engines do instead.
  • Design a high-volume location-stream pipeline and turn it into useful traffic data.
  • Reason about caching static content at global scale.
  • Handle offline and mobile constraints.

The depth expected at staff level includes routing algorithms (bidirectional search, A*, landmarks, contraction hierarchies, customisable route planning), map matching with hidden Markov models, time-dependent ETAs, and the map-data pipeline.

Clarifying Questions#

QuestionWhy it mattersAssumed answer
Which features are in scope?Huge product; must scope.Map display, place search and geocoding, routing with ETA, live traffic, turn-by-turn navigation, offline maps.
Which travel modes?Graph and cost models.Driving first; walking and cycling share the machinery with different costs. Public transit is out of scope (it is a timetable problem).
Scale?Sizing.About 1 billion monthly users, around 300 million daily; tens of millions of concurrent navigation sessions at peak worldwide.
Where does the map data come from?Pipeline scope.Licensed and open sources, plus our own imagery and edits. We design the pipeline at a high level, not data collection.
Latency targets?Algorithm choice.Tiles under 100 ms from the CDN; route computation under 200 ms at p95 for typical trips; ETA updates every few seconds during navigation.
How fresh must traffic be?Stream design.Traffic speeds reflect conditions within about 1 to 2 minutes.
Accuracy of ETA?Model design.Most trips within about 10 percent of actual; measured continuously.
Offline?Client design.Users can download regions (a city or a country) and view, search and route offline; downloads update periodically.
Privacy?Location data is sensitive.Location sharing for traffic is opt-in; data is anonymised and aggregated.

Requirements#

Functional requirements#

  1. View the map: pan and zoom anywhere in the world, with roads, labels, buildings and points of interest.
  2. Search and geocode: find places and addresses (forward geocoding), and resolve a point to an address (reverse geocoding).
  3. Get directions: compute the fastest route between two or more points for driving, walking or cycling, with alternatives and an ETA.
  4. Live traffic: show traffic conditions on roads and incorporate them into routes and ETAs.
  5. Turn-by-turn navigation: guide the user along a route, re-route when they deviate or when conditions change, and update the ETA.
  6. Offline maps: download a region for offline viewing, search and routing.

Below the line: public transit routing, ride-hailing integration, street-level imagery, reviews and business listings in depth (see the proximity-service problem), map editing tools, indoor maps.

Non-functional requirements#

  1. Low latency: tiles in well under 100 ms (from cache), routes under 200 ms p95 for typical trips (under 1 second for continental trips), and geocoding suggestions under 100 ms per keystroke.
  2. High availability: map viewing and navigation are safety-relevant while driving; aim for 99.99 percent on the serving path. Degrade gracefully (for example, routing without live traffic) rather than fail.
  3. Scale: billions of tile requests per day, tens of thousands of route requests per second, and millions of location updates per second during peaks.
  4. Freshness: traffic within about 1 to 2 minutes; map data changes (new roads, closures) within hours to days, and urgent closures within minutes.
  5. Accuracy: correct routes respecting road rules; well-calibrated ETAs.
  6. Mobile efficiency: minimise data and battery use; work on poor networks and offline.

The framing to say out loud: this is several systems sharing one data foundation, the map. Tiles are a static-content CDN problem, routing is a precomputation-heavy graph problem, traffic is a stream-processing problem, and geocoding is a search problem. I will design each for its own workload and connect them through a versioned map-data pipeline.

Capacity Estimation#

Rough numbers to show that each subsystem has a different bottleneck (see Back-of-the-Envelope Estimation).

Users and sessions.

  • 1 billion monthly users, 300 million daily.
  • Assume 20 percent of daily users navigate on a given day, with an average of 2 trips of 20 minutes each: 60 million users × 2 = 120 million navigation sessions per day.
  • Sessions bunch at commute peaks. Peak concurrency is roughly (120 million × 20 min) / (1,440 min) × peak factor 3, about 5 million concurrent sessions globally. Some regions run hotter, so plan for 10 million concurrent sessions at the global peak.

Location updates (traffic probes).

  • A navigating phone sends a location every 1 to 5 seconds. Assume batches every 4 seconds, each containing 4 one-second fixes.
  • 10 million sessions / 4 seconds = 2.5 million requests per second, carrying 10 million GPS fixes per second.
  • Each fix is about 30 to 50 bytes compressed (latitude, longitude, timestamp, speed, heading, accuracy). 10 million × 40 bytes = 400 MB/s, about 35 TB/day raw. Most is kept only briefly; aggregated speeds are tiny.
  • Background (non-navigating) opted-in phones add more probes at lower frequency.

Route requests.

  • 300 million daily users × 1 route request on average = 300 million per day, plus re-routes and alternatives, so call it 1 billion route computations per day.
  • 1 billion / 86,400 ≈ 12,000 per second average and 40,000 per second at peak.
  • Each request must finish in under 200 ms. With a contraction-hierarchy-style engine, a continental query takes about 1 millisecond of CPU. At 40,000 QPS that is only 40 CPU-seconds per second, so about 40 cores of pure query time. Overheads (path unpacking, alternatives, traffic customisation, serialisation) multiply this by 10 to 50, giving a few hundred to a couple of thousand cores. With plain Dijkstra, a continental query takes seconds of CPU, so the same load would need hundreds of thousands of cores. That gap is the whole argument for preprocessing.

Road graph size.

  • The world road network has on the order of several hundred million junction nodes and around a billion directed edges once ways are split at junctions. The exact figure depends on the data source and on how nodes are counted.
  • Storing a node as 8 bytes of coordinates plus an adjacency offset (about 16 bytes), and an edge as target, weight and flags (about 16 bytes), gives 500 million × 16 + 1 billion × 16 ≈ 24 GB.
  • Add contraction-hierarchy shortcuts (roughly the same order as the original edge count) and metadata (names, turn restrictions, geometry for unpacking). A full world routing dataset lands in the tens to around 100 GB, which fits in RAM on one large machine or across a few regional machines.

Map tiles.

  • At zoom level z there are 4^z tiles. Zoom 0 is 1 tile, zoom 10 is about 1 million, zoom 14 is about 268 million, and zoom 18 is about 69 billion.
  • Most high-zoom tiles are ocean or empty land. Vector tiles are usually generated up to about zoom 14 to 16, and the client overzooms beyond that by scaling vector data, which drastically cuts the number of tiles.
  • A vector tile at street level is about 20 to 100 KB compressed. A planet vector tileset to zoom 14 is around 100 GB; an equivalent raster tileset to zoom 18 runs into many terabytes or more.
  • Tile requests: each pan or zoom loads about 10 to 30 tiles. 300 million daily users × 50 map interactions × 15 tiles = 225 billion tile requests per day, about 2.6 million per second on average. Almost all of it must be served by the CDN and the device cache, not the origin. With a 99 percent CDN hit ratio, the origin sees about 26,000 requests per second.

Geocoding and search.

  • 300 million daily users × 3 searches, each with about 5 autocomplete keystrokes, is about 4.5 billion requests per day, roughly 50,000 per second on average and 150,000 at peak.
  • The address and place index is a few hundred million places and addresses, around hundreds of GB of index. That is a sharded search cluster, not a single box.

Offline downloads.

  • A city package is about 50 to 300 MB, and a large country is around 1 to 2 GB, including vector tiles, the routing graph and the search index.
  • If 5 percent of daily users refresh one 200 MB package per month, that is 300 million × 0.05 × 200 MB / 30 ≈ 100 TB of egress per day. This is served by the CDN, with delta updates to cut it substantially.

Summary.

SubsystemLoadMain constraintKey technique
Tiles~2.6M req/s (edge)Bandwidth, global latencyPrecomputed vector tiles, CDN, client cache
Routing~40k req/sCPU per queryPreprocessing (CH/CRP), in-memory graph
Traffic probes~10M fixes/sIngest and stream computeKafka, map matching, windowed aggregation
ETAPer route + per session updateModel accuracyHistorical + live speeds, ML correction
Geocoding~150k req/s peakSearch latencySharded inverted index, prefix search
Offline~100 TB/day egressBandwidth, device storageRegion packages, deltas

Core Entities#

  • Node (junction): a point in the road graph where roads meet or properties change, with an ID and coordinates.
  • Edge (road segment): a directed connection between two nodes, with length, road class, speed limit, access flags (car, bike, foot), one-way status and geometry (a polyline).
  • Turn restriction: a rule such as "no left turn from edge A to edge B", or a turn cost.
  • Map feature: anything drawn on the map, such as roads, buildings, water, land use and labels, each with geometry and attributes.
  • Tile: a precomputed square of map features at a given zoom, x and y, in vector or raster form, tagged with a map-data version.
  • Place / address: a named location (a business, landmark, street address or administrative area) with coordinates and a hierarchy (country, region, city, street, house number).
  • Route: a sequence of edges from origin to destination, with geometry, distance, ETA and turn-by-turn instructions.
  • Navigation session: an active trip with the chosen route, the user's current position on it, the ETA, and re-route history.
  • Probe: an anonymised GPS fix (position, time, speed, heading, accuracy) from a device.
  • Segment speed: the current estimated speed on an edge, with a time window and confidence, derived from probes.
  • Map version: an immutable build of the map data. Tiles, routing graph and geocoder index are all derived from one version.
  • Offline region: a downloadable package bundling tiles, routing data and a search index for a geographic area at a given map version.

These group into three families. Static map data (nodes, edges, features, places) changes slowly and is built in batches. Dynamic data (probes, segment speeds, sessions) changes every second. Derived artefacts (tiles, routing graph, indexes, offline packages) are versioned outputs of batch pipelines, and the serving systems load them.

API Design#

The APIs are REST over HTTPS for request/response, with a streaming channel for navigation (see API Design Best Practices).

# Map tiles (cache-friendly, immutable per version)
GET /tiles/{style}/{version}/{z}/{x}/{y}.mvt
  -> 200, binary vector tile (Protocol Buffers, gzip/brotli), Cache-Control: max-age=31536000, immutable
 
# Traffic overlay tiles (short-lived)
GET /traffic/{z}/{x}/{y}.mvt?t={minute_bucket}
  -> 200, Cache-Control: max-age=60
 
# Geocoding / search
GET /geocode?q=1600+amphitheatre&near=37.42,-122.08&lang=en
  -> { results: [{ placeId, name, address, lat, lng, type, score }] }
GET /autocomplete?q=starb&near=37.42,-122.08&session={token}
  -> { suggestions: [{ placeId, text, matchedRanges }] }
GET /reverse-geocode?lat=37.4220&lng=-122.0841
  -> { address, placeId, components: { street, number, city, postcode, country } }
 
# Routing
POST /routes
{ origin: {lat, lng} | {placeId}, destination: ..., waypoints: [...],
  mode: "driving", departAt: "now" | ISO8601, avoid: ["tolls"], alternatives: true }
  -> { routes: [{ routeId, polyline, distanceM, etaSec, trafficEtaSec,
                  legs: [{ steps: [{ instruction, maneuver, distanceM, durationSec }] }] }] }
 
# Navigation session (stream)
POST /navigation/sessions { routeId } -> { sessionId, streamUrl }
WS   /navigation/sessions/{sessionId}
  client -> server: { fixes: [{lat, lng, t, speed, heading, acc}] }   every ~4 s
  server -> client: { etaSec, reroute?: { routeId, polyline, steps }, alerts: [...] }
 
# Offline
GET /offline/regions?bbox=...      -> [{ regionId, name, sizeMB, version }]
GET /offline/regions/{id}/manifest?have={version}
  -> { version, files: [{ path, hash, sizeMB }], delta: { from, url, sizeMB } }

Design notes:

  • Tile URLs include the map version. Each tile is immutable and can be cached forever. A new map version gives new URLs, so there is no cache invalidation problem; old tiles simply age out.
  • Traffic tiles are separate and short-lived (60 seconds), so the static base map keeps its long cache life.
  • Autocomplete carries a session token. Keystrokes in one search are grouped for ranking, billing and analytics, and the server can keep per-session state warm.
  • Routes return a routeId. Navigation sessions refer to the route by ID, so the server knows exactly what the user is following.
  • Navigation uses a WebSocket (or HTTP/2 or gRPC streaming), because the client streams fixes and the server pushes re-routes and ETA updates (see Polling, Long Polling, SSE, WebSockets and Webhooks). On weak networks the client falls back to periodic HTTP POSTs.
  • Offline manifests are content-addressed. The client says which version it has, and the server returns either a delta or the file list, so updates download only what changed.

High-Level Design#

We build the design one requirement at a time. Everything rests on one foundation: a map-data pipeline that ingests raw sources, builds an immutable map version, and derives tiles, the routing graph and the search index from it.

1. View the map: precomputed tiles on a CDN#

The world is cut into a pyramid of square tiles. At zoom 0 one tile covers the whole world. Each zoom level splits every tile into four, so zoom z has 2^z by 2^z tiles. A tile is addressed by z/x/y in the Web Mercator projection, the projection nearly every web map uses. It maps the sphere onto a square, preserving angles (so streets meet at the right angles) but stretching areas towards the poles.

There are two tile types:

  • Raster tiles are pre-rendered PNG or JPEG images, 256 or 512 pixels square. They are simple to display, but the style is baked in: labels cannot rotate with the map, every zoom level needs its own images, and high-DPI screens need larger images.
  • Vector tiles contain the geometry and attributes of features (roads as polylines, buildings as polygons, labels as points with text), usually encoded as Mapbox Vector Tiles (Protocol Buffers). The client renders them with the GPU. Vector tiles are smaller, can be restyled on the device (day and night mode, highlighting the route), let labels stay upright as the map rotates in navigation, and can be overzoomed: a zoom-14 tile holds enough detail to draw zooms 15 to 20 by scaling.

Modern mobile maps use vector tiles. Raster is still used for satellite imagery and for simple embeds.

A tile pipeline runs whenever a new map version is built. It reads features, simplifies geometry per zoom (no need for every building at zoom 8), selects which features appear at which zoom, clips them to tile boundaries, encodes and compresses them, and writes the tiles to object storage under the version prefix. The CDN fetches from object storage on a miss.

The client does its share too. It keeps a disk cache of recently seen tiles (tens to hundreds of MB), requests only the tiles in the viewport plus a small margin, and prefetches along an active route. With immutable versioned URLs, cached tiles never need revalidation.

2. Search and geocode#

Forward geocoding turns text into coordinates. Reverse geocoding turns coordinates into an address. Both use an index of places and addresses built from the same map version (see Elasticsearch and Search Systems).

  • Forward geocoding is a text-search problem. Parse and normalise the query, look up candidates in an inverted index of names and address tokens, then rank by text match, place importance and distance from the user or the viewport.
  • Reverse geocoding is a spatial problem. Find the nearest address point or street segment to the coordinate, then attach the administrative hierarchy (city, region, country) by point-in-polygon lookups against boundary polygons (see Geospatial Indexing and Proximity Search).

3. Get directions: a routing engine with preprocessing#

The road network is a directed weighted graph. Junctions are nodes, road segments are edges, and the weight is travel time. Finding the fastest route is a shortest-path problem.

The classic algorithm is Dijkstra's algorithm (Edsger Dijkstra, "A note on two problems in connexion with graphs", 1959). It explores outward from the origin in order of distance until it reaches the destination. On a continental graph it settles millions of nodes for a long trip and takes seconds, far too slow for 40,000 queries per second. So production engines preprocess the graph once per map version (and lightly per traffic update) into a structure that answers queries in about a millisecond. The best-known techniques are contraction hierarchies and customisable route planning, covered in Deep Dives 2 and 3.

The Routing Service loads the preprocessed graph into memory. Machines hold either a whole region or the whole world, and requests are routed to the machine that holds the right graph. Each query:

  1. Snaps the origin and destination to the nearest road edges.
  2. Runs the accelerated shortest-path search with current edge weights.
  3. Unpacks the path into real edges and geometry.
  4. Generates turn-by-turn instructions.
  5. Computes alternatives.
  6. Asks the ETA Service for a refined arrival time.

4. Live traffic: probes to segment speeds#

Phones that have opted in send GPS fixes. A Probe Ingest tier authenticates and anonymises them, then writes them to Kafka, partitioned by geographic cell so nearby probes land together. A stream processor (Flink or similar):

  1. Map-matches each trace to the road edges it travelled. GPS is noisy (5 to 20 m error), and in dense cities the nearest road is often the wrong one.
  2. Computes the observed speed on each edge from consecutive matched points.
  3. Aggregates speeds per edge over a sliding window (for example, the last 5 minutes, weighted towards recent data).
  4. Blends with historical speeds when there are few probes.

The result is a live speed table (edge ID to current speed and confidence), refreshed every 30 to 60 seconds. It feeds three consumers:

  • the routing engine, as new edge weights;
  • the traffic tile renderer, which colours roads green, orange and red;
  • the ETA Service.

5. Turn-by-turn navigation#

When the user starts a trip, the client opens a navigation session. Most of the guidance runs on the device, because it must work through tunnels and dead zones and react within a second:

  • the device snaps its own GPS to the route;
  • it announces manoeuvres;
  • it detects deviation.

The server's role is to:

  • receive the position stream, which doubles as a traffic probe;
  • recompute the ETA with fresh traffic;
  • watch for better routes (for example, a crash ahead) and push a re-route suggestion;
  • compute a new route when the device reports that it went off-route.

The Navigation Service holds session state (route, progress, last ETA) in a fast store keyed by session ID, so any server can pick the session up after a reconnect.

6. Offline maps#

The Offline Packager cuts a region out of a map version and bundles:

  • its vector tiles up to a chosen zoom;
  • a compact routing graph for the region with its own preprocessing;
  • a small local search index;
  • metadata.

The package is published to object storage and the CDN. Clients download it in chunks, verify hashes, and later fetch deltas between versions. With a package installed, the client renders, searches and routes locally, and uses the network only for live traffic when available.

The full high-level design#

Components:

  • Clients: render vector tiles with the GPU, keep a tile cache, run on-device guidance, and hold offline packages.
  • CDN and object storage: serve the vast majority of map bytes (tiles, traffic tiles, offline packages). Versioned URLs make tiles immutable (see Content Delivery Networks (CDN) and Object Storage and Blob Storage).
  • API Gateway: handles authentication, rate limiting, and routing requests to the region that holds the right graph (see API Gateway and Backend-for-Frontend).
  • Geocoding Service: text and spatial search over places and addresses.
  • Routing Service: an in-memory preprocessed graph per region, using CH or CRP queries with live weights.
  • ETA Service: blends historical profiles, live speeds and learned corrections into arrival-time predictions.
  • Navigation Service: session state, ETA refresh and re-route pushes.
  • Probe Ingest, Kafka and stream processing: turn raw GPS into live segment speeds.
  • Map-data pipeline: builds immutable map versions and all derived artefacts.

Note how little of this is a traditional database. Static map data lives in versioned files (tiles, graph binaries, index segments). Dynamic data lives in streams and in-memory tables. Sessions and user data (saved places, history) are the only classic database workloads.

Key Flows#

Flow 1: Get directions#

  1. The user types a destination. Autocomplete returns suggestions, and the user picks one, which resolves to a placeId and coordinates.
  2. The client sends POST /routes with its current GPS position as the origin.
  3. The gateway routes the request to a Routing Service instance holding the graph for that region. A cross-region trip goes to an instance holding a larger, continental graph.
  4. Routing snaps both points to the nearest drivable edges, using a spatial index over edges, and takes heading into account for the origin so the route does not start by driving the wrong way.
  5. It runs the accelerated search (CH or CRP) with the current customised weights, meaning the base travel times overlaid with live traffic.
  6. It computes 2 or 3 alternatives that differ meaningfully from the best route.
  7. It unpacks shortcut edges into real road segments, builds the polyline and generates step instructions ("In 300 m, turn left onto Main St").
  8. The ETA Service refines the arrival time for each alternative.
  9. The response returns with the routes, and the client draws them on the vector map.

Latency budget for a typical 20 km city trip:

StepTime
Network and gateway20 to 50 ms (mobile)
Snapping~1 ms
CH or CRP search~1 to 5 ms
Alternatives (several more searches)~5 to 20 ms
Unpacking and instruction generation~2 to 10 ms
ETA refinement~5 to 20 ms
Serialisation~2 ms
Total server~20 to 60 ms

The search itself is a small fraction. Most of the time goes to everything around it, which is typical of preprocessed routing.

Flow 2: Navigate with re-routing#

  1. The client opens a navigation session and keeps a WebSocket connection to the Navigation Service.
  2. Every second the device takes a GPS fix and snaps it to the route locally. It advances progress, triggers voice prompts, and every 4 seconds sends the batched fixes to the server.
  3. The server stores session progress and forwards the fixes to the probe pipeline as traffic data.
  4. Every 30 to 60 seconds, or when the live speed table changes along the remaining route, the server recomputes the ETA. If a significantly faster route appears (for example, more than 2 to 5 minutes saved, to avoid flip-flopping), it pushes a re-route suggestion.
  5. If the device detects it has left the route (several consecutive fixes far from the route, or a heading inconsistent with it), it asks for a new route immediately from its current position. Without a connection, it computes one using the on-device offline graph if available.

Flow 3: From probe to traffic colour#

  1. A phone's fixes arrive at Probe Ingest. Ingest strips the user identity and gives the trace a rotating pseudonymous trip ID, so traces can be stitched for map matching without linking them to an account.
  2. The fixes are written to Kafka, keyed by geographic cell (for example, an S2 or H3 cell at around 1 to 5 km).
  3. A Flink job map-matches each short trace with a hidden Markov model (Deep Dive 5) to find which edges the vehicle drove.
  4. For each edge traversal it computes the speed (edge length divided by time between entry and exit), filtering outliers such as a car parked by the road or a bus at a stop.
  5. A windowed aggregator per edge maintains a robust average of recent speeds (a median or trimmed mean over the last few minutes), weighted by recency and probe quality.
  6. Every 30 to 60 seconds the aggregator publishes a speed snapshot to the live speed table. It also publishes updates to the routing customisation step and the traffic tile renderer.
  7. Traffic tiles are re-rendered for changed areas and served with a 60-second cache lifetime.

End-to-end freshness: a few seconds for ingest, 10 to 30 seconds for matching (it needs several fixes to be confident), a 30 to 60 second publication interval, and then routing customisation. The total is about 1 to 2 minutes, which meets the requirement.

Flow 4: Download an offline region#

  1. The user selects an area. The client asks for the available regions covering it, with their sizes.
  2. The client fetches the manifest for the region and the current version: a list of files with content hashes.
  3. It downloads the files in chunks from the CDN, resuming after interruptions, preferably on Wi-Fi.
  4. It verifies the hashes, installs the package atomically (a new directory, then a pointer switch), and deletes the old version.
  5. Later, the client asks for the manifest with have=<version>. The server returns a delta: only the changed tiles and graph chunks, plus a patch for the search index.

Data Model#

The data splits into static map data, built per map version and stored as files, and dynamic and user data, held in streams, in-memory tables and a few databases.

Static map data (per map version):

Dynamic and user data:

DataStoreWhy
Raw map sources and editsObject storage plus a versioned feature database (for example PostgreSQL with PostGIS for editing)Large, spatial, edited by tools and pipelines
Map version build outputsObject storage (immutable files per version)Write once, read by many serving systems
Vector tilesObject storage plus CDNImmutable, keyed by version/z/x/y
Routing graphBinary files loaded into RAM on routing servers (memory-mapped)Must be in memory for millisecond queries
Base historical speed profilesFiles per version (edge × time-of-week buckets)Large but static; loaded alongside the graph
Live edge speedsIn-memory table, replicated to routing servers; snapshots in a key-value storeUpdated every 30 to 60 s, read millions of times
Probe streamKafka (short retention), then an aggregated lake (Parquet in object storage)High-volume append; analytics and ETA training
Search indexElasticsearch or a custom inverted index, shardedText and prefix search with geo ranking
Navigation sessionsRedis or a similar in-memory store with TTLSmall, hot, short-lived, any server can resume
User data (saved places, history)A sharded key-value or document database (DynamoDB, Cassandra or Spanner-style)Per-user access pattern, global, durable
Offline packagesObject storage plus CDNLarge immutable blobs with manifests

For the general reasoning behind these choices, see Choosing a Database: A Decision Guide.

Notes on the model:

  • Edge IDs must be stable across map versions where possible. Traffic history, user reports and learned ETA corrections are all keyed by edge. If every rebuild renumbered edges, history would be lost. Pipelines keep a stable ID mapping, for example derived from the source way ID plus a segment index, and translate it when roads are split or merged.
  • Base time is stored in deciseconds (tenths of a second) as an integer, which keeps the graph compact and avoids floating-point issues in the search.
  • Geometry lives apart from topology. The search touches only node IDs, edge targets and weights, which must stay cache-friendly. Geometry and names are only needed when unpacking the final route, so they sit in a separate array.

Deep Dives#

1. Map tiles: projection, pyramid, vector encoding and CDN strategy#

Web Mercator in one paragraph. A point at longitude λ and latitude φ (in radians) maps to x = λ and y = ln(tan(π/4 + φ/2)). This stretches the map vertically towards the poles; at latitude 85.05° the y value equals π, so the world becomes a perfect square, and Web Mercator simply cuts the map off there. Normalised to the range 0 to 1 and multiplied by 2^z, the integer parts of x and y are the tile coordinates at zoom z. Mercator is conformal (it preserves local angles and shapes), which is why street grids look right. Its price is area distortion: Greenland looks the size of Africa. For a navigation product, local shape matters much more than global area.

Ground resolution. At zoom z with 256-pixel tiles, one pixel at the equator covers about 156,543 / 2^z metres, which shrinks by cos(latitude) further north. At zoom 15 that is about 4.8 m per pixel at the equator and about 3 m in London. At zoom 18 it is about 0.6 m. This is why street-level detail is needed around zoom 15 to 17, and why tiles beyond zoom 19 to 20 add little.

The pyramid and what is actually stored. Zoom 18 has about 69 billion tiles, but around 70 percent of the Earth is ocean, and most land is empty at street scale. A tile pipeline:

  • generates only non-empty tiles;
  • deduplicates identical tiles (every pure-ocean tile at zoom 12 is byte-identical, so one blob serves millions of addresses);
  • stops at a maximum zoom for vector data, typically 14 to 16.

The client overzooms beyond that. A zoom-14 vector tile holds full-resolution coordinates (usually quantised onto a 4,096-unit grid inside the tile, giving about 0.6 m precision at zoom 14). Drawing it at zoom 18 just scales it up.

Generalisation per zoom. At low zoom you must drop and simplify. Drop minor roads, buildings and small water bodies at zoom 8. Simplify polylines with algorithms like Douglas–Peucker (David Douglas and Thomas Peucker, 1973), which keeps a vertex only if it deviates from the simplified line by more than a tolerance, set to roughly one pixel at that zoom. Merge adjacent land-use polygons. Without generalisation, a zoom-6 tile of Europe would contain every residential street and weigh hundreds of megabytes; with it, the tile stays in the tens of kilobytes.

Clipping and buffers. Features are clipped to the tile boundary plus a small buffer (for example 64 of 4,096 units), so lines and polygons joining across tiles render without seams, and wide strokes near the edge are not cut off.

Labels. Label placement is the hardest part of rendering. Labels must not collide, must stay upright as the map rotates, and should not jump around between zooms. With raster tiles, labels are burnt in and cut at tile edges. With vector tiles, the client places labels across all visible tiles together, using a collision index, and can rotate them with the map. That is a major reason navigation apps moved to vector tiles.

Vector tile encoding. A Mapbox Vector Tile is a Protocol Buffers message with layers (roads, buildings, water, places). Each layer has a list of features. Geometries are encoded as commands (MoveTo, LineTo, ClosePath) with zig-zag, delta-encoded integer coordinates, which compresses well. Attributes are stored as indices into per-layer key and value tables, so repeated strings like "residential" appear once. After gzip or brotli, a dense city tile is typically 30 to 100 KB.

Styles are separate from data. The style (colours, line widths per zoom, which layers show, fonts) is a small JSON document the client applies at render time. The same tiles can serve a day style, a night style, a navigation style that emphasises the route, and a terrain style. Raster maps need a separate tileset for each style.

CDN strategy.

  • Versioned, immutable URLs such as /tiles/{style}/{version}/{z}/{x}/{y} are cached with a one-year max-age. Publishing a new version means clients switch the version in their style config; old tiles stop being requested and age out of the cache. No purge storms.
  • An origin shield (a regional mid-tier cache) collapses misses from hundreds of edge PoPs into one fetch per region per tile.
  • Popularity is very skewed. Low-zoom tiles and city-centre tiles are hit constantly and stay cached everywhere. Rural zoom-14 tiles are rare. Hit ratios of 95 to 99 percent or more at the edge are realistic.
  • Pre-warm the edge caches with low-zoom tiles and major city tiles for a new version before flipping clients to it, so the switch does not cause a miss spike.
  • Traffic tiles are separate URLs with a time bucket and a 60-second cache lifetime. They are small, because they contain only road segments with a congestion level, not the whole map.

Raster versus vector: when each fits.

AspectRaster tilesVector tiles
Client complexityMinimal (show images)GPU renderer, label engine
Size per tileLarger (images), one per style per DPISmaller, one for all styles
Rotation and tiltLabels rotate badlyLabels stay upright, 3D tilt possible
Max zoom generatedEach zoom stored (to 18 to 20)To 14 to 16, then overzoom
StylingFixed at render time on the serverDynamic on the client
Best forSatellite imagery, simple embeds, old devicesNavigation apps, interactive maps

Real-world note. Google Maps moved its mobile and web clients from raster to vector rendering during the 2010s. Open-source stacks (OpenStreetMap data, tile generators like tippecanoe or Planetiler, and renderers like MapLibre) use the same vector approach. The details of any particular company's tile pipeline are not public, so treat the specifics here as the general industry approach rather than a description of one company.

2. Shortest paths from first principles: BFS, Dijkstra, bidirectional, A* and landmarks#

Routing algorithms build on one another, and an interviewer will often ask you to walk the ladder. Each rung fixes the weakness of the one below.

Rung 0: Breadth-first search (unweighted graphs). If every edge costs the same (hops in a social network, or moves in a grid puzzle), BFS finds the shortest path. Put the start in a queue. Repeatedly pop a node and push its unvisited neighbours, remembering for each neighbour which node discovered it (a previous map). When the target is popped, walk the previous map backwards from the target to rebuild the path. BFS is O(V + E) and simple. It is the right tool for "degrees of separation" in a social graph. But roads are weighted: a 2 km motorway at 110 km/h is faster than 300 m of congested side street. BFS minimises the number of segments, not travel time, so it is wrong for routing.

// BFS shortest path by hop count, with path reconstruction
function bfsPath(adj: Map<number, number[]>, s: number, t: number): number[] | null {
  const prev = new Map<number, number>([[s, s]]);
  const queue: number[] = [s];
  for (let head = 0; head < queue.length; head++) {
    const u = queue[head];
    if (u === t) break;
    for (const v of adj.get(u) ?? []) {
      if (!prev.has(v)) { prev.set(v, u); queue.push(v); }
    }
  }
  if (!prev.has(t)) return null;
  const path = [t];
  while (path[path.length - 1] !== s) path.push(prev.get(path[path.length - 1])!);
  return path.reverse();
}

Rung 1: Dijkstra (non-negative weights). Replace the queue with a priority queue ordered by tentative distance. Each time, pop the node with the smallest distance. It is now settled: its distance is final, because every other path to it would go through a node with a larger distance, and weights are non-negative. Then relax its outgoing edges: if dist[u] + w(u, v) < dist[v], update dist[v] and prev[v]. Stop when the target is settled. With a binary heap, the cost is O((V + E) log V).

The intuition is a ripple spreading out from the origin, reaching nodes in order of travel time. The problem is that the ripple is a disc. For a trip of radius r, Dijkstra settles every node within travel time r of the origin, in every direction, including the direction away from the destination. On a European road graph of around 18 million nodes (the standard benchmark used in the research literature), a random long query settles millions of nodes and takes on the order of seconds.

Rung 2: Bidirectional Dijkstra. Run one search forward from the origin and another backward from the destination over reversed edges, alternating between them. Each search's disc has roughly half the radius, and the area of a disc scales with r², so two discs of radius r/2 cover about half the area of one disc of radius r. That gives about a 2x speedup.

The subtle part is the stopping rule. You cannot stop the moment the two searches touch, because the first meeting node is not necessarily on the shortest path. Keep track of μ, the best total dist_f(v) + dist_b(v) seen over any node v reached by both searches. Stop when the smallest key in the forward queue plus the smallest key in the backward queue is at least μ. At that point no undiscovered path can be shorter.

Rung 3: A (goal-directed search).* A* (Peter Hart, Nils Nilsson and Bertram Raphael, "A Formal Basis for the Heuristic Determination of Minimum Cost Paths", 1968) orders the queue by dist[v] + h(v), where h(v) is an estimate of the remaining cost to the target. If h is admissible (it never overestimates) and consistent (h(u) ≤ w(u, v) + h(v)), A* is still exact, and it explores a teardrop pointed at the target instead of a disc.

A consistent heuristic is equivalent to running Dijkstra on reduced costs w'(u, v) = w(u, v) − h(u) + h(v), which are non-negative exactly when h is consistent. This shows why A* is correct: along any path from s to t, the h terms telescope, so every path's length shifts by the same constant.

For travel time, the natural heuristic is straight-line distance divided by the maximum speed in the network. Because the top speed (say, 130 km/h on motorways) is far above typical speeds, the estimate is very loose. In practice the speedup on road networks with travel-time weights is modest, often only around a factor of 2. A* shines when the heuristic is tight, for example for walking or on distance-weighted graphs.

Rung 4: ALT (A, Landmarks, Triangle inequality).* Andrew Goldberg and Chris Harrelson ("Computing the Shortest Path: A* Search Meets Graph Theory", SODA 2005) found a much tighter heuristic.

  • Pick about 16 landmarks, typically at the periphery of the map.
  • Precompute the exact distances from every node to every landmark and from every landmark to every node.
  • By the triangle inequality, for any landmark L: dist(v, t) ≥ dist(L, t) − dist(L, v), and dist(v, t) ≥ dist(v, L) − dist(t, L).
  • Take the maximum of these bounds over all landmarks. It is admissible, consistent, and much tighter than straight-line distance, especially when the target lies "behind" v as seen from a landmark.

ALT gives roughly an order-of-magnitude speedup over Dijkstra. Its cost is memory: 16 landmarks × 2 directions × V nodes × 4 bytes is about 2.3 GB for 18 million nodes. It has one useful property for this design: landmark distances computed on free-flow times remain valid lower bounds when traffic makes roads slower, because traffic only increases weights. So ALT tolerates live traffic without re-preprocessing, as long as weights never drop below the values used for the landmarks.

Why even ALT is not enough. ALT still settles tens of thousands to hundreds of thousands of nodes for a long trip, which takes tens of milliseconds or more. At 40,000 QPS that is a lot of hardware, and it also leaves no time budget for alternatives. The breakthrough came from exploiting the hierarchy of road networks: long trips use a few important roads. That leads to contraction hierarchies.

Worked example. A trip from central London to central Manchester, about 330 km by road and 4 hours:

AlgorithmApproximate nodes settledApproximate time
DijkstraSeveral million (a disc of 4 hours of driving)~1 to 3 s
Bidirectional DijkstraAbout half of that~0.5 to 1.5 s
A* (straight-line / max speed)Somewhat fewer than Dijkstra~0.5 to 1.5 s
ALT (16 landmarks)Tens to hundreds of thousands~20 to 100 ms
Contraction hierarchiesA few hundred to ~1,000~0.1 to 1 ms

These are order-of-magnitude figures consistent with published benchmarks on continental road graphs. Exact values depend on the graph, the hardware and the implementation.

3. Contraction hierarchies: how routing gets to a millisecond#

The idea. Robert Geisberger, Peter Sanders, Dominik Schultes and Daniel Delling ("Contraction Hierarchies: Faster and Simpler Hierarchical Routing in Road Networks", WEA 2008) proposed ordering all nodes by importance, from the quietest cul-de-sac junction up to major motorway interchanges. Nodes are then removed ("contracted") one at a time in that order. Whenever removing a node v would break a shortest path u → v → w, a shortcut edge u → w is added with weight w(u, v) + w(v, w). After every node has been contracted, the original graph plus all the shortcuts forms a hierarchy. Every shortest path in the original graph can be found by going only upward in importance from the origin and only upward from the destination (on reversed edges), and meeting at the top.

Contracting one node. When contracting v, consider every pair of an incoming neighbour u and an outgoing neighbour w that are not yet contracted. A shortcut u → w is needed only if u → v → w is the unique shortest path from u to w among the remaining nodes. To check this, run a small, bounded Dijkstra from u that ignores v, called a witness search. If it finds a path to w no longer than w(u, v) + w(v, w), the path is a "witness" and no shortcut is needed. The witness search is limited (by hops or by settled nodes) to keep preprocessing fast. If the limit is hit, it adds the shortcut anyway, which is safe: extra shortcuts never break correctness, they only cost memory.

Choosing the order. The order is chosen greedily with a priority that combines several terms:

  • The edge difference: the shortcuts added minus the edges removed. Prefer nodes whose contraction adds few shortcuts.
  • Uniformity: prefer nodes whose neighbours have not been contracted, so contraction spreads evenly across the map.
  • Shortcut depth: penalise deep chains of shortcuts.

Priorities are updated lazily as contraction proceeds. Quiet residential junctions go first, with almost no shortcuts. Motorway junctions go last, because removing them would force many shortcuts. The resulting order follows the natural road hierarchy without anyone labelling road classes.

The query. Run a bidirectional Dijkstra in which the forward search relaxes only edges to higher-ranked nodes, and the backward search relaxes only reversed edges to higher-ranked nodes. Both searches climb the hierarchy quickly and stay small: a few hundred settled nodes each, even across a continent. Maintain μ, the best meeting cost, and stop each direction when its queue minimum reaches μ. One extra trick, stall-on-demand, prunes nodes reached suboptimally via an upward edge when a downward edge proves a better distance, which cuts settled nodes further.

Why it is correct (intuition). Take any shortest path from s to t and find its highest-ranked node m. Every node between s and m on the path was contracted before m. When each was contracted, either a shortcut was added that bridges it, or a witness of equal length exists (and that witness also has its own up-down form). By induction, an equal-length path exists that rises monotonically from s to m and then descends monotonically to t. The forward upward search finds the rising part, and the backward upward search finds the reversed descending part.

Unpacking. The path found consists partly of shortcuts. Each shortcut stores its middle node v, so unpacking is a recursion: shortcut (u, w) via v becomes (u, v) + (v, w), each of which may itself be a shortcut. The result is the real edge sequence, which the system uses for geometry, names and instructions.

// CH query (sketch). up[u] lists edges u -> v with rank(v) > rank(u)
// down_rev[u] lists reversed edges u <- v with rank(v) > rank(u)
function chQuery(s, t):
  df = {s: 0}; db = {t: 0}; qf = heap(s, 0); qb = heap(t, 0); mu = INF; meet = none
  while (qf or qb) and min(qf.top, qb.top) < mu:
    for (q, d, edges, other) in [(qf, df, up, db), (qb, db, down_rev, df)]:
      if q.empty or q.top >= mu: continue
      u = q.pop()
      if u in other and d[u] + other[u] < mu: mu = d[u] + other[u]; meet = u
      for (v, w) in edges[u]:
        if d[u] + w < d.get(v, INF): d[v] = d[u] + w; q.push(v, d[v])
  return (mu, meet)      // then unpack s..meet and meet..t recursively

Typical numbers on a continental graph (orders of magnitude from published results on European road networks):

MetricValue
Preprocessing timeMinutes on a multicore server
Shortcuts addedAbout as many as the original edges
Extra memoryA small multiple of the base graph
Nodes settled per queryHundreds
Query timeAround 0.1 to 1 ms
Speedup over DijkstraThousands of times

The catch: weights are baked in. The shortcuts and the node order were computed for one weight function. When traffic changes edge weights, a shortcut's weight is stale, and a witness that justified skipping a shortcut may no longer be shortest. Re-running full contraction takes minutes, which is too slow for traffic updates every minute. There are three ways out:

  1. Customisable CH (CCH) (Julian Dibbelt, Ben Strasser and Dorothea Wagner, around 2014 to 2016). Compute a metric-independent order from graph structure using nested dissection, and add all shortcuts that order implies, with no witness search. Then, per traffic update, recompute only the shortcut weights bottom-up in seconds. Queries become somewhat slower than classic CH, but customisation is fast.
  2. CRP / multi-level partitioning (next deep dive). This is the most widely discussed production answer for live traffic.
  3. Keep CH for the static part and patch. Recompute CH periodically, and handle closures and heavy jams with a small overlay search that avoids affected shortcuts. This is simpler, but approximate.

Other hierarchical and labelling methods worth naming.

  • Highway hierarchies (Sanders and Schultes, 2005), the predecessor of CH.
  • Transit node routing (Bast, Funke, Sanders and Schultes, 2007). This precomputes distance tables between a small set of "access nodes" and answers long queries with table lookups in microseconds.
  • Hub labelling (Abraham, Delling, Goldberg and Werneck, around 2011). Every node stores a label, a list of hubs with their distances, and a query is a merge of two sorted lists. This is extremely fast (microseconds) but memory-heavy.

These sit at different points of the preprocessing / memory / query-time trade-off. CH remains the practical sweet spot when weights change rarely, and it is what open-source engines such as OSRM and GraphHopper offer as their fastest mode.

4. Live traffic in routing: customisable route planning, turn costs and time dependence#

The requirement. Edge weights change every minute as traffic moves, and the router must use them. We need preprocessing that is independent of the weights (slow, once per map version) plus a customisation step that is fast (seconds, per traffic update).

Customisable Route Planning (CRP). Daniel Delling, Andrew Goldberg, Thomas Pajor and Renato Werneck ("Customizable Route Planning", SEA 2011) split the work into three phases.

  1. Metric-independent preprocessing (once per map version, around an hour). Partition the graph into cells with few boundary nodes, and do it at several levels. For example, level 1 has cells of a few thousand nodes, level 2 groups level-1 cells into cells of tens of thousands, and so on up to a handful of levels. Road networks have natural small cuts (rivers, mountains, motorways with few crossings), and partitioners exploit them; the authors' companion method is "Graph Partitioning with Natural Cuts" (Delling, Goldberg, Razenshteyn and Werneck, 2011). The topology of each cell's overlay, a clique connecting every pair of its boundary nodes, is fixed here.
  2. Customisation (per weight change, seconds). For each level-1 cell, compute the shortest distances between all pairs of its boundary nodes using the current weights inside the cell. For level 2, compute boundary-to-boundary distances using the level-1 overlays, and so on up the levels. Each cell is independent, so the work runs in parallel across all cores. Better still, only cells containing changed edges (and their ancestors) need recomputation, so a traffic update that touches 5 percent of edges touches far fewer than 100 percent of cells at the lowest level.
  3. Query (milliseconds). Run bidirectional Dijkstra on a multi-level overlay graph. Inside the origin's and destination's level-1 cells, use the real edges. Elsewhere, use the highest-level overlay cell that contains neither endpoint. A cross-country trip uses real edges only near its ends and jumps across the country on precomputed boundary cliques. Finally, unpack the overlay edges by running a local search inside each cell.

Why the trade-off works. CRP queries (a few milliseconds) are slower than CH (sub-millisecond) but still far within budget. In return, customisation takes seconds, so weights can be refreshed every 30 to 60 seconds. Changing the metric (travel time, distance, a truck profile that avoids low bridges, or a "no tolls" option) is simply another customisation of the same partition. Microsoft researchers developed CRP, and it was reported to power Bing Maps routing. OSRM's "MLD" (multi-level Dijkstra) mode is an open-source implementation of the same idea.

Turn costs and restrictions. Real routing must model turns. A left turn across traffic costs time, a U-turn may be banned, and "no left turn from A to B" is a common restriction. There are two approaches:

  • Edge-based graph. Make each road segment a node, and each allowed turn an edge carrying the turn cost. This is simple and exact, but the graph grows about 3x.
  • Turn tables at junctions. Keep the node-based graph, and store a small turn-cost matrix per junction (entry point × exit point). CRP was designed to handle this compactly, without the edge-based blow-up.

Turn costs are not decoration. In a city, ignoring them gives routes with many left turns that look short but drive slowly. ETAs come out optimistic by 10 percent or more.

Time-dependent routing. Traffic on a 3-hour drive will change during the drive. Using current speeds for the whole trip is wrong for its later part: you will not reach the motorway near the city for 2 hours, by which time its jam will have cleared. Correct handling makes each edge's travel time a function of the entry time, typically a piecewise-linear function per edge derived from historical speed profiles for each 15-minute bucket of the week.

  • Time-dependent Dijkstra works if every edge satisfies the FIFO property: entering later never means leaving earlier. Real traffic satisfies this, and models enforce it.
  • In practice, systems blend three sources by look-ahead time. Near the origin they use live speeds, which are the best estimate for the next 15 to 30 minutes. Further along they use the historical profile for the expected arrival time at each edge. In between they smoothly interpolate, often with a decay of the live deviation from the historical value.
  • Time-dependent variants of CH exist (time-dependent contraction hierarchies, from Karlsruhe researchers in the late 2000s and early 2010s), but they are memory-heavy. A common production compromise is to run the overlay search on a static snapshot of predicted weights, and then evaluate the chosen route and alternatives time-dependently in the ETA step.

Alternative routes. Users want 2 or 3 options. A good alternative is:

  • significantly different, sharing less than about 70 to 80 percent with the best route;
  • not much longer, less than about 25 percent more time;
  • locally optimal, with no silly detours: every short subpath is itself a shortest path.

The via-node approach finds candidate nodes v, so that a route is s → v → t, using the forward and backward search spaces of a CH or CRP query, and then filters them by these criteria. The penalty approach increases the weights of the best route's edges and searches again. With CRP, the penalty approach is natural, because a penalty is just a re-customisation of a few cells.

Routing profiles. Car, truck, bike and foot differ in:

  • Access: footpaths versus motorways.
  • Speeds.
  • Costs: cycling prefers bike lanes and avoids hills; trucks need height and weight limits and avoid residential streets.
  • Turn rules.

With CRP, one partition serves every profile through different customisations. With CH, each profile needs its own full preprocessing.

5. Map matching: snapping noisy GPS to roads with a hidden Markov model#

Why it is hard. Phone GPS error is typically 5 to 10 m in open areas and 20 to 50 m or worse in urban canyons, where signals bounce off tall buildings. Parallel roads (a motorway and its frontage road, or a bridge over a street) are often closer together than the error. Snapping each point to the nearest road gives traces that jump between roads, which produces nonsense speeds: a car apparently teleporting between the motorway at 100 km/h and the side road at 30 km/h. Map matching instead finds the most plausible sequence of road positions for a whole trace.

The hidden Markov model formulation. Paul Newson and John Krumm ("Hidden Markov Map Matching Through Noise and Sparseness", ACM SIGSPATIAL GIS 2009) framed it like this:

  • Hidden states: for each GPS point z_t, a set of candidate positions, which are projections of z_t onto every road segment within a radius (say 50 to 200 m).
  • Emission probability: how likely the GPS point is, given that the vehicle was at candidate r. Model GPS error as Gaussian: p(z_t | r) ∝ exp(−0.5 × (d / σ)²), where d is the distance from z_t to r and σ is the GPS noise (around 4 to 10 m, estimated from data).
  • Transition probability: how likely it is to move from candidate r_i at time t to r_j at time t+1. The key insight is that for real movement, the driving distance between consecutive candidates (computed by routing on the graph) is close to the straight-line distance between the two GPS points. So use p ∝ exp(−|route_dist − great_circle_dist| / β). A candidate pair that requires a 2 km detour to explain 100 m of straight-line movement (for example, exiting the motorway, turning around and coming back) gets near-zero probability.
  • Inference: the Viterbi algorithm finds the most likely state sequence in O(T × K²) time for T points with K candidates each, by dynamic programming. For each point and each candidate, keep the best log-probability of any path ending there, together with a back-pointer.

Worked example. A car drives on a motorway, and a parallel service road runs 25 m away. GPS point 1 is 5 m from the motorway and 20 m from the service road. Point 2 is 18 m from the motorway and 7 m from the service road (multipath noise). Point 3 is 4 m from the motorway.

  • Nearest-road snapping gives motorway, service road, motorway: a zig-zag.
  • In the HMM, the transition from the motorway at point 1 to the service road at point 2 requires a route distance of perhaps 1.5 km (they connect only at junctions), while the GPS points are only 30 m apart. That transition probability is close to 0.
  • Staying on the motorway costs a worse emission at point 2 (18 m versus 7 m from the observation), but it has a near-perfect transition.
  • Viterbi picks motorway, motorway, motorway, which is correct.

Practical engineering.

  • Candidate pruning: keep K ≤ 5 to 10 per point to bound cost; use a spatial index (an R-tree or a cell grid) over road segments to find candidates quickly.
  • Sparse sampling: with fixes every 30 seconds instead of every second, route distances between candidates matter more, and the router must run between candidate pairs. That makes matching costlier but more robust. Newson and Krumm showed the HMM degrades gracefully as sampling becomes sparser.
  • Breaks: if all transitions are near zero (a GPS jump, a tunnel or a ferry), split the trace and start again.
  • Online versus offline: for live traffic, use fixed-lag Viterbi. Wait for a few more points, then commit the matched position a few points back. That gives most of the accuracy with a delay of 10 to 30 seconds.
  • Speed per edge: once a trace is matched, compute the time at which it entered and exited each edge by interpolating between fixes, and derive the traversal speed. Partial traversals (the trace starts mid-edge) give speeds weighted by the fraction covered.
  • Heading and speed hints: the device's heading and Doppler speed help disambiguate. Add them to the emission model, so that a candidate whose road direction disagrees with the heading by 90 degrees is unlikely.

Open-source engines (OSRM's match service, and Valhalla's map matcher) implement HMM-based matching of this kind, so it is well-trodden ground.

Where it runs. In this design, map matching runs in the stream processor, partitioned by geo cell. Each worker loads the road graph for its cells (a few GB for a dense region) and keeps short per-trip state, holding the last few fixes and Viterbi columns, keyed by trip pseudonym. That state is checkpointed with the stream processor's normal mechanism (for example, Flink checkpoints), so a worker crash does not lose a burst of traffic data.

The on-device navigation snapping is a simpler, constrained version of the same problem: the device already knows the route, so it mostly asks "am I still on the route, and where along it?"

6. Traffic estimation: from matched traversals to a live speed per edge#

Matching gives a stream of (edge, entry time, exit time, speed, quality) traversals. Turning that stream into a trustworthy live speed per edge raises several problems.

Robust aggregation. Traversal speeds on one edge vary a lot:

  • one driver is cautious;
  • a bus stops;
  • a delivery van double-parks;
  • someone pulls into a petrol station, and the matcher still thinks they are on the road.

Use robust statistics, such as the median or a trimmed mean over a sliding window, and weight each traversal by recency (an exponential decay with a half-life of a few minutes) and by match quality. On multi-lane roads with separate turn lanes, the edge speed can be bimodal: through traffic moves while the left-turn queue sits still. Advanced systems model lane-level or movement-level speeds (through, left, right) for major junctions.

Sparse data and confidence. A motorway at rush hour has hundreds of probes per minute. A rural road might see one an hour, and a residential street, almost none. For each edge, keep both an estimate and a confidence that grows with the number of recent probes. Blend live and historical: estimate = c × live + (1 − c) × historical(time-of-week), where c rises towards 1 as the probe count grows. With no recent probes, fall back on the historical profile. With no history, fall back on the posted speed limit times a road-class factor.

Spatial imputation. Congestion propagates. If the next three edges downstream are jammed and the current edge has no probes, it is probably slow too. Some systems smooth speeds along a road (a 1D Kalman filter or a simple smoother along consecutive edges). Graph models (see the ETA deep dive) learn this propagation directly.

Historical profiles. Aggregate months of traversals into time-of-week buckets, for example 7 days × 96 fifteen-minute slots = 672 buckets per edge. Store the median speed and the spread for each. For around a billion edges, storing every bucket is far too much: 672 × 1 B × 1 byte is about 670 GB. So compress:

  • most edges share a handful of profile shapes (a commuter road, a weekend shopping street, a motorway);
  • store a profile ID plus a scale per edge, and keep full profiles only for important edges.

Holidays, school terms and events get special-day profiles.

Incident and closure detection.

  • Sudden drops: speed falls from 100 to 10 km/h across consecutive edges within minutes. Flag a likely incident and lower the routing weight sharply ahead of the probe evidence.
  • Absence of traffic: a normally busy road suddenly has no traversals while the parallel roads are busy. This is a strong signal of a closure, which a speed-only model would miss, because no probes means no speed.
  • User reports: apps such as Waze (acquired by Google in 2013) are known for crowdsourced reports of accidents, hazards, police and closures. Reports need verification: several independent reporters, confirmation from speed data, and decay over time unless re-confirmed.
  • Official feeds: road authorities publish closures and roadworks. Ingest them as overrides with a start and end time.

Publishing. Every 30 to 60 seconds, emit a delta of edges whose speed changed meaningfully (for example by more than 10 percent, or a congestion-level change). Downstream consumers apply deltas: CRP customisation, traffic tile rendering and the ETA Service. Full snapshots are written periodically to a key-value store, so a restarted consumer can rebuild state quickly.

Privacy. Location traces are among the most sensitive data a company can hold, because a few points reveal home and work.

  • Strip the account identity at ingest.
  • Use short-lived, rotating trip pseudonyms.
  • Drop the first and last part of each trip (near home and the destination) before analysis.
  • Aggregate before storing long term.
  • Enforce a minimum count before publishing a speed, so a single person's movement cannot be read off a quiet road.

Raw traces should be retained only briefly. Long-term data should be aggregated speeds, not paths. See Security Fundamentals for System Design.

7. ETA prediction: sum of segments, then machine learning#

Baseline: sum of segment times. ETA = Σ over route edges of (length / predicted speed at the expected entry time) + Σ turn costs. With time-dependent speeds this is already reasonable, but it misses several effects:

  • Junction delays: traffic lights and queues at turns, which speeds on edges do not capture well.
  • Systematic bias: for example, parking time at a busy destination.
  • Correlated errors: if traffic is worse than history on the first part, it is probably worse further on too.
  • Unusual conditions: weather, events and holidays.

Machine-learned correction. A common production pattern is to predict a residual on top of the routing engine's estimate: ETA = routing_estimate × (1 + f(features)) or routing_estimate + g(features). Typical features:

  • route length and road-class mix;
  • time of day and week;
  • region;
  • weather;
  • live-versus-historical deviation along the route;
  • origin and destination types (an airport, a stadium);
  • the number of turns and signals.

Gradient-boosted trees work well. Deep models such as transformers over route segments are used at larger scale. Uber has publicly described a deep-learning residual model of this kind (DeepETA), layered over its routing engine.

Graph neural networks. Traffic propagates over the road graph, so a natural model works on the graph itself. Austin Derrow-Pinion and colleagues at DeepMind and Google ("ETA Prediction with Graph Neural Networks in Google Maps", CIKM 2021) described:

  • splitting the road network into supersegments, which are sequences of connected segments with significant traffic volume;
  • training a GNN that predicts travel time per supersegment from the current and historical traffic of the neighbouring segments;
  • reported meaningful reductions in poor ETAs in several cities.

Training stability required careful techniques (they discussed MetaGradients and parameter averaging). This is a good example of how far a mature product goes beyond "sum of edges".

Evaluation and calibration.

  • Metrics: mean absolute percentage error (MAPE), and also the tail: the fraction of trips more than 20 percent off. Users forgive a 2-minute miss on an hour-long trip, but not a 15-minute miss.
  • Asymmetry: arriving later than predicted is worse for users than arriving earlier. Some products bias slightly pessimistic, or show a range.
  • Ground truth: actual trip times from completed navigation sessions. Watch for selection bias: people who follow the route versus those who deviate, and trips abandoned mid-way.
  • Feedback loops: if the router sends everyone onto the side road the model says is clear, it stops being clear. Large-scale systems consider load-aware routing, spreading users across near-equal alternatives. That is a known hard problem, and approaches are proprietary and evolving.

Online updates during navigation. The server recomputes the remaining ETA every 30 to 60 seconds using:

  • the progress so far (if the driver is running 10 percent slower than predicted, adjust the remaining estimate a little; drivers differ);
  • fresh live speeds on the remaining edges;
  • the time-dependent profile for the rest.

Smooth the displayed ETA so that it does not jump around by a minute every update.

8. Geocoding, reverse geocoding and place autocomplete#

Forward geocoding pipeline.

  1. Normalise: apply Unicode normalisation, lowercase, strip accents for matching (keeping the originals for display), expand abbreviations ("St" to "street" or "saint" depending on context, "Ave" to "avenue"), and transliterate where useful.
  2. Parse: split the input into components such as house number, street, unit, city, postcode and country. Address formats vary hugely. The house number comes first in the US and after the street in much of Europe. Japan uses block-based addressing. Many places have no street addresses at all. Statistical parsers trained on large address corpora (the open-source libpostal library is a well-known example) beat hand-written rules.
  3. Candidate retrieval: search an inverted index over place names, street names, admin names and postcodes, with each candidate carrying its hierarchy ("Main Street, in Springfield, in Illinois, in the US").
  4. Hierarchy consistency: prefer candidates whose components agree. "Springfield, IL" should not match a Springfield in Oregon.
  5. House number resolution:
    • Use an exact address point if one exists.
    • Otherwise, interpolate along the street segment's address range. For example, if a block runs from 100 to 198 on the even side and the query is 150, place it about halfway along the block, on the correct side of the street.
  6. Rank by text-match quality, completeness of the match, place importance (population, popularity), and distance from the user or viewport.

Autocomplete. Every keystroke is a query, so it must take under 100 ms server time and use tiny payloads. Use edge n-gram or prefix indexes on names, so "starb" matches "Starbucks". Rank with a strong location bias: the user typing "main st" wants the one nearby. Popular places get a prior. Debounce on the client (wait about 100 to 150 ms after typing stops), cancel in-flight requests that are superseded, and cache recent prefixes on the device. This is the same family of problem as the search-autocomplete case study, with geography added to the ranking.

Reverse geocoding.

  1. Find the nearest address point or street segment to the coordinate with a spatial index.
  2. Find the containing admin polygons (neighbourhood, city, county, region, country) with point-in-polygon queries over an R-tree of boundary polygons. Boundary polygons can have thousands of vertices, so precompute a coverage of each polygon in grid cells (S2 or H3, see Geospatial Indexing and Proximity Search). Most lookups then resolve with a cell lookup, and only points in cells on the boundary need an exact polygon test.
  3. Assemble the address in the local format and language.

Multilingual and fuzzy matching. Names exist in several languages and scripts ("München", "Munich" and "Monaco di Baviera"). Index all variants and match the query language. Fuzzy matching (edit distance 1 to 2 on longer tokens) catches typos but must be limited, or short queries match everything.

Scale. Hundreds of millions of places and addresses, at 150,000 QPS peak, means a sharded search cluster. One option is to shard by geography: most queries are local and carry a location bias, so they hit one or two shards, with a small global index of countries, major cities and landmarks queried in parallel. Another is to shard by document, scattering each query to every shard and gathering the results; this is simpler but costlier per query. See Elasticsearch and Search Systems. The index is rebuilt per map version and swapped atomically; new businesses arrive through a faster incremental path.

9. Routing at scale: sharding the graph and the cross-shard problem#

The naive approach: shard a graph and traverse across machines. Consider how you would run a shortest-path search on a graph too big for one machine, which is the classic social-graph setup.

  • Nodes are spread over many graph servers.
  • A lookup service maps a node ID to the server that holds it.
  • A traversal service runs BFS or Dijkstra centrally. Each time it expands a node, it asks the lookup service where the node lives, then fetches its adjacency list from that server over the network.

Every expansion is a network round trip: perhaps 0.5 ms within a data centre, compared with about 100 ns for a memory access. Dijkstra settling a million nodes across shards would spend about 500 seconds waiting on the network. Even batching all of a frontier's lookups per round only helps so much. For a social graph doing BFS to depth 3, this can be tolerable with batching and caching of hot adjacency lists. For road routing it is hopeless.

Why road routing avoids it. Road networks have two properties social graphs lack.

  1. They are small enough. Tens of GB with preprocessing fits in RAM on one large server. So the graph is replicated, not sharded: every routing server holds the whole graph for its coverage area, and any query runs entirely in local memory. Scaling is horizontal by adding replicas, not by partitioning.
  2. They are geographic and nearly planar. Trips are local: most are under 50 km. Natural cuts are small. So when you do partition, partition by region, with each region's graph covering the region plus a margin. Queries inside a region go to that region's servers.

Regional versus continental deployment.

  • Region servers (for example, one per country or metro area with a 50 to 100 km margin) answer the large majority of trips. They have smaller graphs, so they are cheaper to run and faster to rebuild and customise.
  • Continental or world servers hold the full graph (or a coarse overlay plus regional cells, CRP-style) and answer long trips that cross region boundaries.
  • The gateway decides: if both endpoints sit in the same region and their straight-line distance is under a threshold, send the query to the region servers; otherwise send it to continental servers.

When the graph truly must be split: partitioned overlays. CRP's structure points to how distributed routing can work. Each machine holds the detailed cells for its region plus the overlay (the boundary cliques) for everyone else. Because the overlay is small, around a few percent of the graph, every machine can hold all of it. A long query runs locally:

  • detail near the origin (local);
  • the overlay across the middle (local);
  • detail near the destination, which needs one remote call to the destination region's server to finish the last cell and unpack it.

That is two or three network hops per query instead of one per node. Valhalla, an open-source routing engine, takes a related approach and organises its graph into hierarchical geographic tiles that can be loaded on demand. This is also what makes on-device and offline routing practical.

Replicas, load and deployments.

  • 40,000 QPS at peak, at about 10 ms of total CPU per request including alternatives and unpacking, is about 400 cores. Add headroom for spikes and for regional failover to reach around 1,000 to 2,000 cores across regions. With 32 to 64 cores per server, that is a few dozen servers, each holding the graph for its area.
  • Map version rollout is blue-green. Bring up servers with the new graph, warm them with replayed queries, compare their routes with the old version on a sample (catching broken roads and missing turn restrictions), then shift traffic gradually.
  • Metric updates (live traffic) arrive every 30 to 60 seconds. Each server applies the customisation locally (seconds of CPU) or receives precomputed overlay weights from a central customiser, then swaps them in atomically with a pointer swap so that in-flight queries finish on the old metric.

10. Turn-by-turn navigation at scale#

Why the device does the guidance. Voice prompts must fire at the right moment ("in 200 m, turn left") even in tunnels, rural dead zones and congested cells. So the server sends the full route (geometry, steps, lane hints), and the device:

  • snaps GPS to the route at 1 Hz, fused with accelerometer and gyroscope data (dead reckoning through tunnels);
  • advances progress along the route;
  • schedules prompts by distance and speed;
  • detects off-route: for example, a fix more than about 30 to 50 m from the route for several consecutive seconds, or a heading that disagrees with the route direction.

What the server does.

  • Session state: route ID, progress, last ETA and the last few positions, in an in-memory store keyed by session ID with a TTL of a few hours. Any Navigation Service instance can take over after a reconnect.
  • ETA refresh: every 30 to 60 seconds, recompute with fresh speeds for the remaining edges.
  • Proactive re-routing: when a speed delta or incident touches the remaining route, evaluate the alternatives from the current position. Suggest a switch only if it saves more than a threshold (both absolute and relative), to avoid flapping. Some apps switch automatically, and others ask.
  • Reactive re-routing: on an off-route report, compute a new route from the current position and heading. Prefer routes that do not demand an immediate U-turn, since the driver is now moving along a different road.

Connections at scale. With 10 million concurrent sessions, each holding a long-lived connection:

  • Each server holds perhaps 100,000 to 500,000 mostly idle connections (with an event-driven server and tuned kernel limits), so a few dozen to a hundred connection servers globally.
  • Batching: 2.5 million uplink messages per second is fine when spread across that fleet.
  • Downlink messages are rare (ETA updates every 30 to 60 seconds, occasional re-routes), so pushes are cheap.
  • Rebalancing: when a server drains for deployment, clients reconnect to another server with jittered back-off, and the session state lives in the shared store, so nothing is lost.

See Pattern: Pushing Realtime Updates.

Battery and data. GPS at 1 Hz plus screen-on rendering is expensive. Clients reduce the uplink frequency when on a motorway with nothing happening, compress fix batches (delta-encoded integers), and prefetch tiles along the route on Wi-Fi or at the start of the trip. They avoid re-downloading the route geometry on minor ETA updates by sending only numbers.

Safety and stability.

  • Do not re-route constantly.
  • Do not route through roads known to be closed.
  • Treat sudden "faster" alternatives that go through residential streets with suspicion. Some cities and products add penalties to keep through traffic on arterials.
  • When the server is unreachable, keep guiding on the current route, with the ETA computed on the device from historical speeds.

11. Offline maps: packaging, consistency and delta updates#

What a package contains.

  • Vector tiles for the region up to a chosen zoom (often 14 to 15, overzoomed beyond).
  • A routing graph for the region with its own preprocessing (CH or a CRP-style partition) and base speed profiles, so that routes and ETAs work without the network.
  • A search index: places, addresses and a small autocomplete index.
  • Metadata: the map version, the boundary polygon, the style resources needed (fonts, icons) and the licence notices.

Size budget. A large city is roughly 100 to 300 MB, and a medium country 0.5 to 2 GB. Tiles usually dominate, then the search index, then the routing graph. Several techniques shrink it:

  • drop building footprints below a zoom;
  • store a coarse base layer for the surrounding region at low zoom only;
  • use compact graph encodings (variable-length integers and delta-encoded node IDs);
  • ship edge geometry at a lower precision.

Region boundaries.

  • Predefined regions (countries, states and metros) let the CDN cache shared packages. This is far better than custom rectangles, because one blob serves millions of users.
  • Packages for adjacent regions overlap by a margin, so a route that crosses the border slightly still works. Routing across two downloaded packages either stitches their boundary nodes on the device (CRP-style overlays make this natural) or falls back to online routing.

Version consistency. Tiles, graph and index in one package must come from the same map version. Otherwise the route might follow a road the tiles do not show, or the search might return a place the graph cannot reach. Install atomically: download into a new directory, verify every hash, then switch a pointer. When online, the app mixes online services (newer version) with an offline package (older version). Edge IDs differ, so the app must route either fully online or fully offline, never splice the two. Use online traffic only as a speed overlay keyed by stable edge IDs, with a mapping table where needed.

Delta updates. Map data changes slowly: in a month, perhaps a few percent of tiles in a region change. A delta is computed per tile, by content hash, and is the list of changed tiles. Graph and index changes are harder, because preprocessing reorders things, so a small road change can ripple through a CH order. Options:

  • Chunked files with content addressing: split the graph into geographic tiles (Valhalla-style hierarchical tiles) or into CRP cells, so that a change affects only a few chunks.
  • Binary diffs between versions for files that are not chunked.
  • Full replacement when the delta would exceed about half the package.

The client keeps the old version working until the new one is fully installed. Updates are throttled to Wi-Fi and charging by default.

Expiry. Offline data goes stale. Closures, new roads and business changes accumulate. Products prompt for an update after a period (for example, a month) and may expire packages after a longer period, because licensing and correctness both argue against serving year-old data.

Offline search and routing on the device.

  • Search runs over a compact local index (prefix tries or a small inverted index, with on-device ranking by distance).
  • Routing runs a CH or bidirectional A* query in a few milliseconds to tens of milliseconds on a phone. That is fast enough, because the graph is regional and memory-mapped from flash.
  • Without live traffic, ETA uses historical profiles. It is less accurate, so the app labels it as such.

12. The map-data pipeline: from sources to a versioned map#

Every serving system above reads a map version, so the pipeline that builds it is the foundation of correctness.

Sources.

  • Open data (OpenStreetMap is the best-known global open map, edited by volunteers).
  • Licensed data from mapping vendors and governments (road networks, address registries, postcodes, administrative boundaries).
  • Imagery (satellite, aerial and street-level) from which features such as buildings, lane markings and signs are extracted, increasingly with machine learning.
  • Probe-derived signals: new roads appear as dense clusters of GPS traces where the map has no road, and turn restrictions show up as turns that nobody makes.
  • User edits and reports.
  • Business listings.

Conflation. Merge overlapping sources into one consistent graph. Match the same road across sources (a geometric and attribute match), choose the best attribute per field (the name from source A, the speed limit from B), resolve conflicts, and keep provenance per attribute so later fixes can be traced.

Validation. Run automated checks before a version ships:

  • Topology: disconnected islands of road, dangling edges, one-way streets that trap cars (a node you can enter but never leave).
  • Attributes: impossible speed limits, motorways without access ramps.
  • Regressions: compute a large set of golden routes and compare them with the previous version. If a common trip suddenly becomes 30 percent longer, a road was probably broken. Also replay recent real trips and check that their matched paths still exist.
  • Rendering: sample tiles and compare them visually, for example by image diffing of low-zoom renders.

Versioning and rollout.

  • A version is an immutable snapshot with an ID.
  • Builders produce tiles, the graph, indexes and packages for that version.
  • Each serving system rolls it out progressively (canary regions first), and every system can roll back to the previous version by switching a pointer.
  • Cadence: global rebuilds might run weekly, while regional or incremental builds run daily.

Fast path for urgent changes. A bridge closing today cannot wait for a weekly build. So there is a live overlay: a small set of patches (closures, temporary restrictions, new speed limits) applied on top of the current version.

  • Routing applies closures by setting edge weights to infinity in the next customisation, which takes seconds with CRP.
  • Traffic tiles show the closure icon.
  • The next full build incorporates the change permanently.

This mirrors a common pattern: an immutable base plus a mutable delta layer that is periodically compacted into the base.

Stable IDs. As discussed in the data model, edges keep their IDs across versions wherever the underlying road is unchanged. This keeps traffic history, ETA models and user reports attached to the right road.

Bottlenecks and Failure Modes#

Failure / hotspotImpactMitigation
New map version flips all tile URLs at onceMassive CDN miss storm, origin overload, slow maps worldwidePre-warm low zooms and city cores, origin shield, gradual client rollout of the new style version
Routing preprocessing baked to stale weightsRoutes ignore current jams; ETAs wrongCRP or customisable CH with customisation every 30 to 60 s; time-dependent evaluation of the final route
Plain Dijkstra on continental graphSeconds per query, thousands of extra coresPreprocessing (CH, CRP), bidirectional search, regional graphs
Graph traversal across shardsOne network hop per node expansion, unusable latencyReplicate whole regional graphs in RAM; partitioned overlays with at most a hop or two
Noisy GPS in urban canyonsWrong road matched, bogus speeds, ghost jamsHMM map matching with heading, fixed-lag Viterbi, robust aggregation, minimum probe counts
Sparse probes on minor roadsNo live data; stale or missing speedsConfidence-weighted blend with historical profiles; spatial imputation; posted-speed fallback
Road closed but no probes on itRouter keeps sending cars into a closed roadAbsence-of-traffic detection, user reports with verification, official feeds, live overlay closures
Everyone sent to the same "clear" detourDetour jams; predictions self-defeatingRe-route thresholds, load-aware spreading across near-equal alternatives, fast feedback from probes
Probe ingest spike (holiday exodus, outage recovery)Kafka lag, stale trafficPartition by geo cell with headroom, autoscale matchers, shed low-priority background probes first
Navigation connection servers drain or crashMillions of reconnects, thundering herdJittered back-off, shared session store, device keeps guiding offline during reconnect
Bad map data release (broken bridge, missing turn ban)Wrong or dangerous routes at scaleGolden-route diffs, canary regions, instant pointer rollback, live overlay hotfixes
Geocoder ambiguity ("Springfield", "Main St")Wrong destination, user drives to wrong cityLocation bias, hierarchy consistency, show disambiguation, confidence threshold before auto-select

What Interviewers Expect#

Mid-level:

  • Splits the product into tiles, search, routing, traffic and navigation.
  • Knows that tiles are precomputed and served from a CDN with z/x/y addressing.
  • Models the road network as a weighted graph and names Dijkstra and A*.
  • Proposes phones sending GPS to build traffic, with a stream pipeline.
  • Has reasonable APIs for routes and navigation, and does rough capacity maths for tiles and routes.

Senior:

  • Explains why Dijkstra is too slow at continental scale, quantifying the settled nodes and time.
  • Describes contraction hierarchies (shortcuts, upward search, unpacking) and the conflict between preprocessing and live traffic.
  • Knows that GPS must be map-matched, not nearest-snapped.
  • Blends live and historical speeds.
  • Designs vector tiles with versioned immutable URLs and overzoom.
  • Puts guidance on the device for robustness.
  • Discusses offline packages and version consistency.
  • Handles closures and re-route stability.

Staff+:

  • Chooses CRP or customisable CH for live traffic, explaining the metric-independent partition versus fast customisation, turn costs, time-dependence (FIFO) and alternatives.
  • Explains HMM map matching (emission and transition models, Viterbi, fixed-lag).
  • Designs ETA as a routing estimate plus a learned residual, with a calibration and tail focus.
  • Argues replicating the graph rather than sharding it, and explains why cross-shard traversal fails while partitioned overlays work.
  • Treats the map-data pipeline (conflation, validation with golden routes, versioning, rollback, live overlay) as a first-class system.
  • Covers privacy of location data.
  • Talks about feedback loops and load-aware routing, and about measuring quality in production.
Deep Dive: A* with a consistent heuristic in TypeScriptShow

A compact A* over a compressed adjacency layout. Passing h = () => 0 turns it into Dijkstra. The heuristic below is straight-line distance divided by the network's maximum speed, which is consistent for travel-time weights.

type Graph = { offsets: Int32Array; targets: Int32Array; timeDs: Int32Array; lat: Float64Array; lng: Float64Array };
 
function haversineM(a: number, b: number, c: number, d: number): number {
  const R = 6371000, toR = Math.PI / 180;
  const dLat = (c - a) * toR, dLng = (d - b) * toR;
  const s = Math.sin(dLat / 2) ** 2 + Math.cos(a * toR) * Math.cos(c * toR) * Math.sin(dLng / 2) ** 2;
  return 2 * R * Math.asin(Math.sqrt(s));
}
 
function aStar(g: Graph, s: number, t: number, vmaxMps = 36): number {
  // h in deciseconds: straight-line metres / max speed, never an overestimate
  const h = (v: number) => (10 * haversineM(g.lat[v], g.lng[v], g.lat[t], g.lng[t])) / vmaxMps;
  const dist = new Map<number, number>([[s, 0]]);
  const heap = new MinHeap<number>();          // keyed by dist + h
  heap.push(s, h(s));
  const settled = new Set<number>();
  while (!heap.isEmpty()) {
    const u = heap.pop()!;
    if (settled.has(u)) continue;               // lazy deletion of stale entries
    if (u === t) return dist.get(t)!;
    settled.add(u);
    const du = dist.get(u)!;
    for (let e = g.offsets[u]; e < g.offsets[u + 1]; e++) {
      const v = g.targets[e], nd = du + g.timeDs[e];
      if (nd < (dist.get(v) ?? Infinity)) { dist.set(v, nd); heap.push(v, nd + h(v)); }
    }
  }
  return Infinity;
}

Two production details. First, lazy deletion: pushing duplicates and skipping already-settled nodes is simpler and usually faster than a heap with decrease-key. Second, the graph is in compressed sparse row form, described in the next deep dive. Real engines also replace the Map with flat arrays, reset per query through a touched-node list, so a query never allocates.

Deep Dive: Memory layout of the road graphShow

Routing is memory-bound: most of a query's time is spent waiting for cache misses. Layout matters as much as the algorithm.

Compressed sparse row (CSR). Store three flat arrays:

  • offsets[V+1]: the outgoing edges of node u are at positions offsets[u] up to (but not including) offsets[u+1];
  • targets[E];
  • weights[E].

At 4 bytes per entry, 1 billion edges cost 8 GB for targets and weights, and 500 million nodes cost 2 GB for offsets. There are no pointers and no per-object overhead; a naive object-per-edge representation in a managed language could easily be 5 to 10 times larger.

Node ordering for locality. If node IDs are assigned in random order, neighbouring junctions sit far apart in memory and every relaxation is a cache miss of around 100 ns. Renumbering nodes along a space-filling curve (Hilbert or Z-order) puts geographically close nodes close in memory, so a search exploring a neighbourhood touches a few cache lines repeatedly. For CH, ordering by rank groups the top of the hierarchy, which every long query touches, into a small hot region that stays in cache. Reordering commonly gives speedups of around 2x or more on the same algorithm.

Separate hot and cold data. The search touches only targets, weights and a few flag bits. Names, geometry, speed profiles and lane data are needed only for the final path. Keep them in separate arrays indexed by edge ID, which keeps the hot arrays small. Geometry is stored as delta-encoded, quantised coordinates, which are typically 2 to 4 bytes per vertex instead of 16.

Memory-mapping. Build the graph files once per version and mmap them on routing servers. Start-up is then instant (pages load on demand), many processes share one copy in the page cache, and blue-green swaps only need to map a new file. On phones, the same trick lets offline routing work without loading a 300 MB graph into RAM.

Weight width. Travel time in deciseconds fits in 32 bits trivially (over 6 years), while 16 bits covers about 109 minutes. That is enough for most single edges, but shortcuts can exceed it, so engines use 32 bits for shortcut weights and sometimes 16 bits for base edges.

Deep Dive: Tile maths and Viterbi, worked numericallyShow

Latitude and longitude to a tile. For London (51.5072° N, 0.1276° W) at zoom 15:

  • n = 2^15 = 32,768.
  • x = (lng + 180) / 360 × n = (179.8724 / 360) × 32,768 ≈ 16,372.4, so x = 16,372.
  • y = (1 − ln(tan φ + sec φ) / π) / 2 × n. With φ = 51.5072° in radians, ln(tan φ + sec φ) ≈ 1.051, so y ≈ (1 − 0.3346) / 2 × 32,768 ≈ 10,896.2, so y = 10,896.
  • The tile is 15/16372/10896. The fractional parts (0.39, 0.23) say where inside the tile the point lies, which is useful for picking neighbouring tiles to prefetch.
  • Ground resolution: 156,543 × cos(51.5°) / 2^15 ≈ 2.97 m per pixel for 256-pixel tiles.

Viterbi on the motorway / service road example. Use log-probabilities. Take σ = 5 m and emission log p = −0.5 × (d / σ)². Take β = 5 m and transition log p = −|route − straight| / β.

PointDistance to motorwayEmission (M)Distance to service roadEmission (S)
15 m−0.5020 m−8.00
218 m−6.487 m−0.98
34 m−0.3221 m−8.82

For transitions, staying on the same road differs from the straight-line distance by about 2 m, giving −0.4. Switching between the roads needs about a 1.5 km route to explain 30 m of movement, giving about −294.

  • Path M, M, M: −0.50 − 0.4 − 6.48 − 0.4 − 0.32 = −8.10.
  • Path S, S, S: −8.00 − 0.4 − 0.98 − 0.4 − 8.82 = −18.60.
  • Any path that switches roads: below −290.

Viterbi chooses M, M, M. The bad fix at point 2 is absorbed by the transition model. This is exactly the advantage over per-point snapping, which would have picked S at point 2.

Deep Dive: Instruction generation and lane guidanceShow

Turning an edge sequence into instructions people can follow is a substantial piece of logic.

Manoeuvre detection. Walk the path and, at each junction, compare the entry and exit bearings. The angle classifies the manoeuvre:

  • straight: under about 20 degrees;
  • slight turn;
  • turn;
  • sharp turn;
  • U-turn.

Only emit an instruction where the driver must decide. Continuing straight along the same named road through a junction with no other sensible option needs no prompt. A road whose name changes mid-way should usually say "continue onto", or nothing at all.

Naming and references. Use the exit road's name or reference ("A40", "I-280 N"), plus signposted destinations from motorway signs where available ("towards Oxford"). For roundabouts, count the exits and say "take the third exit". Exits are counted only for roads you are allowed to take, according to the local convention.

Lane guidance. For motorway splits and complex urban junctions, the data may include lane counts and per-lane turn arrows. The engine looks ahead to the next manoeuvre too: "keep left" now, because in 400 m you must turn left, even if the current fork alone could use either lane. This look-ahead is what makes lane guidance feel smart rather than literal.

Timing of prompts. Distance-based thresholds are scaled by speed: on a motorway at 110 km/h, prompt at 2 km, 1 km and 400 m; in a city at 30 km/h, prompt at 300 m and 50 m. Merge prompts for manoeuvres that come in quick succession ("turn left, then immediately turn right").

Localisation. Instructions are generated as structured data (manoeuvre type, road name, exit number, distance) on the server, and rendered into words and speech on the device in the user's language. That keeps the payload small and multilingual, and lets offline routing reuse the same templates.

Deep Dive: Real systems and what is publicly knownShow
  • Google Maps:
    • Uses vector rendering on its clients.
    • Combines aggregated location data from users who opt in with historical patterns for traffic.
    • Its DeepMind collaboration on GNN-based ETA was published at CIKM 2021.
    • The internals of its routing engine are not public in detail, so avoid claiming a specific algorithm for it.
  • Waze: known for crowdsourced incident reports and community map editing; acquired by Google in 2013.
  • Bing Maps: Customisable Route Planning came from Microsoft Research, and was reported as the basis of Bing Maps' routing.
  • OSRM (Open Source Routing Machine): offers two modes: CH for the fastest queries on static weights, and MLD, a multi-level partition in the CRP style that supports fast weight updates. It also has an HMM-based map-matching service.
  • GraphHopper: an open-source engine with CH, landmark-based (ALT-style) and flexible modes.
  • Valhalla: an open-source engine with hierarchical, geographically tiled graphs, dynamic costing at query time, and map matching. It is suited to offline and on-device use.
  • OpenStreetMap: the largest open global map dataset. Many tile, geocoding (for example Nominatim) and routing stacks are built on it.
  • Research benchmarks: much of the routing literature evaluates on road graphs of Western Europe and the United States, for example those from the 9th DIMACS Implementation Challenge on shortest paths (2006). That is why the figures above refer to continental graphs of tens of millions of nodes.

When you discuss real systems in an interview, say what is public and label everything else as your own design choice.

Deep Dive: Failure walkthroughsShow

1. The traffic pipeline stalls for 10 minutes.

  • Live speeds stop updating.
  • The routing customiser keeps serving the last snapshot, decaying live deviations towards historical values as they age. Ten-minute-old traffic is still informative; an hour-old jam is not.
  • ETAs become less accurate, but routing keeps working.
  • Alerts fire on freshness (the age of the last published snapshot), not just on errors.
  • After recovery, matchers catch up on the Kafka backlog. Data older than the window is dropped for live purposes but kept for history.

2. A bad map version breaks a motorway junction.

  • Golden-route diffs should catch it before rollout. If it slips through, canary regions show a spike in "route much longer than yesterday" and in off-route events at that junction.
  • Mitigation: roll the region back to the previous version by switching a pointer. Because tiles, graph and index are versioned together, the rollback is consistent.
  • Short-term hotfix: use the live overlay.

3. A CDN region degrades.

  • Tiles load slowly in one geography. Clients keep showing cached tiles. Navigation continues, because the route geometry and the guidance are on the device.
  • Multi-CDN or DNS-based failover moves traffic to another provider or region.
  • Traffic tiles, which are short-lived, are the first casualty, so the app hides the traffic layer rather than showing stale colours.

4. A routing region loses half its servers.

  • The gateway sheds load: it disables alternatives, which cuts CPU per request by 2 to 3 times, and sends overflow to continental servers, which can answer regional queries too.
  • Re-routes for active navigation sessions are prioritised over new route requests.
  • Devices with offline packages route locally.

5. A stadium event ends.

  • 50,000 people request routes from one spot at once.
  • Routes are cheap, so CPU is fine, but every route takes the same exit roads, which instantly jam. ETA models without event awareness are optimistic.
  • Mitigations: event-aware historical profiles, faster live blending near venues, and spreading users across alternatives.
Deep Dive: Observability and quality metricsShow

Serving health.

  • Tile p50 and p99 latency, and CDN hit ratio by zoom and region.
  • Route latency by distance band.
  • Navigation connection counts and reconnect rate.
  • Geocoder latency.

Freshness.

  • Age of the latest live-speed snapshot.
  • Kafka consumer lag per geo partition.
  • Customisation duration.
  • Time from closure report to routing effect.

Quality, the metrics that actually matter.

  • ETA error: MAPE, and the share of trips more than 20 percent late, per region and time band.
  • Route acceptance and deviation: how often users leave the suggested route in the first few minutes. A spike at one junction usually means bad data.
  • Re-route rate per trip: too high means flapping.
  • Geocoding success: whether the user picks the first result, and the rate of searches immediately refined.
  • Map-matching confidence: the share of traces that need splitting.
  • Traffic accuracy: predicted versus observed traversal times on held-out probes.

Dashboards by geography. Map products fail locally. A national average hides a broken city. Every key metric is sliced by region, and alerts compare against the same region's own baseline.

See Observability: Logs, Metrics and Traces.

Deep Dive: A 45-minute interview planShow
  1. Minutes 0 to 5: scope (tiles, search, routing with ETA, traffic, navigation, offline) and state the scale.
  2. Minutes 5 to 10: quick estimates (tiles at millions per second at the edge, about 40,000 routes per second, about 10 million fixes per second), and observe that each subsystem has a different bottleneck.
  3. Minutes 10 to 20: the full HLD: the map pipeline producing versioned artefacts, the CDN for tiles, the Routing Service, the probe pipeline, the Navigation Service and the geocoder.
  4. Minutes 20 to 35: go deep on routing. The ladder Dijkstra, bidirectional, A*, ALT, then CH, with numbers, then the live-traffic conflict and CRP. Briefly cover turn costs, time dependence and alternatives.
  5. Minutes 35 to 40: the traffic pipeline: HMM map matching, aggregation, the historical blend, closures, privacy.
  6. Minutes 40 to 45: navigation on the device, offline packages with version consistency, failure modes and rollback.

If the interviewer steers towards ETA, swap step 5 for the residual-model and GNN discussion. If they steer towards tiles, cover generalisation, overzoom and CDN pre-warming.

Deep Dive: Variants and extensionsShow
  • Public transit. Transit is a timetable problem, not a road graph with static weights. Algorithms such as RAPTOR (Daniel Delling, Thomas Pajor and Renato Werneck, "Round-Based Public Transit Routing", 2012) work in rounds, where round k finds the best arrivals using k trips, and naturally produce Pareto sets of arrival time versus number of transfers. Connection-scan algorithms are another family. The walking legs to and from stops use the pedestrian graph.
  • Electric vehicles. The route must keep the state of charge above zero. Energy use depends on speed, elevation and temperature, and regenerative braking makes downhill edges negative energy. That breaks plain Dijkstra's assumptions and needs potential-shifting or constrained search. Charging stops add a choice of where and how long to charge.
  • Trucks. Height, weight and hazmat restrictions, plus different speeds. With CRP this is another customisation over the same partition.
  • Cycling and walking. Elevation, surface, safety (bike lanes), stairs and accessibility. The costs are multi-criteria and often user-tuned.
  • Ride-hailing and delivery. Massive many-to-many distance tables (many drivers to many riders) are needed for matching. CH-based algorithms compute one-to-many and many-to-many tables efficiently, by sharing the upward search spaces (bucket-based methods), instead of running one query per pair.
  • Fleet route optimisation. Vehicle routing problems with time windows sit on top of these distance tables. They are NP-hard and solved heuristically.
  • Indoor and campus maps. Multi-level graphs, with positioning from Wi-Fi or beacons instead of GPS.

Key Takeaways#

  • Several systems share one map. Tiles are a CDN problem, routing is a precomputed-graph problem, traffic is a stream problem, and geocoding is a search problem. They connect through an immutable, versioned map-data build.
  • Vector tiles with versioned immutable URLs give tiny payloads, on-device styling and rotation, overzoom beyond zoom 14 to 16, and cache-forever CDN behaviour without purges.
  • Plain Dijkstra is thousands of times too slow on continental graphs. Bidirectional search, A* and landmarks help. Hierarchical preprocessing (contraction hierarchies) brings queries down to around a millisecond.
  • Live traffic conflicts with baked-in preprocessing. CRP or customisable CH separate a metric-independent partition from a seconds-long customisation. Turn costs, time-dependent evaluation and alternatives complete the router.
  • GPS must be map-matched, not snapped. An HMM (Gaussian emissions, route-versus-straight-line transitions, Viterbi with fixed lag) turns noisy traces into edge traversal speeds. Robust aggregation, confidence-weighted historical blending and closure detection produce the live speed table.
  • ETA is a routing estimate plus a learned correction, judged by its tail errors, not only by the average.
  • Replicate the road graph; do not shard the traversal. Cross-shard hops per node expansion are fatal. Regional replicas and partitioned overlays keep queries local.
  • Guidance runs on the device, with the server handling ETA refresh and re-routing, so navigation survives dead zones.
  • Offline packages bundle tiles, the graph and the index from one map version, install atomically and update by deltas.
  • Map quality is a pipeline problem: conflation, validation with golden routes, canary rollout, instant rollback and a live overlay for urgent closures.