Skip to content

Design a Ride-Hailing App (Uber)

Advanced 54 min read Part 17 of 18

Design Uber: high-rate driver location ingestion, geospatial indexes, matching with driver locks, ETA, the trip state machine and consistent assignment.

The Problem#

A rider opens an app, types a destination, sees a price, and taps "Request". Within seconds a car a few streets away is assigned, its icon starts moving on the map, and a few minutes later it pulls up at the kerb. Behind that simple experience is one of the most demanding real-time systems in consumer software. Uber, Lyft, Grab, Didi, Ola and Bolt all solve the same core problem: connect a person who needs a ride with a nearby driver who is free, quickly, fairly and without ever assigning one driver to two riders at the same time.

What makes ride-hailing different from most web applications is that the main data is moving. Millions of drivers report a new GPS position every few seconds. Each position is stale almost as soon as it is written. The question the system asks most often, "which available drivers are near this point right now?", is a spatial query over data that changes millions of times per second. Then, once a candidate driver is chosen, the system must run a small human-in-the-loop workflow: offer the ride, wait up to about 10 seconds for the driver to accept, and move on to the next driver if they decline or ignore it, all while guaranteeing that the driver is not offered a second ride at the same time.

Three big ideas carry most of the design:

  1. Location as a stream, not a table. Driver positions are written to an in-memory geospatial index (Redis GEO, or an in-process grid of H3 or S2 cells), not to a relational database row per update. Durability barely matters because the next update arrives in seconds.
  2. Matching as a contention problem. Assigning a driver is like selling a concert seat: two requests must never win the same driver. Locks with timeouts (TTL), conditional updates and a single source of truth for driver status give the needed strong consistency.
  3. Dispatch as a durable workflow. "Offer, wait, time out, try the next driver" survives crashes only if the state lives somewhere durable, for example in a queue with committed offsets, a delay queue, or a durable-execution engine such as Temporal. Temporal descends from Cadence, which Uber itself built and open-sourced.

Around these sit fare estimation, ETA prediction, the trip lifecycle, real-time updates to the rider's map, payments, surge pricing and the geography-based sharding that lets the system scale city by city.

Analogy. Think of an old-fashioned taxi dispatch office with a giant city map on the wall. Each taxi radios in its position every few seconds, and an assistant moves a magnet on the map (the location index). When a customer calls, the dispatcher looks at the magnets near the caller (the proximity query), picks the closest free taxi, and radios it: "pickup at Main and 5th, do you take it?" While waiting for an answer, the dispatcher flips that magnet to red so no other dispatcher offers it a second job (the driver lock). If no answer comes within 10 seconds, the magnet flips back to green and the dispatcher calls the next taxi (timeout and fallback). Once the driver accepts, a ticket is written in the logbook (the trip record) and updated at each step: driver en route, passenger picked up, trip finished, fare paid (the trip state machine). A big city needs many dispatchers, each responsible for one district map (geo-sharding). Taxis near the edge of a district must show up on the neighbour's map as well (boundary queries).

This problem is popular at senior and staff level because it combines:

  • Write-heavy ingestion of a fast-changing stream (millions of updates per second).
  • Spatial indexing with real trade-offs: geohash versus quadtree versus hexagonal grids, and in-memory versus durable stores.
  • Strong consistency for one narrow piece of state (driver assignment) inside an otherwise eventually consistent system.
  • Long-running, human-in-the-loop workflows that must survive crashes.
  • Geographic partitioning, hotspots such as a stadium emptying, and the boundary problem between partitions.

Clarifying Questions#

QuestionWhy it mattersAssumed answer
Which core flows are in scope?Bounds the design.Fare estimate, ride request, matching to a nearby available driver, driver accept or decline, navigation to pickup and drop-off, trip tracking.
How many drivers and riders?Sizes location ingestion and matching.Global service; up to about 10 million registered drivers and around 2 to 3 million online at the global peak; about 30 million trips per day.
How often do drivers report location?Dominant write load.About every 4 to 5 seconds while online, adaptive by speed and status.
How fast must a match happen?Latency budget for the matching loop.A match, or a clear failure, within 1 minute; first offer to a driver typically within 1 to 2 seconds of the request.
Can a driver get two offers at once?Defines the consistency requirement.No. A driver gets at most one outstanding offer, and a ride is offered to one driver at a time.
What is the acceptance window?Drives lock and timeout design.10 seconds; then move on to the next driver.
How bursty is demand?Hotspot handling.Very: a concert or stadium can produce tens of thousands of requests from one small area within minutes, and up to about 100,000 requests from one location at a big event.
Ride types (X, XL, Comfort), pooling, scheduled rides?Expands matching.Out of scope for the core; discussed as extensions.
Ratings, tipping, chat?Peripheral features.Out of scope.
Who computes routes and maps?Build versus buy.Assume a routing and ETA service exists (third-party maps API or in-house engine); we discuss how it works in a deep dive.
Payments?Integration boundary.Hand off to a payment service; we cover the hold-and-capture flow briefly.

Requirements#

Functional requirements#

  1. Fare estimate. A rider enters a pickup point and a destination and gets an estimated fare and ETA.
  2. Request a ride. The rider requests a ride based on that estimate.
  3. Match. The system matches the request with a nearby, available driver.
  4. Accept or decline. The driver can accept or decline; on acceptance they navigate to the pickup and then to the drop-off.
  5. Track. Both sides see the trip's status and the driver's live position until the trip ends.

Below the line (out of scope, mentioned to show product thinking): rating drivers and riders after a trip; scheduling rides in advance; ride categories (economy, large, premium); shared or pooled rides; in-app chat and calling; driver earnings and payouts; safety features such as trip sharing.

Non-functional requirements#

  1. Low-latency matching. Match within 1 minute or report failure; the proximity query itself should take tens of milliseconds.
  2. Strong consistency of assignment. No driver is ever assigned to two rides at once, and no ride is ever assigned to two drivers.
  3. High throughput and burst handling. Millions of location updates per second globally, and sudden demand spikes concentrated in one small area.
  4. High availability. A ride request must not be silently dropped, even if a matching instance crashes. Rider-facing availability of 99.99 percent for request and trip flows.
  5. Freshness. Driver positions used for matching should be at most a few seconds old.

Below the line: GDPR-style privacy and data residency, full monitoring and alerting, zero-downtime deploys. These are real concerns and we touch on them, but they do not drive the core design.

A useful framing for the interviewer: the location system needs high throughput and can tolerate a little loss and staleness; the assignment system needs strong consistency and can tolerate a little latency. Designing each part for its own needs, rather than one database for everything, is the heart of a good answer.

Capacity Estimation#

The numbers below are design assumptions chosen to be realistic for a global ride-hailing company. They are not any company's published figures. See Back-of-the-Envelope Estimation for the method.

Drivers and location updates.

  • Registered drivers: about 10 million. Online at the global peak: about 2.5 million.
  • Update interval: about every 4 seconds. 2.5 million ÷ 4 = about 625,000 location updates per second at peak.
  • A common interview simplification is "10 million drivers every 5 seconds = 2 million updates per second". That is a useful worst case: it shows that no general-purpose database will absorb this write rate cheaply. At on-demand DynamoDB pricing, for example, 2 million small writes per second would cost on the order of hundreds of thousands of dollars a day.
  • Payload: driver id, latitude, longitude, heading, speed, accuracy, client timestamp and status come to about 100 bytes of useful data, or about 200 to 300 bytes with protocol framing. Ingest bandwidth at 625,000 per second is about 62 MB/s of payload, roughly 150 MB/s on the wire. That is manageable if spread across a few hundred connection servers.

The live location index.

  • 2.5 million drivers × about 100 bytes per entry in an in-memory geo index, plus about 200 bytes of status and metadata, is under 1 GB in total.
  • Memory is not the constraint. Throughput is: a single Redis node handles very roughly 100,000 to 200,000 simple commands per second.
  • So 625,000 updates per second needs several shards, which geography supplies naturally: each city or region has its own index.

Location history.

  • Average online drivers are lower than the peak, say 1.2 million. 1.2 million ÷ 4 s × 86,400 s ≈ 26 billion points per day.
  • At 100 bytes raw that is about 2.6 TB per day. Columnar compression of delta-encoded coordinates and timestamps typically gives 5 to 10 times, so roughly 300 to 500 GB per day.
  • History feeds the trip record (the actual route for fare calculation), ETA model training, safety investigations and analytics. It belongs in a log and object storage, not in the matching path.

Trips.

  • About 30 million trips per day is about 350 per second on average. Peaks run 3 to 4 times higher, so roughly 1,000 to 1,500 ride requests per second globally.
  • A large city at rush hour might see 50 to 200 requests per second.
  • At a stadium event, 100,000 requests over 15 to 30 minutes is about 50 to 100 requests per second from one square kilometre. That is a hotspot, not a throughput problem in aggregate.

Fare estimates.

  • Riders check prices several times per trip and many never book: about 5 to 10 estimates per trip.
  • That is 150 to 300 million per day, about 2,000 to 3,500 per second on average and 10,000 per second at peak.
  • Each estimate needs a route and ETA computation, so the routing service must be sized for this, not for trips.

Proximity queries.

  • Matching itself generates only a few queries per request: 1,500 per second × perhaps 3 radius expansions = a few thousand per second.
  • The hidden giant is the "cars near me" view in open rider apps. 5 million open apps refreshing every 5 seconds would be 1 million queries per second.
  • Serve that from a coarse, cached, per-cell snapshot rather than exact queries (Deep Dive 2).

Live tracking fan-out.

  • Concurrent trips ≈ trips per day × average trip duration including pickup ÷ minutes per day = 30 million × 20 ÷ 1,440 ≈ 420,000 on average, and up to about 1 million at peak.
  • Each driver update in an active trip is pushed to one rider: up to about 250,000 pushes per second.

Trip state writes.

  • Each trip has about 10 state changes (requested, offered, accepted, arrived, started, completed, paid, plus retries and offers).
  • 30 million × 10 = 300 million per day, about 3,500 per second on average and about 12,000 at peak. A sharded relational or wide-column store handles this easily.
QuantityEstimate
Online drivers (global peak)2.5 million
Location updatesabout 625,000 per second (2 million worst case)
Live index memoryunder 1 GB in total
Location historyabout 26 billion points per day, about 2.6 TB raw
Ride requestsabout 1,000 to 1,500 per second at peak
Fare estimatesabout 10,000 per second at peak
"Cars nearby" viewsup to about 1 million per second if done naively
Concurrent tripsabout 1 million at peak
Trip state writesabout 12,000 per second at peak

The conclusion shapes the whole design. Location is a high-rate stream that needs an in-memory index. Trips are a modest-rate workload that needs strong consistency. Fare and ETA are a compute-heavy read workload. Three different storage and scaling strategies follow.

Core Entities#

  • Rider: a user who requests rides. Profile, contact details, payment methods and rating.
  • Driver: a user who provides rides. Profile, licence, vehicle, rating, and a status (offline, available, offered, on trip). The status is the field whose consistency matters most.
  • Vehicle: make, model, plate, capacity and category. Belongs to a driver.
  • Fare (quote): an estimate for a pickup and destination at a point in time: price, currency, ETA, surge multiplier, expiry. Created by the fare-estimate call and referenced by the ride request, so the client can never submit its own price.
  • Ride (trip): one journey from request to payment. Rider, driver, fare, pickup, destination, status, timestamps, actual route, final price.
  • Offer (dispatch attempt): a ride offered to one specific driver, with a deadline and an outcome (accepted, declined, expired). A ride may have several offers.
  • Location: the latest position of a driver (latitude, longitude, heading, speed, timestamp), plus a history stream.

API Design#

All calls are authenticated. The rider or driver identity comes from the session token, never from the request body. Timestamps that matter are generated by the server, and prices are read from stored fare quotes, never accepted from the client. Passing a user id, a fare amount or a trusted timestamp in the body is a common red flag in interviews, because any client can be modified. See API Design Best Practices.

Rider APIs.

POST /v1/fares
  body: { pickup: {lat, lng}, destination: {lat, lng}, rideType: "standard" }
  -> 201 { fareId, price, currency, surgeMultiplier, pickupEtaSeconds,
           tripDurationSeconds, expiresAt }

POST /v1/rides                      Idempotency-Key: <uuid>
  body: { fareId }
  -> 201 { rideId, status: "requested" }

GET  /v1/rides/{rideId}
  -> 200 { rideId, status, driver?, vehicle?, driverLocation?, etaSeconds?, fare }

POST /v1/rides/{rideId}/cancel
  -> 200 { status: "cancelled", cancellationFee? }
  • POST /v1/fares is a POST because it creates a stored quote. The server records it with a short expiry, typically a few minutes. The later ride request references it by id, which locks in the quoted price and blocks tampering.
  • POST /v1/rides takes an idempotency key, so a retry after a flaky network does not create two rides. See Idempotency and Safe Retries.

Driver APIs.

POST  /v1/drivers/me/status      body: { status: "available" | "offline" }
POST  /v1/drivers/me/locations   body: { points: [ {lat, lng, heading, speed,
                                         accuracy, clientTs} ] }
PATCH /v1/rides/{rideId}         body: { offerId, action: "accept" | "decline" }
POST  /v1/rides/{rideId}/events  body: { type: "arrived" | "started" | "completed" }
  • Locations accept a small batch of points, so the client can buffer during brief connectivity loss and the server can reconstruct the route. In practice these travel over a persistent connection rather than as separate HTTPS requests (Deep Dive 1).
  • Accept and decline carry the offerId, so a late response to an expired offer is recognised and rejected rather than mistaken for an answer to a newer offer.

Real-time channel. Both apps hold a persistent connection, a WebSocket or HTTP/2 stream, to a connection gateway:

  • Drivers receive offers on it, with mobile push notifications (APNs on iOS, FCM on Android) as a fallback when the app is in the background.
  • Riders receive status changes and driver positions on it.

See Polling, Long Polling, SSE, WebSockets and Webhooks and Pattern: Pushing Realtime Updates.

High-Level Design#

We build the design one functional requirement at a time. Then we harden it against the non-functional requirements in the deep dives.

1. Fare estimate#

The rider's app sends pickup and destination to POST /v1/fares. The API Gateway authenticates the request, applies per-user rate limits and routes it to the Ride Service. The Ride Service:

  1. Asks a Routing and ETA Service for the driving distance and duration. In an interview this can be a third-party maps API; at scale it is usually an in-house engine.
  2. Asks the Pricing Service to apply the pricing model: base fare, per-minute and per-kilometre rates, the surge multiplier for the pickup area, tolls and fees.
  3. Stores a Fare record with an expiry and returns it.

2. Request a ride#

The rider taps "Request". The app sends POST /v1/rides with the fareId and an idempotency key. The Ride Service:

  1. Checks that the fare belongs to this rider and has not expired.
  2. Creates a Ride row with status requested.
  3. Triggers matching.

No new services are needed: the Ride table sits next to the Fare table. The important design choice comes in the next step: how matching is triggered so that a crash cannot lose the request (Deep Dive 9).

3. Match the rider with a nearby, available driver#

Two new pieces appear:

  • Location Service. Receives a continuous stream of driver positions through a connection gateway and keeps the latest position and status of every online driver in a geospatial index.
  • Matching Service. Takes a ride request and asks the Location Service for available drivers near the pickup. It ranks them by pickup ETA and other factors, then starts offering the ride.

The naive version writes each location update to the main database and runs a "within 2 km" query with a full scan or a B-tree on latitude. That fails twice:

  • Write rate. Hundreds of thousands to millions of updates per second overwhelm a general-purpose database, or make it extremely expensive.
  • Query shape. A B-tree on latitude alone narrows the search to a horizontal band of the planet, not a circle. Two-dimensional proximity needs a spatial index.

The fix is an in-memory geospatial index, partitioned by geography (Deep Dives 1 and 2).

4. The driver accepts or declines, then navigates#

The Matching Service sends an offer to the top-ranked driver through a Notification and Push path: the driver's live connection if they have one, and APNs or FCM as a fallback. The driver has about 10 seconds to respond:

  • Accept. PATCH /v1/rides/{id} with action: accept goes to the Ride Service. In a single atomic step it moves the ride to accepted, records the driver, and moves the driver to on trip. The response carries the pickup location, and the driver app starts turn-by-turn navigation using the phone's GPS and a maps SDK.
  • Decline or no answer. The Matching Service moves on to the next driver in the ranked list.

This simple version has two consistency gaps:

  • Two matching instances could offer the same driver two rides at once.
  • A crash during the 10-second wait could leave a ride stuck forever.

We close both gaps with driver locks with TTL (Deep Dive 4) and durable dispatch workflows (Deep Dive 5).

5. Track the trip#

After acceptance, the driver's location updates also flow to a Trip Tracking path. The Location Service publishes each update for drivers on an active trip to a channel keyed by trip id. The rider's connection gateway is subscribed to that channel and pushes each position to the rider's app.

The driver app reports trip events (arrived, started, completed). The Trip Service, part of the Ride Service in small designs, advances the trip state machine and emits events:

  • Payment captures the fare.
  • Notifications tell the rider "your driver has arrived".
  • Analytics stores the record.

Evolving the design#

ConcernBadGoodGreat
Location writesOne database write per updateBatch updates every few seconds into a geospatial database such as PostGISIn-memory geo index (Redis GEO or an in-process H3 grid), latest-value-wins, sharded by region, with history streamed to Kafka
Proximity searchFull scan with distance formulaB-tree on latitude and longitude, or a geospatial databaseCell-based index (geohash, S2 or H3) with ring expansion, then ETA ranking
Update frequencyFixed 1 to 5 s for all driversFixed 5 sAdaptive by speed, status and nearby demand
One offer per driverApplication-level in-memory flagsDatabase status column with timeout handlingAtomic lock with TTL (Redis SET NX PX) plus conditional update of the durable driver and ride rows
No dropped requestsSynchronous, first-come-first-served, no queueQueue between Ride and Matching servicesPartitioned durable queue (Kafka per region) with offsets committed after the match is decided
Driver does not respondIn-memory timerDelay-queue message per offerDurable workflow (Temporal or Step Functions) with timers that survive crashes
Scale and latencyBigger serversRead replicasGeo-sharding of services, queues and data by region, with scatter-gather only at boundaries

The full high-level design#

Components:

  • API Gateway. Authentication, rate limiting, request routing. Riders and drivers each get APIs tuned to their app. See API Gateway and Backend-for-Frontend.
  • Connection gateway. Holds millions of long-lived connections (WebSocket or HTTP/2 streaming) from driver and rider apps. It accepts location streams and pushes offers, status changes and live positions. It is stateless apart from the connection table, which it registers in a fast directory so other services can find which gateway node holds a given user.
  • Location Service. Validates and smooths location updates, updates the in-memory geo index for the driver's region, publishes positions for active trips to the tracking channel, and appends every point to the location log (Kafka) for history and analytics.
  • Geo index per region. Latest position and status of each online driver, indexed by cell for fast proximity queries. Implemented with Redis GEO or a custom in-memory service over H3 or S2 cells.
  • Fare and Pricing Service. Fare estimates from routing results, the pricing model and surge multipliers computed per area from live supply and demand.
  • Routing and ETA Service. Road-network shortest paths with live traffic and a machine-learned correction layer. Serves fare estimates, candidate ranking and rider-facing ETAs.
  • Ride and Trip Service. Owns ride and trip records and the trip state machine. It is the source of truth for assignment: accepting a ride is a transaction here.
  • Dispatch queue. A durable, region-partitioned queue of ride requests, so a request survives a matching-instance crash and surges are buffered.
  • Matching and Dispatch workflows. For each request: find candidates, rank them, lock a driver, offer, wait with a timeout, and repeat. Best run as durable workflows.
  • Lock store. Short-lived driver locks with TTL (Redis), giving fast mutual exclusion over offers. The final assignment is always confirmed by a conditional write in the Ride database.
  • Ride and driver database. Sharded by region, strongly consistent per row: PostgreSQL or MySQL shards, or a distributed SQL database. Holds riders, drivers, vehicles, fares, rides, offers and payments metadata.
  • Event bus. Trip and dispatch events (Kafka) consumed by payments, notifications, receipts, fraud detection, analytics and ML feature pipelines.

Key Flows#

Flow 1: request to match#

The rider gets a 201 as soon as the ride row is durable and the request is in the queue. Everything after that is asynchronous, and the rider's app learns about progress through the live connection. Ranking uses ETA, not straight-line distance. A driver 400 m away on the other side of a river or a motorway can be ten minutes away by road.

Flow 2: offer, accept or time out#

The lock stops two workflows from offering the same driver at once. The conditional update in the Ride Service is the final arbiter: it only succeeds if the ride is still requested (or offered to this offer) and the driver is still free. A driver who taps "accept" one second after the deadline gets a polite "this request is no longer available", because their offerId is no longer current.

Flow 3: trip in progress and live tracking#

The trip state machine#

The driver state machine#

The two machines are linked. Ride Offered → Accepted and driver Offered → OnTrip must happen together, atomically. That is the strong-consistency requirement expressed as state. Deep Dive 7 covers how transitions are enforced.

Data Model#

StoreDataWhy
Ride database: PostgreSQL or MySQL shards by region, or distributed SQL such as CockroachDB or SpannerRiders, drivers, vehicles, fares, rides, offersTransactions and conditional updates for assignment; modest write rate; relational queries for support tools
In-memory geo index: Redis GEO or a custom serviceLatest location and status per online driverHundreds of thousands of updates per second; millisecond proximity queries; loss is tolerable because data refreshes every few seconds
Lock store: RedisDriver locks with TTLFast SET NX PX, automatic expiry
Location log: Kafka, then object storage or a lakehouse in columnar filesEvery location pointDurable, cheap, replayable history for routes, ML and audits
Time-series or wide-column store: Cassandra or a time-series database, optionalRecent per-trip routes for quick lookupFast "route of trip 42" queries without scanning the lake
Event bus: KafkaTrip and dispatch eventsDecouples payments, notifications, analytics

The ride row carries region because everything about a trip happens inside one geography. It is the natural shard key. The version column on rides and drivers supports optimistic concurrency, as Deep Dive 7 shows. See Choosing a Database: A Decision Guide, Data Modeling and Geospatial Indexing and Proximity Search.

Deep Dives#

1. Driver location ingestion at a high write rate#

The problem. Driver location is the highest-volume data in the system: about 625,000 updates per second at peak in our estimate, and 2 million in the worst case. A relational database row per update is the wrong tool. Each update would:

  • write the heap row,
  • update every index on the table, including a spatial index if there is one,
  • append to the write-ahead log,
  • and replicate to followers.

That is several random I/Os per update, at a rate that would take dozens of large database primaries. And the data is worth almost nothing a few seconds later, because a newer position replaces it. Location is a latest-value-wins stream, not a record of truth.

Bad: write every update to the main database. The database melts, or costs a fortune. Proximity queries contend with the write load.

Good: batch updates into a geospatial database. Buffer positions in the Location Service for a few seconds and write them in bulk to a spatial database, for example PostgreSQL with the PostGIS extension and a GiST index. Batching cuts per-write overhead and lock contention. The cost is staleness: a position can be several seconds old before the index sees it, on top of the few seconds between updates. A driver moving at 50 km/h covers about 14 metres per second, so 10 seconds of staleness is about 140 metres. That is enough to pick a driver who has just turned away from the rider.

Great: an in-memory geospatial index, updated in place. Keep only the latest position of each online driver, in memory, indexed by cell:

  • Redis GEO stores each driver as a member of a sorted set whose score is a 52-bit interleaved geohash of the position. GEOADD overwrites the previous position. GEOSEARCH (added in Redis 6.2, replacing GEORADIUS) returns members within a radius or box of a point, optionally sorted by distance and limited to the nearest N.
  • A custom in-process index keys a hash map by H3 or S2 cell id to the set of drivers in that cell. It is updated as drivers move between cells. A single process can apply hundreds of thousands to millions of updates per second this way.

Either way, the index is sharded by geography: one or a few shards per city or region. Each update touches exactly one shard.

Durability is optional, and that is the point. If a Redis node fails and its replica lost the last second of updates, the index self-heals within one update interval (about 4 to 5 seconds) as every online driver reports again. Persistence (append-only file or snapshots) and replicas with automatic failover (Redis Sentinel or Redis Cluster) reduce the gap further. Nothing downstream depends on any single point ever having been stored in the index. Durable history goes to a separate log.

Removing stale drivers. A driver whose app crashes or loses signal stops sending updates. Their last position must not be offered work. Options:

  • A companion sorted set of driver id scored by last-update time. A sweeper runs every few seconds, removes members older than about 30 seconds with ZRANGEBYSCORE, and deletes them from the geo set too.
  • Filter at query time: the index returns candidates plus their last-seen time, and the matcher drops any older than a threshold. Use this as well as cleanup, not instead of it.
  • In a custom index, store the timestamp with each entry and evict lazily during scans.

Transport: persistent connections, not one HTTPS request per update.

  • A new HTTPS request every 4 seconds costs headers, often a TLS handshake after a mobile network change, and a full request cycle at the load balancer.
  • Instead, each driver app holds one long-lived connection to a connection gateway: a WebSocket, an HTTP/2 or gRPC stream, or an MQTT-style protocol. It streams small binary-encoded messages of tens of bytes over it.
  • One gateway node can hold tens of thousands to a few hundred thousand idle-but-open connections, so 2.5 million drivers need on the order of tens of gateway nodes, plus headroom.
  • The same connection carries offers to the driver. That is faster and more reliable than mobile push, which can be delayed by the operating system.

The ingestion pipeline.

  1. The gateway authenticates the connection once at setup, using the driver's token. It then forwards updates to the Location Service partition for the driver's region. Consistent routing by driver id keeps one driver's updates in order.
  2. The Location Service validates each point: is the timestamp plausible, is the accuracy acceptable, is the implied speed since the last point physically possible? It discards out-of-order points. A point is applied only if its client sequence number or timestamp is newer than the stored one, which a small Lua script in Redis can check atomically.
  3. It updates the geo index and the driver's status hash.
  4. If the driver is on a trip, it publishes the point to the trip's tracking channel.
  5. It appends every point to the location log (Kafka, keyed by driver id), asynchronously and in batches. Consumers build trip routes, train ETA models and feed safety and fraud systems.

GPS is noisy.

  • Phone GPS is typically accurate to about 5 to 10 metres under open sky, and much worse in urban canyons between tall buildings, where reflections can put a car 50 metres or more off, sometimes on the wrong street.
  • Smoothing: a Kalman filter (Rudolf Kálmán, 1960) combines the noisy fixes with a motion model (position, speed, heading) to estimate the true track. It is used on the device, the server, or both.
  • Map matching: snapping the trace to the road network, for example with the hidden-Markov-model approach of Newson and Krumm ("Hidden Markov Map Matching Through Noise and Sparseness", ACM SIGSPATIAL GIS 2009). It matters for three things: showing the car on the right road, measuring distance driven for the fare, and computing ETAs from the correct road segment.
  • Teleport detection: a jump that implies 300 km/h is a bad fix, or GPS spoofing (Deep Dive 12), and is dropped.

Adaptive update intervals. A fixed 4-second interval for every driver wastes battery, mobile data and server capacity. The driver app can choose its interval from context:

  • Stationary or crawling (waiting at a pickup hotspot, stopped at a light): every 10 to 30 seconds.
  • Moving fast: every 3 to 5 seconds. Faster still when turning or changing direction often, because that is when positions become wrong fastest.
  • On a trip: every 2 to 4 seconds, so the rider's map looks smooth.
  • Near a pending request, or offered a ride: every 1 to 2 seconds, because matching precision matters right now.
  • Offline or on break: no updates. A heartbeat every minute or so keeps the session alive.

On the server, dead reckoning (extrapolating from the last position, speed and heading) estimates where a driver is between updates. Rider apps animate the car smoothly between points the same way.

Suppose 40 percent of online drivers are idle and stationary and drop from 4-second to 20-second updates. Their load falls by 80 percent, so the total falls by about 32 percent, to about 425,000 updates per second, with little loss of matching quality. The hard part is the algorithm: choosing thresholds, testing them against matching quality, and handling sensor quirks on thousands of phone models. Do not treat the client as a dumb box. Client-side logic is often the cheapest scalability lever, just as chunking and compression on the client are in file-upload systems.

Buffering through tunnels. When connectivity drops, the app keeps recording points locally and uploads them as a batch on reconnection. The live index uses only the newest point; the location log gets the full trace, so the final route and fare stay correct.

2. The geospatial index: geohash, quadtree, S2 and H3#

Why a normal index does not work. A B-tree on (lat, lng) can quickly find rows with latitude between 37.77 and 37.79. That is a thin horizontal band around the whole planet. Within the band it must still scan every longitude. Two separate B-trees, one on latitude and one on longitude, give two huge sets to intersect. Proximity is two-dimensional. It needs an index that keeps nearby points near each other in the index order, or an explicit spatial tree. See Geospatial Indexing and Proximity Search.

Geohash.

  • Alternately bisect longitude and latitude. Each step adds one bit saying which half the point is in.
  • Interleave the bits and encode them in base-32. Each character adds 5 bits, so the cell shrinks by a factor of 32 per character.
  • Approximate cell sizes at the equator:
CharactersCell size (approx.)
439 km × 19.5 km
54.9 km × 4.9 km
61.2 km × 0.61 km
7153 m × 153 m
838 m × 19 m
  • Prefix equals containment: every point in cell 9q8yy has a geohash starting with 9q8yy. A string or integer index therefore doubles as a spatial index.
  • "Drivers near the pickup" becomes: compute the pickup's 6-character cell, look up that cell and its 8 neighbours, then filter by exact distance.
  • The neighbours matter because of the edge problem. Two points 10 metres apart can sit on opposite sides of a cell boundary and share no common prefix, most dramatically across the equator or the prime meridian.
  • Cells are also not equal-sized everywhere: they get narrower towards the poles.
  • Redis GEO is geohash-based. Its sorted-set score is the 52-bit interleaved value, which gives sub-metre precision. GEOSEARCH computes the covering cells for a radius internally and filters by distance.

Quadtree.

  • Recursively split a square region into four children whenever it holds more than K points, for example 100.
  • Dense downtown areas get small cells; empty countryside stays as large cells. Each leaf holds about the same number of points, so a nearest-N search touches a predictable amount of data.
  • Quadtrees shine for static or slowly changing points, such as businesses on Yelp, where the tree is built offline and rebuilt occasionally.
  • For moving drivers, every update can move a point between leaves, and splits and merges churn constantly. It works in memory with care, but uniform cells (geohash, H3, S2) are simpler to update at high rates and easier to shard.

R-trees (PostGIS, via GiST).

  • A tree of nested bounding rectangles: excellent for polygons (service areas, airports, geofences) and for durable spatial queries.
  • Updates require tree maintenance, so a very high update rate on the same points is expensive.
  • Ride-hailing systems still use PostGIS-style stores for static geography (zones, pricing regions, airport queues), while the moving drivers live in memory.

S2 (Google).

  • Projects the sphere onto the six faces of a cube and orders each face's cells along a Hilbert curve.
  • The result is a 64-bit cell id where numerically close ids are usually spatially close, with 31 levels of hierarchy (0 to 30) from a face down to about a square centimetre.
  • Its region coverer approximates any shape (a circle around the pickup, a city polygon) with a small set of cells at mixed levels, which become a few range scans.
  • Distortion is much lower than with latitude and longitude grids. Uber has said in public talks that its dispatch system once used S2 cells, which shows the approach works at this scale.

H3 (Uber, open-sourced in 2018).

  • A hierarchical grid of hexagons, built on an icosahedron projection.
  • 16 resolutions (0 to 15). Each step makes cells about 7 times smaller by area.
  • Approximate averages:
ResolutionAverage areaEdge length
7about 5.2 km²about 1.2 km
8about 0.74 km²about 460 m
9about 0.1 km²about 170 m
  • Uniform neighbours. Every hexagon has six neighbours, all sharing an edge, and all at the same centre-to-centre distance. Square grids have edge neighbours and corner neighbours at different distances. This makes "rings" around a cell (H3's gridDisk, also called k-ring) a good approximation of a circle. It also makes smoothing across neighbouring cells (for surge prices, demand forecasts or ETA statistics) behave evenly.
  • Trade-off: a hexagon cannot be split exactly into seven smaller hexagons, so parent-child containment is approximate. In addition, each resolution has 12 pentagons, placed mostly over oceans.
  • For counting and analysis, H3's uniformity is a big win. For exact containment (a strict cell hierarchy), S2 or geohash is cleaner.

The query algorithm, H3 style.

  1. Compute the pickup's cell at resolution 9.
  2. Take the 1-ring: the cell plus its 6 neighbours, about 0.7 km². Collect available drivers of the right category from those 7 cells.
  3. If fewer than N candidates (say 10), expand to the 2-ring (19 cells) and then the 3-ring (37 cells), up to a maximum radius of a few kilometres.
  4. For each candidate, compute the exact great-circle distance (haversine) and drop any outside the radius.
  5. Send the closest 20 or so to the ETA service and rank them by road ETA.

Ring expansion means a dense downtown request touches 7 cells and a few dozen drivers, while a suburban request expands until it finds enough. Each cell lookup is a hash-map read, so the whole query takes well under a few milliseconds in memory.

IndexStrengthWeaknessGood fit
Geohash (Redis GEO)Simple, one-dimensional, prefix queries, built into RedisEdge effects, cells distort with latitudeQuick, standard solution for moving points
QuadtreeAdapts to densityChurn under frequent movesStatic points (businesses), rebuilt periodically
R-tree (PostGIS)Polygons, durable, rich spatial SQLCostly at very high update ratesGeofences, zones, static geography
S2Low distortion, region covering, hierarchicalMore complex libraryRegions, coverage, sharding by cell ranges
H3Uniform hexagon neighbours, great for aggregation and ringsApproximate hierarchy, pentagonsMatching rings, surge and demand grids, analytics

"Cars near me" for millions of idle rider apps. Answering 1 million exact queries per second would cost more than all of matching. Instead, every 2 to 5 seconds, each region shard publishes a snapshot per resolution-8 cell: up to about 20 driver positions per vehicle category, slightly fuzzed for privacy. Rider apps request, or are pushed, the snapshot for their cell and its neighbours. The snapshot changes slowly and is shared by everyone in the cell, so it caches perfectly in memory. The exact query runs only when the rider actually requests a ride.

3. Matching and dispatch#

Matching has three stages: candidate generation (who is nearby and eligible), ranking (who is the best choice), and dispatch (offering the ride and handling the answer).

Candidate generation.

  • Query the geo index for available drivers of the requested category, using ring expansion around the pickup (Deep Dive 2).
  • Apply hard filters: vehicle category and seats, driver preferences (a "heading home" destination filter), regulatory constraints (airport permits, city licences), and staleness of the last location.
  • Some platforms also consider drivers about to finish a trip near the pickup. A driver dropping someone off 300 metres away in one minute can beat a free driver 8 minutes away. This needs the in-trip driver's remaining ETA, so it lives one step beyond the basic design.

Ranking. Straight-line distance is a weak signal. Ranking should use:

  • Pickup ETA by road. This is the main factor. It accounts for one-way streets, rivers, motorways and traffic.
  • Heading. A driver already moving towards the rider is better than one driving away at the same distance, because a U-turn costs minutes.
  • Probability of acceptance. Learned from the driver's history and context. Offering to a driver who declines 80 percent of the time burns 10 seconds of the rider's minute.
  • Quality and fairness. Ratings, time since the driver's last trip (spreading earnings), and service-level rules.

Greedy versus batched matching. The simplest matcher handles each request as it arrives and takes the best driver for that request. That is locally optimal but can be globally poor. Example:

  • Rider R1 requests first. Driver A is 2 minutes from R1 and 3 minutes from R2. Driver B is 6 minutes from R1 and 9 minutes from R2.
  • Greedy: R1 gets A (2 minutes); R2, arriving a second later, gets B (9 minutes). Total wait 11 minutes.
  • Joint: R1 gets B (6) and R2 gets A (3). Total 9 minutes, and nobody waits 9.

Batched matching collects requests and available drivers in an area over a short window, typically a couple of seconds. It builds a bipartite graph with an edge from each request to each feasible driver, weighted by cost (pickup ETA, adjusted for acceptance probability and other factors), and solves a minimum-cost assignment.

  • The Hungarian algorithm (Kuhn, 1955; refined by Munkres, 1957) solves it exactly in cubic time in the number of nodes. That is fine for the hundreds of requests and drivers in one area's batch.
  • Min-cost-flow solvers and greedy heuristics on sorted edges are alternatives for larger batches.

Ride-hailing companies have publicly described moving from greedy dispatch to batched, globally optimised matching for exactly this reason. The cost is the batch window: each rider waits up to a couple of seconds longer before the first offer, to save minutes of pickup time across the area. In quiet areas with one request at a time, batching gives nothing, so the window can shrink to zero.

Dispatch: one driver at a time. Our requirement is that a ride is offered to one driver at a time and a driver receives one offer at a time. The arithmetic of the 1-minute budget:

  • With a 10-second window and an acceptance probability of 0.7, the expected number of offers is 1 / 0.7 ≈ 1.4. The average time to an accepted offer is roughly 10 to 15 seconds (most drivers answer within a few seconds, not at the deadline).
  • The worst case is about 6 sequential offers within a minute. Riders in areas with low acceptance hit the limit.
  • Levers: shorter windows (for example 8 seconds), ranking by acceptance probability, and expanding the search radius after each failed round.

Alternative: broadcast offers. Offer the ride to several drivers at once and assign it to the first who accepts. Some taxi and delivery platforms work this way. It matches faster, but:

  • Drivers race each other and often tap "accept" only to be told they lost, which is frustrating.
  • It needs a lock on the ride, as well as on each driver, so only one accept succeeds.
  • It conflicts with "one outstanding offer per driver", because a driver may be shown several rides.

A hybrid is common in designs like this. Offer sequentially for the first two or three attempts, then broadcast to a small wave if time is running out.

No drivers. If no candidates are found within the maximum radius, or the 1-minute budget runs out, the ride moves to NoDrivers. The rider sees a clear message, possibly with a suggestion such as a different category or waiting for surge pricing to fall. Silent hanging is the worst outcome.

4. Locking and consistency of driver assignment#

This is the same problem as reserving a concert seat during checkout: an item (a driver) is held for one buyer (a ride) for a limited time (10 seconds), and must never be sold twice. See Pattern: Dealing with Contention and Distributed Locks.

The invariants.

  1. A driver has at most one outstanding offer.
  2. A ride has at most one outstanding offer (in the sequential design).
  3. A driver is assigned to at most one active ride.
  4. A ride is assigned to at most one driver.

Invariants 3 and 4 are about correctness: a broken one means two riders waiting for the same car. Invariants 1 and 2 are mostly about experience and efficiency: a broken one means a confusing double offer, which is bad but recoverable.

Bad: application-level locks in each matching instance. Each instance keeps an in-memory set of "drivers I have offered" and a timer to release them.

  • No coordination: two instances can offer the same driver at the same moment.
  • Lost state: if an instance crashes, its locks disappear, which is safe, but its rides are stranded. If it pauses, its view of locks diverges from the others.
  • Worse with scale: the more instances there are, the more often conflicts happen.

Good: a status column in the database with a conditional update. Acquire the "lock" by updating the driver row only if they are free:

-- Acquire: succeeds only if the driver is free or their previous offer has expired
UPDATE drivers
SET status = 'offered', current_offer_id = :offer_id,
    offer_deadline = now() + interval '10 seconds', version = version + 1
WHERE driver_id = :driver_id
  AND current_ride_id IS NULL
  AND (status = 'available'
       OR (status = 'offered' AND offer_deadline < now()));
-- 1 row updated: we hold the driver. 0 rows: pick the next candidate.

The database's row locking provides the coordination. The classic weakness of this approach is the timeout:

  • If the matcher holds an in-memory timer to reset the status after 10 seconds and then crashes, the driver stays offered forever.
  • A periodic cron job that resets expired offers works, but adds a component and delays.

The offer_deadline < now() clause above removes the problem differently. It uses lazy expiry: an expired offer is treated as free by the next acquirer, so nothing needs to "release" it. Offers run at a few thousand per second, well within a sharded database's capacity, so this is a solid design.

Great: a distributed lock with TTL in Redis, backed by a conditional commit.

SET lock:driver:{driver_id} {offer_id} NX PX 12000
-- NX: only if absent.  PX 12000: expires by itself after 12 seconds.
-- Release only our own lock (Lua, atomic compare-and-delete):
if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end
return 0
  • Automatic expiry: if the matcher crashes, the lock disappears on its own after the TTL. No sweeper, no stuck drivers.
  • Fast and cheap: sub-millisecond, and it keeps the hot contention off the database. This matters when 200 workflows in a stadium hotspot are all trying the same 50 nearby drivers.
  • Owner-checked release: the Lua compare-and-delete stops a slow workflow whose lock already expired from deleting the lock that another workflow now holds.
  • The TTL (12 s) is slightly longer than the offer window (10 s) to cover network delay. The offer itself carries the authoritative deadline.

Why the Redis lock alone is not enough. Redis replication is asynchronous. If the primary fails right after granting a lock, the promoted replica may not have it, and a second workflow can acquire the same driver. A workflow can also pause, for example in garbage collection, past its TTL and then act as if it still held the lock. Martin Kleppmann's 2016 essay "How to do distributed locking" and Salvatore Sanfilippo's reply are the classic debate on this. The practical conclusion is to use the fast lock for efficiency and a fenced, conditional write in the source of truth for correctness.

The accept transaction. When the driver accepts, the Ride Service runs one transaction on the region's database shard:

BEGIN;
UPDATE rides
SET status = 'accepted', driver_id = :driver_id, version = version + 1
WHERE ride_id = :ride_id AND status = 'offered' AND current_offer_id = :offer_id;
UPDATE drivers
SET status = 'on_trip', current_ride_id = :ride_id, current_offer_id = NULL
WHERE driver_id = :driver_id AND current_offer_id = :offer_id
  AND current_ride_id IS NULL;
-- If either statement updated 0 rows: ROLLBACK and tell the driver the offer is gone.
COMMIT;
  • The offer_id acts as a fencing token. A late accept for an expired offer, a duplicated request, or an accept from a driver whose lock was lost all fail the WHERE clause.
  • Rides and drivers are sharded by region, so the transaction is local to one shard and needs no two-phase commit. A driver who moves into another region while available is re-homed: their driver record's region changes at a quiet moment, never mid-offer.
  • Ride-side exclusivity (invariant 2) comes from having exactly one dispatch workflow per ride. This is enforced by a unique workflow id equal to the ride id (in Temporal), or by partitioning the dispatch queue by ride id so one consumer owns each ride.

The cancel-versus-accept race. The rider taps "cancel" at the same instant the driver taps "accept". Both are conditional updates on the same ride row:

  • If the cancel commits first, the accept finds status = cancelled and fails, and the driver is told the rider cancelled.
  • If the accept commits first, the cancel becomes a post-acceptance cancellation, which may carry a fee under policy.

Either way the row has one final state, and both apps learn it from the event that follows. This is optimistic concurrency at work. See Concurrency Control and Database Locking.

5. When a driver does not respond: timeouts and durable dispatch#

A driver drops their phone on the passenger seat and goes for a coffee. The offer must expire after 10 seconds and the ride must move to the next driver, even if the matching instance that sent the offer crashes in those 10 seconds. Waiting for a human with a deadline and moving on if they do not answer is the signature of a multi-step, human-in-the-loop process. See Pattern: Multi-Step Processes and Workflows.

Bad: an in-memory timer. setTimeout(10 s, tryNextDriver) in the matching process. A crash or deploy loses the timer, and the ride is stuck in offered until something else notices.

Good: a delay queue. When an offer is sent, also enqueue a delayed message for 10 seconds later, for example with an SQS delay queue, a Redis sorted set scored by due time, or a delayed-delivery topic. The message says "check ride 42, offer o7". When it is delivered, any matching instance:

  1. Reads the ride.
  2. If the ride is still offered with current_offer_id = o7, marks the offer expired, releases the driver, and sends the next offer, with its own delayed check.
  3. If the ride moved on (accepted, cancelled, or a newer offer), does nothing.

The delayed check is idempotent, because the offer_id makes it specific to one attempt. So an accept that arrives just before the check is handled correctly: the check sees accepted and exits. The complexity lies in scattering the workflow's logic across message handlers, and in reasoning about every interleaving of accept, decline, cancel and timeout.

Great: a durable workflow. Model each ride's dispatch as a workflow in a durable-execution engine such as Temporal or AWS Step Functions. Temporal grew out of Cadence, the workflow engine Uber built for this kind of problem and open-sourced. The workflow code reads like the business logic:

// Temporal-style workflow; one instance per ride, workflowId = rideId
export async function dispatchRide(rideId: string, pickup: LatLng): Promise<Outcome> {
  const deadline = Date.now() + 60_000;               // 1-minute matching budget
  let radiusKm = 1.5;
  const tried = new Set<string>();
  while (Date.now() < deadline) {
    const candidates = await activities.rankCandidates(pickup, radiusKm, [...tried]);
    if (candidates.length === 0) { radiusKm = Math.min(radiusKm * 1.5, 6); await sleep('2s'); continue; }
    for (const driverId of candidates) {
      tried.add(driverId);
      const offerId = await activities.lockAndOffer(rideId, driverId);  // Redis NX + offer row
      if (!offerId) continue;                                           // driver taken
      // wait for the driver's answer (a signal) or 10 s, whichever first
      const answer = await waitForSignal('driverAnswer', offerId, '10s');
      if (answer === 'accepted') return { status: 'accepted', driverId };
      await activities.expireOffer(rideId, offerId);                    // releases the driver
      if (Date.now() >= deadline) break;
    }
  }
  await activities.markNoDrivers(rideId);
  return { status: 'no_drivers' };
}

What the engine provides:

  • Durable timers. The 10-second wait and the 1-minute deadline survive crashes and deploys. The engine records each step in an event history, and if the worker dies, another worker replays the history and continues from the same point.
  • Signals. The driver's accept or decline arrives as a signal to the workflow by id. The accept transaction in the Ride Service still runs the conditional update (Deep Dive 4). The signal only tells the workflow the result.
  • Exactly one workflow per ride. Starting a workflow with an id that is already running is rejected, which enforces "one dispatch per ride".
  • Retries for activities. A failed call to the ETA service is retried with backoff, without hand-written retry loops.
  • Visibility. Operators can inspect any ride's dispatch history.

The trade-off is a new piece of infrastructure to run or buy, and a new programming model. Workflow code must be deterministic, so all side effects go through activities and time comes only from the engine. For a system where every dropped request is lost revenue and a stranded rider, the guarantee is usually worth it. See Temporal and Workflow Engines.

Scaling numbers. About 1,500 new dispatch workflows per second at peak, each lasting about 15 seconds on average with around 5 history events. That is roughly 22,500 concurrently running workflows and about 7,500 events per second. This is a moderate load for a sharded Temporal cluster. Batched matching changes the shape: one workflow per area batch cycle, plus one lightweight workflow per ride that waits for its assignment.

6. ETA: how long until pickup, and how long is the trip?#

ETA appears in three places: the fare estimate (trip duration drives price), ranking candidates (pickup ETA per driver), and the rider's screen (countdown to pickup and arrival). It is the most-called computation in the system: perhaps tens of thousands of route computations per second at peak, mostly for fare estimates and candidate ranking.

Layer 1: a road graph and shortest paths.

  • Model the road network as a directed graph. Intersections are nodes. Road segments are edges, weighted by expected travel time and annotated with turn restrictions and one-way rules.
  • Dijkstra's algorithm (1959) finds the fastest route but explores every node closer than the destination. On a continental graph with tens of millions of nodes, a single long query can take seconds.
  • A* (Hart, Nilsson and Raphael, 1968) adds a heuristic, such as straight-line distance divided by maximum speed, to explore towards the goal first. It helps, but not enough at scale.
  • Contraction hierarchies (Geisberger, Sanders, Schultes and Delling, 2008) preprocess the graph by ranking nodes by importance and adding "shortcut" edges. Queries then search upward from both ends in the hierarchy and meet in the middle, visiting only hundreds or thousands of nodes. Continental queries run in about a millisecond.
  • Live traffic changes edge weights, which invalidates plain shortcuts. Customisable variants separate the preprocessing of the graph's structure from the fast application of new weights, so traffic can be applied every few minutes. The Maps and Navigation case study covers routing algorithms in depth.

Layer 2: live traffic. The location stream is itself a traffic sensor. Map-matched driver traces give the observed speed on each road segment. Aggregate it over the last few minutes, per segment, with outlier removal, to set the current edge weights. Where there are no fresh observations, blend in historical speeds for that segment, weekday and time of day.

Layer 3: a learned correction. Route-based ETAs carry systematic biases, such as time to find parking at a stadium, pickup delays at airports, or traffic lights that the graph does not model. A machine-learned model predicts the residual: the difference between the routing engine's ETA and the actual travel time. Its features include the route, the time, the area, the weather and the trip type. The final ETA is the routing ETA plus the predicted residual. Uber has described this approach publicly, under the name DeepETA, a deep model that corrects routing-engine ETAs. Training data comes straight from the location log: every completed trip is a labelled example.

Making it fast enough.

  • Candidate ranking does not need full turn-by-turn routes. It needs travel-time estimates from 20 driver positions to one pickup, which is a one-to-many query. Searching backwards once from the pickup covers all candidates in roughly the cost of a single route.
  • Cache by cell pairs. Pickup ETAs between H3 cells at resolution 8 or 9 change slowly over a few minutes. Precomputed or cached cell-to-cell travel times give a cheap first-pass ranking, refined with exact routing only for the top few candidates.
  • Fare estimates can reuse the route computed for display, and can be cached per origin cell, destination cell and time bucket for a short time.

Accuracy and how it is measured.

  • Track the error distribution, not just the mean: the absolute error, and the percentage of ETAs within one or two minutes of the truth, split by city, time and trip length.
  • Biased optimism is costly. A pickup ETA of 3 minutes that becomes 8 annoys riders more than an honest 6.
  • Some products show ranges for longer trips, or re-estimate continuously during pickup and the trip. Each new location update refines the remaining ETA, and the rider's app updates the countdown.

Build versus buy. In an interview, "call a mapping provider's distance-matrix API" is a fine starting point. At ride-hailing scale, however, the call volume, the latency budget (tens of milliseconds for ranking) and the value of the company's own traffic data push towards an in-house routing engine built on open map data or licensed maps. Mapping APIs still serve as a fallback and for geocoding addresses.

7. The trip state machine and the Trip Service#

A trip is a long-lived entity with a strict lifecycle. Modelling it as an explicit state machine gives three things:

  • Correctness: illegal transitions such as Requested → Completed are rejected.
  • Idempotency: a repeated "start trip" event does nothing the second time.
  • A clean event stream for everything downstream.

States and who triggers them.

FromToTriggered bySide effects
(none)RequestedRider requestStart dispatch workflow; payment pre-authorisation
RequestedOfferedDispatch workflowOffer row; driver locked
OfferedRequestedOffer timeout or declineDriver released; next offer
OfferedAcceptedDriver accept (transaction)Driver on_trip; rider notified with car details
AcceptedArrivedDriver taps "arrived", or a geofence auto-detects itRider notified; wait-time clock starts
ArrivedInProgressDriver taps "start", optionally with a PIN checkTrip timer and distance metering start
InProgressCompletedDriver taps "end"Final fare computed; driver back to available
CompletedPaidPayment capturedReceipt sent; driver earnings recorded
Requested, Offered, Accepted, ArrivedCancelledRider, driver or systemCancellation fee policy; driver released
RequestedNoDriversDispatch workflow gives upRider informed; pre-authorisation released

Enforcing transitions. Each transition is a conditional update guarded by the expected current state and the row's version:

UPDATE rides
SET status = 'in_progress', started_at = now(), version = version + 1
WHERE ride_id = :ride_id AND status = 'arrived' AND driver_id = :caller_driver_id;
-- 0 rows: either already started (idempotent repeat: return current state)
-- or illegal (wrong state or wrong driver: return 409 Conflict)

The Trip Service distinguishes a repeat (the ride is already in the target state, so it returns success with the current state) from an illegal transition (it returns an error). Mobile clients retry aggressively on flaky networks, so repeats are common and must be harmless. The event id (driver id, ride id, event type) acts as a natural idempotency key. See Idempotency and Safe Retries.

Publishing events reliably: the transactional outbox. Each transition must also emit an event (trip.accepted, trip.completed) for payments, notifications and analytics. Writing to the database and then publishing to Kafka is two separate operations, and a crash between them loses or duplicates events. Instead:

  1. In the same transaction as the state change, insert a row into an outbox table.
  2. A relay reads the outbox, or tails the database's change log with change data capture, and publishes to Kafka.
  3. Consumers dedupe by event id.

Downstream systems then see every committed transition exactly once in effect, in order per ride. See Distributed Transactions: 2PC, Sagas and Outbox.

Geofences and automatic transitions. Many transitions can be suggested or automated from location. "Arrived" can fire when the driver is within about 50 metres of the pickup and has slowed down. Airports and stadiums have pickup zones (polygons) with virtual queues for drivers. These polygons live in a spatial store (PostGIS or an in-memory polygon index), and each location update for an on-trip or queued driver is checked against them. The check is cheap because each update is tested only against the few polygons covering its H3 cell.

Computing the final fare. At Completed, the Trip Service asks for the map-matched route from the location log for this trip's time window. It computes distance and duration and applies the pricing rules agreed in the fare quote (upfront pricing), or computes a metered fare (time and distance) where regulations require it. Using the server-side, map-matched trace rather than client-reported totals prevents tampering and corrects for GPS noise. Gaps in the trace, for example from a tunnel, are filled by routing between the points on either side of the gap.

Payment flow.

  • At request time, place an authorisation hold on the rider's card for the quoted fare plus a margin. This checks that the card works and reserves funds.
  • At completion, capture the final amount, which can be lower or higher within network rules. On cancellation, release the hold.
  • Payment calls to the provider use the ride id as an idempotency key, so retries cannot charge twice.
  • Payments run asynchronously from trip.completed events, so a slow payment provider never blocks the driver from taking their next ride.

The Payment System case study covers ledgers and reconciliation.

Storage of trips.

  • Active trips are small, hot and strongly consistent: keep them in the regional transactional database.
  • Completed trips are read occasionally (receipts, support, disputes) and must be kept for years for tax and regulatory reasons. Archive them to cheaper storage after a retention period, for example a wide-column store or the data lake, keyed by rider and by driver.
  • Uber has written publicly about building Schemaless, a scalable datastore on top of MySQL, for trip data. It illustrates that sharded relational storage with an append-friendly model works at this scale.

8. Fare estimates and surge (dynamic) pricing#

The fare quote.

fare = max(minimum_fare,
           (base + per_km × route_km + per_min × route_min) × surge_multiplier)
       + booking_fee + tolls + airport_fee

The quote is stored with an id, the inputs (route, multiplier, rule version) and an expiry of a few minutes. The ride request references the quote id. This gives three properties:

  • The price is server-authoritative. The client never sends a price, so it cannot send a cheaper one.
  • The price is stable. The rider pays what they saw even if surge changes while the driver is en route.
  • It is auditable. Support can reconstruct exactly why a fare was what it was.

If the quote expires before the rider taps "request", the app fetches a new one.

Why surge exists. When demand outstrips supply in an area (a concert ending, a storm, rush hour), a fixed price means riders wait a very long time or get no car at all. A temporary multiplier does two things:

  • It reduces demand from riders who can wait or choose alternatives.
  • It attracts drivers from neighbouring areas and brings more drivers online.

Whether and how much to surge is a business and regulatory decision. Some cities cap multipliers or prohibit surge during emergencies. The system design question is how to compute it quickly and stably.

Computing the multiplier.

  1. Measure supply and demand per cell. Use H3 at a resolution where a cell is a neighbourhood, for example resolution 7 or 8. Every few seconds to a minute, count:
    • available drivers in each cell (from the geo index);
    • requests and fare-estimate views in each cell over the last few minutes (a demand signal that leads actual requests).
  2. Smooth across space and time. Raw per-cell ratios are noisy and would make prices flicker between neighbouring streets. Hexagonal grids make spatial smoothing natural: blend each cell with its 1-ring, weighted. Temporal smoothing, such as exponential moving averages, stops the multiplier from oscillating every few seconds.
  3. Map the smoothed ratio to a multiplier with a pricing function, within caps and minimum steps, for example in steps of 0.1. Forecasting models can anticipate surges, for example from the event schedule at a stadium, so the price nudges drivers before the crowd appears.
  4. Publish the multiplier map to the Pricing Service's in-memory cache. Fare estimates read it, and drivers' apps show a heat map to guide repositioning.

This is a classic stream aggregation: location and request events in, windowed counts per cell, smoothing, results out. Apache Flink or a similar stream processor fits, with state keyed by cell. See Apache Flink and Stream Processing and Batch vs Stream Processing.

Fairness and trust.

  • The multiplier must be computed only from aggregate, area-level signals, and applied the same way to everyone in the same area and time.
  • Show it clearly before the request.
  • Log the inputs so any price can be explained later.
  • Avoid feedback loops. Drivers who know the surge map can briefly go offline to trigger surge, a behaviour reported in the press. Use demand and supply signals that are hard to game, smooth them over time, and detect coordinated behaviour.

9. Peak demand: never dropping a ride request#

Two threats lose ride requests:

  • Overload: a surge of requests arrives faster than matching instances can process them.
  • Crashes: a matching instance dies while holding requests in memory.

Bad: synchronous, first-come-first-served, no queue. The Ride Service calls the Matching Service directly and waits. Under a spike, matching falls behind, calls time out, and requests are dropped or retried by clients, which makes the spike worse. A crash loses every request the instance was holding, and riders wait for a match that will never come. Horizontal autoscaling helps, but takes minutes, while a stadium empties in seconds.

Great: a durable queue between request and matching, with dynamic scaling.

  1. The Ride Service writes the ride row, publishes a ride.requested message, and returns 201 to the rider.
  2. The dispatch queue is partitioned by region, and by area within a big region, so each city's matching capacity scales independently and a surge in one city cannot starve another.
  3. Matching consumers process messages. With Kafka, a consumer commits a message's offset only after the request's dispatch is safely owned: its durable workflow has started, or its outcome is recorded. If a consumer crashes before committing, the partition is reassigned and the new consumer re-reads the message. Starting the workflow with id = ride id makes the redelivery harmless.
  4. Autoscale consumers on queue lag and on the age of the oldest unprocessed request, not on CPU. Pre-scale for known events: New Year's Eve, concerts, matches.

Two subtleties with a Kafka-style log:

  • Head-of-line blocking. Offsets are committed in order per partition. A request that takes 40 seconds to match must not hold up the commits of the requests behind it. That is a strong reason to hand each request to a durable workflow quickly, so the consumer commits within milliseconds, and to keep long waits out of the consumer loop.
  • Parallelism is capped by partitions. Choose enough partitions per region for peak consumers, for example 32 to 128 for a large city.

A managed queue (Amazon SQS, Amazon MSK, Confluent Cloud) removes operational burden. SQS gives per-message acknowledgement and visibility timeouts, which avoid the in-order commit issue. A Kafka-style log gives replay and ordering. See Asynchronous Processing and Message Queues and Apache Kafka in Practice.

Priority instead of strict FIFO. In a strict FIFO queue, one difficult request (a remote suburb that needs radius expansion) can delay easy ones behind it. Options:

  • Use a priority order by waiting time (oldest first), with boosts for premium categories, accessibility needs or riders who have already been re-matched after a driver cancelled.
  • In batched matching the queue empties into the next batch every couple of seconds anyway, and the assignment solver handles priority through edge costs, for example by lowering the cost for long-waiting riders.

The stadium problem: 100,000 requests from one place. When a concert ends, tens of thousands of people request rides within minutes, all from a few H3 cells. Problems compound:

  • Hot geo cell. Every matching workflow queries the same few cells and races for the same drivers. Redis locks absorb the contention, but thousands of failed lock attempts waste time. Batched matching is the right tool here: one solver assigns the cell's available drivers to its pending requests in one pass, instead of thousands of workflows fighting.
  • Not enough drivers. Supply is the real limit. Surge pricing and driver heat maps pull in drivers from surrounding areas, and the queue absorbs the wait. Riders see an honest "high demand, estimated wait 12 minutes" instead of failures.
  • Pickup chaos. Thousands of cars cannot reach one kerb. Venues and airports use designated pickup zones and driver queues (first in, first out among drivers waiting in a staging lot). Riders walk to a zone, and the matcher assigns drivers from the queue. This is a product solution to a physical bottleneck, and interviewers like candidates who see it.
  • Fare estimate storm. Everyone checks prices at once. Cache the route and multiplier per origin cell for a few seconds, and rate-limit per user. See Rate Limiting and Throttling.
  • Hot shard. If the stadium's area is one partition, its matching consumers saturate. Sub-partition hot areas dynamically by finer cells, or route them to a dedicated batch matcher.

Admission control is the last resort. When even the queue's wait would exceed the matching budget, tell new requesters up front and offer alternatives, rather than accepting requests that will time out.

10. Geo-sharding: scaling services and data by region#

Almost everything in ride-hailing is local. A rider in Paris is matched with a driver in Paris, priced by Paris rules, and tracked on Paris streets. That makes geography the natural shard key for nearly every component. See Partitioning and Sharding.

What gets sharded by region.

  • Geo index: one or more shards per city, or per group of small cities.
  • Dispatch queue partitions and matching workers: per region.
  • Ride and driver database: sharded by region, so the accept transaction is single-shard.
  • Pricing and surge state: per region.
  • Connection gateways: deployed near users, routing each driver's stream to their region's Location Service.

Benefits.

  • Scale. Adding cities adds shards. No single component sees global traffic, apart from global services such as accounts and payments.
  • Latency. Run each region's stack in a data centre or cloud region near it.
  • Blast radius. A failure in one region's index or database affects one region.
  • Compliance. Data residency laws can keep a country's trip data in-country.

The boundary problem. A pickup near the edge of a region can have its best driver just across the boundary. Options:

  • Overlap (ghost) zones. Drivers within a few kilometres of a boundary are indexed in both neighbouring shards, and their status is checked against the owning shard before an offer.
  • Scatter-gather at boundaries. If the pickup's search rings cross into another shard, query both and merge the results. This is the only time a proximity search touches multiple shards, and it is a small fraction of queries.
  • Choose boundaries well. Draw regions along natural barriers with little traffic across them (water, mountains, administrative borders), not through dense downtown areas. Metropolitan areas usually stay inside one region.

Shard assignment inside a region. A big city can have several geo-index shards, each owning a set of cells. A cell-to-shard map lives in a coordination service (etcd or ZooKeeper), so hot cells can be moved or split without reshuffling everything. A consistent-hashing ring over cell ids is another option. Uber has described Ringpop, an open-source library it built that combines SWIM-style gossip membership (Das, Gupta and Motivala, DSN 2002) with a consistent-hash ring. It lets a cluster of dispatch processes agree which node owns which key (for example, a cell or a driver) and forward requests to the owner. See Consistent Hashing and Heartbeats, Failure Detection and Gossip.

Read replicas help the read-heavy parts: trip history, receipts, driver profiles, support tools. The assignment path always reads and writes the primary of its region's shard, because it needs strong consistency.

Global services that cannot be sharded by region (user accounts, payment methods, identity, fraud models) are replicated globally, or served from a home region per user with caching. A traveller who signs up in London and rides in New York has their account read through a global, replicated store. Trips are written to New York's regional shard.

Multi-region availability. Each region's stack runs across multiple availability zones. For disaster recovery, its trip database replicates to a standby in another region. If a whole region fails:

  • Location state rebuilds itself. Drivers' apps reconnect to the standby region, and the geo index fills within one update interval.
  • Active trips need care. Uber has described a technique of storing an encrypted digest of the active trip's state on the driver's phone, so that a backup data centre can reconstruct trips in flight from the phones as they reconnect, even if the latest database writes did not replicate.

The general lesson: for state that clients hold anyway, the clients can be part of the recovery plan. See Multi-Region and Global Data and Disaster Recovery and Backups.

11. Reliability: partial failures and graceful degradation#

A ride-hailing system runs on phones on mobile networks, in cars, in tunnels. Partial failure is the normal state. Design every interaction to survive lost messages and retries.

The driver's accept is lost on the way back. The driver taps accept, the transaction commits, but the response never reaches the phone. The app retries the PATCH with the same offerId. The Ride Service sees the ride already accepted by this driver with this offer and returns success with the current state. It does not return an error. Idempotent transitions turn retries from a hazard into a non-event.

The offer push never arrives. The driver's connection dropped, and mobile push is delayed. The 10-second timeout expires, the offer is marked expired, and the next driver gets the ride. If the first driver's app reconnects and shows the stale offer, the accept fails cleanly on the offerId check. For faster detection, the gateway can report whether the offer was delivered to the device. If the device never acknowledged it within 2 seconds, the workflow moves on early.

The rider's app goes offline mid-trip. Nothing breaks. The trip continues; on reconnect, the app fetches the ride state and resumes the live stream. State lives on the server, and the app is a view.

The driver's app goes offline mid-trip. The car is still moving. Points are buffered on the phone and uploaded later, and the fare is computed from the complete trace. If the app stays dark for a long time, safety and support processes trigger (Deep Dive 12). The trip is not automatically ended.

A Location Service instance or Redis shard fails.

  • Gateways reroute updates to a healthy instance, and Redis fails over to a replica.
  • Missing drivers reappear within one update interval.
  • During those seconds, matching in that area sees fewer candidates. It may expand the radius slightly or wait one cycle; it should not fail requests.

A matching worker crashes. Its Kafka partitions are reassigned within seconds. Durable workflows resume on other workers from their event history. Locks it held expire by TTL. No ride is lost; a few are delayed by seconds.

A database shard primary fails. Failover to a synchronous replica takes seconds to a minute, depending on the technology.

  • During it, accepts and trip transitions for that region fail and are retried by the apps with backoff.
  • Dispatch workflows pause on retrying activities.
  • Location tracking and the live map keep working, because they do not depend on the trip database.

This separation is why the high-rate location path never shares a store with the transactional path.

Dependency failures and fallbacks.

Dependency downDegraded behaviour
ETA serviceRank by straight-line distance × a city-specific detour factor; show "about N min" with wider uncertainty
Pricing or surge serviceUse the last published multiplier map (cached); fall back to multiplier 1.0 with a cap if very stale
Payment providerComplete trips normally; queue captures for retry; flag accounts only after repeated failure
Push notificationsRely on the live connection; extend offer windows slightly
Maps provider for geocodingRecent-address cache, pin-drop on map

Every remote call has a timeout sized to its budget, retries with jitter only where idempotent, and a circuit breaker so a sick dependency fails fast instead of tying up threads. See Resilience Patterns: Timeouts, Retries and Circuit Breakers and Designing for High Availability.

12. Safety, privacy and fraud#

Location privacy. Location data reveals where people live, work, worship and seek medical care. Treat it as sensitive personal data:

  • Minimise. The rider sees the driver's exact position only during an active trip. The "cars near me" view shows fuzzed, delayed and sampled positions, not real-time precise ones.
  • Mask contact details. Riders and drivers call and message through proxy phone numbers. The system relays calls between temporary numbers so neither side learns the other's real number.
  • Retention. Raw location history is kept only as long as needed for receipts, disputes, safety investigations and legal obligations. Long-term analytics use aggregated or pseudonymised data, for example per-cell speeds, not per-person traces. Regulations such as the GDPR give users rights to access and delete their data, and some countries require it to stay in-country (the geo-sharding helps here).
  • Access control and audit. Internal tools that can view a person's trip history must be tightly permissioned and every access logged. Misuse of internal "god view" tools is a well-known historical lesson for the industry.

GPS spoofing and fraud. Some drivers use fake-GPS apps to appear near busy areas or airports, or to inflate trip distances. Defences:

  • Cross-check GPS against network signals (cell towers, Wi-Fi), phone sensors (an accelerometer that says the car is stationary while GPS says it is moving at 60 km/h), and physics (impossible jumps or speeds).
  • Detect mock-location settings and known spoofing apps through device attestation, while recognising that determined attackers can bypass client checks.
  • Compute fares from the map-matched route, so a trace that wanders through buildings or across water is flagged.
  • Detect collusion: the same rider and driver pairs repeatedly, very short trips with promotions, or accounts sharing devices. Graph-based fraud models work well on these relationships.

Account and payment fraud. Stolen cards, account takeovers and promo abuse are handled by risk scoring at sign-up, at payment-method addition and at request time. The authorisation hold at request time (Deep Dive 7) catches dead cards before a driver is dispatched.

Safety features as system features.

  • Trip sharing: a rider shares a live link to their trip; it is a read-only view of the trip channel.
  • An emergency button that sends the precise location to emergency services.
  • Driver identity checks: periodic selfie verification against the profile photo.
  • Anomaly detection on active trips: a long unexpected stop or a large route deviation triggers a check-in to both parties. It runs as a stream job over the location log, joined with the trip state.

See Security Fundamentals for System Design and Authentication and Authorization.

Bottlenecks and Failure Modes#

Failure / hotspotImpactMitigation
Location writes overwhelm the storeStale positions, slow matching, high costIn-memory geo index per region; latest-value-wins; adaptive update intervals; history to Kafka asynchronously
Hot geo cell at a stadium or airportLock contention, slow matching, overloaded shardBatched matching per cell; pickup zones and driver queues; sub-partition hot areas; surge to rebalance supply
Redis shard or primary failureDrivers vanish from the index; locks may be lostReplicas with automatic failover; index self-heals within one update interval; final assignment fenced by conditional database transaction
Matching instance crash mid-offerStranded rides, stuck driversDurable workflows or delay-queue checks; TTL locks; queue offsets committed only after ownership is durable
Double assignment raceTwo riders waiting for one carRedis SET NX PX for offers; single-shard accept transaction with offer_id fencing and status guards
Driver ignores the offerRider waits; budget burns10-second window; delivery acknowledgement for early fallback; rank by acceptance probability; hybrid broadcast after several misses
Fare-estimate stormRouting service overloadCache by origin and destination cells per time bucket; rate limiting; one-to-many ETA queries
"Cars nearby" pollingMillions of proximity queries per secondPer-cell snapshots every few seconds, shared and cached; push to open apps
Region-boundary pickupsMissed better driversOverlap zones or boundary scatter-gather; boundaries along natural barriers
Database shard primary failureAccepts and transitions fail for a regionSynchronous replica failover; idempotent client retries; location path independent of the trip database
ETA or pricing dependency outageNo ranking or quotesFallback to distance × detour factor; cached multiplier map; circuit breakers
GPS noise and spoofingWrong matches, wrong fares, fraudKalman smoothing and map matching; physics and sensor cross-checks; fares from server-side routes

What Interviewers Expect#

Mid-level.

  • Clear functional and non-functional requirements, with sensible items placed out of scope.
  • Clean entities and API: fare quote, ride request referencing the fare id, driver location updates, accept or decline. Identity comes from the session token, not the body.
  • A working high-level design with Ride, Location, Matching and Notification services.
  • Recognises that latitude and longitude B-tree indexes do not support proximity search, and proposes some spatial index, even without picking one in detail.
  • At least the "good" solution for driver locking: a database status column with a conditional update and a timeout.

Senior.

  • Moves through the high-level design quickly, then goes deep on at least two of: location ingestion and the in-memory geo index, the driver-locking problem, and queueing so no request is dropped.
  • Quantifies the location write rate and explains why an in-memory, latest-value-wins index is right and why durability barely matters for it.
  • Explains geohash or H3 ring queries, the edge problem, and stale-driver cleanup.
  • Uses a distributed lock with TTL for offers, and explains why the final accept is still a conditional transaction.
  • Introduces a durable queue between request and matching, commits after ownership, and autoscales on lag.
  • Discusses geo-sharding by region and the boundary problem.

Staff+.

  • Drives the conversation and frames the core insight: high-throughput, loss-tolerant location data versus low-rate, strongly consistent assignment, with different stores and scaling for each.
  • Goes deep on three or more areas with real trade-offs:
    • batched versus greedy matching, with the assignment-problem framing;
    • durable workflows (Temporal or Cadence) versus delay queues for human-in-the-loop timeouts;
    • fencing with offer ids;
    • adaptive client update intervals and dead reckoning;
    • ETA as routing plus learned residuals;
    • surge as windowed stream aggregation on an H3 grid with smoothing;
    • hotspot handling with pickup zones;
    • regional disaster recovery, including client-held state.
  • Brings operational judgement: what to monitor (match latency, acceptance rate, ETA error, stale-driver ratio), how the system degrades when dependencies fail, and privacy and fraud as first-class requirements.
  • Leaves the interviewer with a new perspective, for example by pointing out that "cars nearby" polling, not matching, is the largest query load.
Deep Dive: geohash, haversine and ring queries in codeShow

The geohash encoding bisects longitude and latitude in turn, interleaving one bit from each, and emits a base-32 character every 5 bits:

const BASE32 = '0123456789bcdefghjkmnpqrstuvwxyz';
 
export function geohash(lat: number, lng: number, precision = 7): string {
  let latLo = -90, latHi = 90, lngLo = -180, lngHi = 180;
  let hash = '', bits = 0, ch = 0, evenBit = true;   // even bits: longitude
  while (hash.length < precision) {
    if (evenBit) {
      const mid = (lngLo + lngHi) / 2;
      if (lng >= mid) { ch = (ch << 1) | 1; lngLo = mid; } else { ch = ch << 1; lngHi = mid; }
    } else {
      const mid = (latLo + latHi) / 2;
      if (lat >= mid) { ch = (ch << 1) | 1; latLo = mid; } else { ch = ch << 1; latHi = mid; }
    }
    evenBit = !evenBit;
    if (++bits === 5) { hash += BASE32[ch]; bits = 0; ch = 0; }
  }
  return hash;
}
 
// Great-circle distance in metres (haversine)
export function haversine(aLat: number, aLng: number, bLat: number, bLng: number): number {
  const R = 6_371_000, toRad = Math.PI / 180;
  const dLat = (bLat - aLat) * toRad, dLng = (bLng - aLng) * toRad;
  const h = Math.sin(dLat / 2) ** 2 +
            Math.cos(aLat * toRad) * Math.cos(bLat * toRad) * Math.sin(dLng / 2) ** 2;
  return 2 * R * Math.asin(Math.sqrt(h));
}

Why interleaving preserves locality. Each pair of bits picks one quadrant of the current cell, so the geohash is a path down a quadtree. Points sharing a long prefix share a small cell. Sorting by geohash visits cells in a Z-order (Morton) curve. That curve mostly keeps neighbours close, but it has jumps where it crosses from one big quadrant to the next. Those jumps are the edge problem: neighbours across a jump have very different hashes, which is why queries always include the neighbouring cells. The Hilbert curve used by S2 has no such long jumps between consecutive cells, so ranges of S2 cell ids are more compact on the ground. That is one reason S2 coverings need fewer ranges for the same shape.

Ring query on a cell grid.

function nearbyAvailable(pickup, wantN, maxRings):
  origin = cellOf(pickup, RESOLUTION)
  found = []
  for k in 0..maxRings:
    for cell in ringAtDistance(origin, k):          -- hexagons at exactly k steps
      for d in index[cell]:
        if d.status == AVAILABLE and now - d.seenAt < 30s:
          found.append((haversine(pickup, d.pos), d))
    if len(found) >= wantN and k >= 1: break        -- always include the 1-ring
  return smallest wantN of found by distance

On a hexagonal grid, the ring at distance k has 6k cells, so rings 0 to k hold 1 + 3k(k + 1) cells in total: 7 for k = 1, 19 for k = 2, 37 for k = 3. With resolution 9 hexagons (edge about 170 m), ring 3 reaches roughly a kilometre from the pickup. Always include at least the 1-ring, even if the centre cell has enough drivers. The nearest driver may sit just across the cell edge, closer than everyone in the centre cell.

Redis equivalent. The Location Service does the following:

GEOADD drivers:sf:available -122.4194 37.7749 driver:123
ZADD   drivers:sf:seen 1733220000 driver:123
GEOSEARCH drivers:sf:available FROMLONLAT -122.4183 37.7760 BYRADIUS 2 km ASC COUNT 25 WITHDIST

Keeping separate geo sets per status, such as available and on_trip, means matching never even sees busy drivers. Moving a driver between sets on a status change must be atomic, using MULTI or a Lua script, so the driver is never in both sets or in neither.

Deep Dive: batched matching as an assignment problemShow

Set-up. Every 2 seconds, the batch matcher for an area takes the pending requests R and the available drivers D. For each feasible pair it computes a cost, for example:

cost(r, d) = pickupEtaSeconds(d, r)
           + 60 × (1 - acceptProbability(d, r))      -- expected waste of a decline
           - 5 × secondsAlreadyWaited(r) / 60         -- prioritise long-waiting riders

Pairs whose pickup ETA is above a cap, for example 15 minutes, are infeasible.

A worked 3 × 3 example (pickup ETAs in minutes).

Driver ADriver BDriver C
Rider 1237
Rider 2398
Rider 3546
  • Greedy in arrival order (R1, then R2, then R3, each taking their cheapest remaining driver): R1 takes A (2), R2 takes C (8), R3 takes B (4). Total 14 minutes, and Rider 2 waits 8.
  • Greedy on the globally cheapest edge first: A–R1 (2), then B–R3 (4), then C–R2 (8). Again 14 minutes.
  • Optimal assignment (checking all 6 permutations): R1–B (3), R2–A (3), R3–C (6). Total 12 minutes, and nobody waits more than 6.

Both greedy variants grab driver A for Rider 1, saving Rider 1 one minute but costing Rider 2 five. The solver sees that A is nearly as good for Rider 2, while Rider 1 has a close second choice in B. Finding cases like this, where greedy's early choices block better global outcomes, is the whole point of the solver.

The Hungarian algorithm in one paragraph. Subtract each row's minimum from that row and each column's minimum from that column. Zeros now mark "free" choices. Try to pick one zero in every row and column. If you cannot, cover all zeros with the fewest lines, subtract the smallest uncovered value from every uncovered cell, add it where lines cross, and repeat. It ends with an optimal assignment, and its running time is cubic in the matrix size. A batch of 300 requests and 400 drivers is a few tens of millions of basic steps, about tens of milliseconds, well within a 2-second cycle. Larger areas are split into sub-areas, or solved with min-cost flow on a sparse graph that keeps only each request's nearest 20 drivers.

Trade-offs to discuss.

  • Window length. Longer windows find better matches but add wait. Adapt the window to density: zero in quiet areas, 2 to 5 seconds in dense ones.
  • Acceptance is uncertain. The assignment is a plan, not a fact. Declined offers return the request to the next batch with a higher priority.
  • Stability. Re-optimising every 2 seconds can flip a tentative assignment just before the offer goes out. Once an offer is sent, the pair is fixed until the offer resolves.
  • Fairness to drivers. Pure ETA minimisation always favours drivers in the densest spots. A small cost term for time since the driver's last trip spreads work more evenly.
Deep Dive: the numbers worked throughShow

Connection gateways.

  • 2.5 million drivers plus about 3 million riders with open apps is about 5.5 million persistent connections at peak.
  • At a conservative 100,000 connections per gateway node (memory for TLS state and buffers, about 20 to 50 KB per connection, so 2 to 5 GB per node), that is 55 nodes, or about 80 with headroom for zone failure, spread across regions.
  • Message rate per node: (625,000 location updates + 250,000 tracking pushes + a few thousand offers and events) ÷ 80 ≈ 11,000 messages per second per node. That is comfortable.

Geo index shards.

  • A large city with 100,000 online drivers updating every 4 seconds produces 25,000 writes per second.
  • Each update is a GEOADD and a ZADD for last-seen, plus an occasional status move: about 50,000 Redis commands per second. Matching adds a few hundred GEOSEARCH queries per second for the city.
  • One Redis primary handles this with headroom, plus a replica. A global footprint of hundreds of cities fits in tens of shards, many small cities sharing one.
  • Memory per city: 100,000 drivers × about 300 bytes = 30 MB. Trivial.

Locks.

  • About 1,500 rides per second × about 1.5 offers each ≈ 2,250 lock acquisitions per second globally, plus failed attempts in hotspots, perhaps 10,000 operations per second at worst.
  • Sharded by region, each lock shard sees a few hundred to a few thousand. Negligible.

Kafka for location history.

  • 625,000 messages per second × about 120 bytes with keys ≈ 75 MB/s ingest at peak, or about 225 MB/s across replicas with replication factor 3.
  • With partitions handling roughly 5 to 10 MB/s each, that is about 10 to 15 partitions of throughput. In practice you would use many more, for example 64 to 256 across regional clusters, so consumers can parallelise.
  • Retention: 3 days hot ≈ 26 billion × 3 × 120 bytes ≈ 9.4 TB per replica, about 28 TB with replication. Archive to object storage as columnar files.

Dispatch workflows. About 22,500 concurrent workflows and about 7,500 history events per second at peak, as computed in Deep Dive 5. With 5 history events of about 1 KB each per workflow, 30 million workflows per day × 5 KB ≈ 150 GB per day of workflow history, kept for about 7 days (roughly 1 TB). Modest.

Trip database.

  • 12,000 state writes per second at peak globally. The largest region handles perhaps 15 percent of that, about 1,800 per second, which a single well-provisioned PostgreSQL or MySQL primary can serve. Shard by region, and within very large regions by city.
  • Storage: 30 million rides per day × about 2 KB per ride with offers ≈ 60 GB per day, about 22 TB per year before archiving.

Matching latency budget, from tap to first offer on the driver's phone:

StepTypical
Request to Ride Service, ride insert, queue publish30 to 80 ms
Queue to consumer to workflow start10 to 50 ms
Geo query, 7 to 19 cells1 to 5 ms
One-to-many ETA for 20 candidates20 to 60 ms
Rankingunder 5 ms
Lock and offer row5 to 15 ms
Push over live connection to the driver50 to 300 ms on mobile networks
Total, without batchingabout 0.2 to 0.5 s

With a 2-second batch window, the first offer arrives in about 1 to 2.5 seconds. Either way, nearly all of the rider's wait is spent waiting for the driver's decision, not on system latency.

Deep Dive: the connection gateway and pushing to millions of phonesShow

Every real-time feature depends on the connection gateway: location ingestion, offers, live tracking and status changes. It is worth designing on its own terms. See Pattern: Pushing Realtime Updates.

Keeping connections alive on mobile networks.

  • Mobile carriers and home routers drop idle connections, often after a few minutes and sometimes much sooner. The app and the gateway exchange keepalive pings every 20 to 60 seconds. For an online driver, location updates already serve as keepalives.
  • When the phone switches from Wi-Fi to cellular, or passes through a tunnel, the connection dies. The app reconnects with exponential backoff and jitter, so a regional network blip does not become a synchronised reconnect storm.
  • Protocols that resume a session without a full handshake reduce reconnect cost. TLS session resumption helps, and QUIC (the transport under HTTP/3) can migrate a connection across network changes.

Finding the connection that holds a user. An offer for driver 123 is produced by a dispatch workflow running somewhere in the region. It must reach whichever gateway node holds driver 123's connection. Two common designs:

  • Connection directory. When a connection opens, the gateway writes driver:123 → gateway-node-17 with a TTL into Redis, refreshed by keepalives. Senders look up the node and call it directly, or publish to that node's personal channel.
  • Pub/sub by user. Each gateway subscribes to channels for the users it holds, for example user:123 in Redis pub/sub, or a partition of a message bus mapped by user id. Senders publish without knowing where the user is.

Redis pub/sub is fire-and-forget: if nobody is subscribed at that moment, the message vanishes. That is acceptable for live positions, which are superseded every few seconds anyway, but not for offers or status changes. Those are also persisted (the offer row, the ride status), so a reconnecting app can fetch them.

Resuming without gaps. Give each user's stream of important events a sequence number. On reconnect, the app sends the last sequence it saw, and the gateway replays anything newer from a short buffer, or the app re-fetches current state with GET /v1/rides/{id}. Clients should treat the live stream as a hint and the API as the truth. Then a lost message costs a few seconds of delay at worst, never a wrong state.

Mobile push as a backup channel. When the driver app is backgrounded or the connection is down, send the offer via APNs or FCM as well. These services typically deliver within seconds, but they do not guarantee delivery, and the operating system may delay or coalesce notifications under power-saving rules. So:

  • Never rely on push alone for time-critical offers.
  • Measure delivery-to-display latency per platform.
  • Shorten the effective offer window when only push is available, and move to the next driver early if no device acknowledgement arrives.

Sizing and draining.

  • Gateways are memory-bound, not CPU-bound: they hold mostly idle sockets with small buffers.
  • Deploy by draining. Stop accepting new connections on a node, then close existing ones gradually over several minutes with a "reconnect elsewhere" hint. That way 100,000 phones do not reconnect in the same second.
  • Spread nodes across availability zones. Losing a zone's gateways means a reconnect wave of a third of the users, which the remaining nodes must absorb with headroom.

Fan-out for live tracking. Each active trip has exactly one or two subscribers (the rider, plus anyone the rider shared the trip with), so fan-out is narrow but very wide in count: about 250,000 pushes per second spread over all gateways. Two refinements:

  • Downsample positions for viewers who are not the rider, for example shared-trip viewers every 10 seconds.
  • Send deltas or compact binary messages. At this rate, a 30-byte message instead of a 300-byte JSON object saves over 60 MB/s of egress at peak.
Deep Dive: what real ride-hailing platforms have sharedShow

The descriptions below come from public talks, open-source projects and engineering blog posts. Internal details change over time and are not all public, so treat them as illustrations of the ideas in this case study, not as current architecture.

  • Dispatch as a sharded, in-memory, real-time system. Uber engineers described their dispatch system, publicly called DISCO, in talks around 2015. It kept supply (drivers) and demand (riders) state in memory, partitioned by geography using S2 cells, and used Ringpop to route requests to the process that owns a given cell or entity. The same talks described the driver's phone holding encrypted trip state as a disaster-recovery aid.
  • Ringpop. An open-source library (originally in Node.js) that gives an application cluster gossip-based membership (SWIM-style) and a consistent-hash ring, with request forwarding to the owner of a key. It is a building block for application-level sharding without a separate coordination service per request.
  • H3. Uber open-sourced its hexagonal hierarchical grid in 2018. It has become widely used for spatial aggregation (supply and demand, pricing, ETA statistics, analytics), beyond ride-hailing.
  • Cadence, then Temporal. Uber built Cadence, a durable workflow engine, and open-sourced it. Its creators later founded Temporal, which continued the model. Long-running business processes with timers, retries and human steps, such as dispatch, are the motivating use case.
  • Schemaless and Docstore. Uber described Schemaless (2016) as an append-friendly, sharded datastore built on MySQL for trips and other high-volume data, and later Docstore as a successor general-purpose store. The pattern is sharded relational storage with a simple data model, not an exotic database.
  • ETA with learned corrections. Uber described DeepETA (2022), a deep-learning model that predicts the residual between the routing engine's ETA and observed arrival times, served at very high request rates with tight latency budgets.
  • Batched, marketplace-wide optimisation. Several ride-hailing companies have described dispatch as a marketplace optimisation problem (matching, pricing and driver positioning together) rather than nearest-driver lookup. The details are mostly proprietary.

The common thread matches this case study:

  • Keep live supply and demand in memory, sharded by geography.
  • Make dispatch durable through workflows.
  • Store trips in sharded, strongly consistent storage.
  • Treat ETA and pricing as data and ML problems fed by the location stream.
Deep Dive: failure walkthroughsShow

1. A Redis primary for a big city fails at rush hour. Sentinel or Cluster promotes the replica within a few seconds. Asynchronous replication means the newest roughly 1 second of positions and a handful of locks are missing.

  • Positions: drivers' next updates, within about 4 seconds, refill the index.
  • Locks: two workflows might now offer the same driver. The driver sees an offer, possibly a second one replacing it. Only one accept transaction can commit, and the other workflow's offer fails on the driver row's current_offer_id and moves on.
  • Impact: a few seconds of slightly worse matching in one city, with no double assignment.

2. A deploy introduces a bug that makes matching workers crash on start. Queue lag climbs on the city's dispatch partitions, and the alert on oldest-request age fires within a minute. Requests are safe in the queue and the workflows already started are durable. Roll back. The backlog drains in seconds once workers recover, because each request needs only milliseconds of consumer time. Riders saw "finding your driver" for longer, and some cancelled. That cost is real, which is why canary deploys per region matter.

3. The stadium empties. 40,000 requests arrive in 10 minutes from 3 H3 cells.

  1. The forecast-based pre-scale already added matching capacity and began a mild surge 15 minutes before the end, drawing drivers towards the venue.
  2. Requests are routed to the venue's pickup-zone flow, and the batch matcher assigns drivers from the staging-lot queue.
  3. Riders see honest wait estimates.
  4. The fare-estimate cache absorbs repeated price checks, and per-user rate limits stop scripted refreshes.

Without these, thousands of workflows would race for the same 200 nearby drivers, most lock attempts would fail, and riders would see repeated "no drivers" errors.

4. A region's trip database primary fails. Failover to the synchronous replica takes about 30 seconds.

  • During it, accepts and trip events for that region fail. Apps retry with backoff and idempotency, and dispatch workflows retry their activities.
  • The live map and tracking keep working, because they use the location path.
  • Riders see "connecting" for half a minute; drivers' "start trip" taps complete after failover.
  • No trip is lost, because the replica was synchronous.

5. A whole cloud region goes down. DNS and global load balancing move traffic to the standby region:

  • Driver and rider apps reconnect, and the geo index refills within seconds.
  • The trip database replica in the standby region is a few seconds behind. Trips accepted in those seconds may be missing. Reconnecting driver apps upload their active-trip state, and the system reconciles it with the replica.
  • Dispatch workflows that had not replicated are restarted from the rides still in requested state.
  • Expect minutes of disruption, not hours. Staff-level answers name the recovery point objective (seconds of trip writes) and the recovery time objective (minutes) explicitly.

6. GPS goes haywire downtown. A tall-building area produces fixes scattered by 100 metres. Map matching and Kalman smoothing keep the displayed position on plausible roads. Matching uses the smoothed position plus heading, and pickup ETA errors in the area rise. Monitoring per area shows it, and the learned ETA correction for that area adapts over time.

Deep Dive: a 45-minute interview plan and common variantsShow
MinutesWhat to do
0 to 5Requirements: fare estimate, request, match, accept or decline, navigate. Non-functional: match within 1 minute, no double assignment, burst handling. Put ratings, scheduling and categories below the line.
5 to 10Entities (Rider, Driver, Fare, Ride, Location, Offer). API with fare id in the ride request and identity from the token. Quick capacity: location updates per second.
10 to 20High-level design: gateway, Ride Service, Location Service with geo index, Matching Service, notifications, database. Walk through each functional requirement.
20 to 30Deep dive 1: location ingestion and proximity search, in-memory geo index, geohash or H3 rings, staleness, adaptive updates.
30 to 38Deep dive 2: driver locking (status column versus Redis TTL lock plus conditional accept), timeouts (delay queue versus durable workflow).
38 to 45Deep dive 3: no dropped requests (queue with commit after ownership), hotspots, geo-sharding and boundaries. Wrap up with failure modes.

Variants and what changes.

  • "Design food or grocery delivery." There are three parties (customer, store, courier) and a preparation time. Matching optimises courier arrival against the food-ready time, and couriers can batch several orders. Inventory availability from nearby stores and warehouses becomes central. See the Local Delivery Service case study.
  • "Design shared or pooled rides." Matching becomes a vehicle-routing problem: insert a new rider into an existing route if the detour for current riders stays within a limit. Candidate generation includes on-trip vehicles, and the solver evaluates insertions.
  • "Design scheduled rides." A job scheduler triggers dispatch shortly before the pickup time, with pre-matching to drivers who opt in. See the Distributed Job Scheduler case study.
  • "Design a proximity service such as Yelp." The points are static, so a quadtree or geohash index in a durable store with caching fits. There is no locking and no live stream. See the Proximity Service case study.
  • "Design scooter or bike sharing." The vehicles report location; users pick and unlock them. The locking problem moves to the vehicle, a reservation with TTL. Battery levels and rebalancing logistics replace driver acceptance.
  • "Design an airport taxi queue." Geofences and FIFO queues of drivers per zone, plus fairness rules. This is a small, interesting sub-problem.
Deep Dive: observability and SLOsShow

Rider-facing SLOs.

  • 99 percent of ride requests get a first driver offer within 3 seconds, or a clear "no drivers" result within 60 seconds.
  • 99.99 percent of accepted rides have exactly one driver. Treat any double assignment as a severity-one incident.
  • 99.9 percent of trip state transitions succeed within 1 second, including retries.
  • Live driver position on the rider's screen is at most 5 seconds old, 99 percent of the time.

Key metrics, per city and per area.

  • Time to match distribution, and the share of requests that end in NoDrivers.
  • Offer acceptance rate and decline reasons; offers per accepted ride.
  • Pickup ETA error (predicted versus actual), split by area and time of day.
  • Stale-driver ratio: the share of geo-index entries older than the freshness threshold. A spike means ingestion trouble.
  • Location ingest rate compared with the expected rate from online drivers. A drop means connectivity or gateway problems.
  • Lock contention: failed SET NX per successful offer. High values mean a hotspot that needs batching.
  • Queue lag and oldest-request age per dispatch partition.
  • Accept transaction conflicts (0-row updates) by reason: expired offer, cancelled, driver changed.
  • Dependency health: ETA, pricing and payment latency and error rates, and circuit-breaker states.

Tracing. Carry a trace id through request, queue, workflow, ETA calls, lock, offer, driver response and accept transaction. "Why did this rider wait 50 seconds?" should be answerable from one trace, for example "3 drivers did not respond, then radius expansion".

Marketplace dashboards. Supply and demand heat maps per H3 cell, surge multipliers over time, and driver utilisation. These are as important to operators as technical metrics, because a perfectly healthy system can still serve riders badly if supply is in the wrong place.

Testing. Replay recorded days of location and request streams against new matching code in a simulator, comparing wait times, ETAs and driver utilisation before shipping. Marketplace changes are hard to evaluate in production A/B tests, because riders and drivers in the same city interact. Use switchback experiments (alternating treatment over time windows) or city-level comparisons.

See Observability: Logs, Metrics and Traces and Capacity Planning and Load Testing.

Key Takeaways#

  • Two very different kinds of state. Driver locations are a high-throughput, loss-tolerant, latest-value-wins stream. Ride assignment is low-rate, strongly consistent state. Give each its own store and scaling strategy.
  • Keep the live location index in memory. Use Redis GEO or a custom cell index (H3, S2, geohash), sharded by region. Durability barely matters because the index refills within one update interval. History goes to Kafka and the data lake.
  • Use cells and rings for proximity. B-trees on latitude and longitude do not answer "near me". Cells plus neighbouring rings, followed by exact distance and then ETA ranking, do. Always include neighbours to avoid the edge problem.
  • The client is part of the design. Adaptive update intervals, buffering offline points, smoothing and dead reckoning cut load and improve accuracy.
  • Lock drivers fast and commit carefully. A Redis SET NX PX lock with TTL keeps offers exclusive and self-releasing. The final accept is a single-shard conditional transaction fenced by the offer_id, so lock loss or late responses can never double-assign.
  • Dispatch is a durable, human-in-the-loop workflow. Offer, wait 10 seconds, move on, within a 1-minute budget. Temporal or Cadence workflows, or idempotent delay-queue checks, survive crashes without stranded rides.
  • Never drop a request. Put a durable, region-partitioned queue between request and matching, commit only after ownership is durable, and autoscale on lag and request age.
  • Batched matching beats greedy in dense areas. Framed as a minimum-cost assignment problem, it trades a couple of seconds of waiting for minutes of better pickups.
  • ETA is routing plus learning. Use contraction-hierarchy-style routing on a live traffic graph built from the location stream, plus a learned residual correction.
  • Shard by geography. Do it for services, queues and data, with special handling at boundaries and hotspots (pickup zones, batching, surge). Treat privacy, fraud and graceful degradation as first-class requirements.