A ride-sharing service like Uber or Lyft matches a rider who wants to go somewhere with a nearby driver, in seconds, millions of times a day. Three things make it hard: drivers' phones stream hundreds of thousands of location updates per second, 'which available drivers are near this point?' must be answered instantly with a geospatial index, and each driver must be assigned to exactly one trip even when many dispatchers work at once. Around that core sit ETAs, a trip state machine, surge pricing and the handoff to payments.
Think of it like
A taxi dispatcher with a gridded city map
Picture an old dispatch office with a giant city map divided into numbered squares. Every few seconds each cab radios in and the dispatcher moves its pin to the right square. When a call comes in, the dispatcher looks only at the caller's square and the squares around it, picks the cab that can get there fastest (not the one that is closest as the crow flies, since there may be a river in between), radios the offer, and puts a 'reserved' flag on that cab so no colleague offers it a second fare. When a district gets more calls than cabs, prices go up until things balance out.
1. Requirements
Functional
- Riders see nearby cars, a fare estimate and a pickup ETA
- Riders request a ride; the system offers it to a suitable nearby driver
- Drivers go online or offline and accept or decline offers
- Both sides see each other's live location during pickup and the trip
- Trip lifecycle: arrive, start, complete, cancel
- Dynamic (surge) pricing when demand outstrips supply
- Charge the rider and record driver earnings after the trip
Non-functional
- Match within a few seconds; location updates visible within ~1–2 s
- Very high write throughput for driver locations
- A driver is never assigned to two trips; a trip never gets two drivers
- Payments are exactly-once in effect (no double charges)
- Highly available, especially in peak hours and on holidays
- Location data may be a few seconds stale; trip state may not
| In scope | Out of scope (mention, then park) |
|---|---|
| Location ingestion and the geospatial index | Map rendering and turn-by-turn navigation |
| Matching and dispatch, trip state machine | Ride pooling (shared rides) beyond a mention |
| ETAs, surge pricing | Driver onboarding, background checks, ratings |
| Payments handoff | Payment processing internals (see Design a Payment System) |
| Scaling by geography, failure handling | Food delivery and freight (similar core, different constraints) |
2. Back-of-the-envelope estimation
Assume 20 million trips per day worldwide and 2 million drivers online at the global peak, each sending a location update every 4 seconds. A location update (driver ID, latitude, longitude, heading, speed, timestamp) is about 100 bytes on the wire. See Back-of-the-Envelope Estimation.
Location updates
500k /s
2M drivers every 4 s
Ride requests
~230 /s
peaks above 1,000/s
Trips in progress
~280k
20-minute average
Live location set
~400 MB
soft state, in memory
3. API design
# Rider: price and ETA before requesting
POST /v1/fare-estimates
{ "pickup": { "lat": 40.7484, "lng": -73.9857 }, "dropoff": { "lat": 40.7061, "lng": -74.0087 }, "product": "standard" }
-> 200 { "quoteId": "q_81f", "fare": { "min": 21.5, "max": 26.0, "currency": "USD" },
"surgeMultiplier": 1.4, "pickupEtaSec": 240, "expiresAt": "2026-11-10T21:04:00Z" }
# Rider: request a ride with the quote (idempotent)
POST /v1/rides
Idempotency-Key: 3c9d-11aa
{ "quoteId": "q_81f", "paymentMethodId": "pm_22" }
-> 201 { "rideId": "r_5521", "state": "MATCHING" }
GET /v1/rides/r_5521 -> { "state": "DRIVER_ASSIGNED", "driver": {...}, "etaSec": 180 }
DELETE /v1/rides/r_5521 -> cancel (fee rules depend on state)
# Driver: availability, offers and trip events
PUT /v1/drivers/me/status { "status": "online", "product": "standard" }
POST /v1/rides/r_5521/accept -> 200 or 409 Conflict (offer expired or taken)
POST /v1/rides/r_5521/events { "type": "arrived" | "started" | "completed", "at": "..." }// driver -> server, every ~4 s (batched when the network is poor)
{ "type": "loc", "points": [ { "lat": 40.74852, "lng": -73.98561, "heading": 92, "speedMps": 7.4, "ts": 1762808640120 } ] }
// server -> driver: a ride offer that expires
{ "type": "offer", "rideId": "r_5521", "pickup": { "lat": 40.7484, "lng": -73.9857 },
"pickupEtaSec": 180, "estFare": 23.8, "expiresInSec": 15 }
// server -> rider during pickup and the trip
{ "type": "driver_loc", "rideId": "r_5521", "lat": 40.7461, "lng": -73.9879, "etaSec": 150 }- Persistent connections (WebSocket or a long-lived HTTP/2 or gRPC stream) carry location updates and offers; opening a new request every 4 seconds would waste battery and handshakes. See Real-time Communication.
- Quotes lock in the price. The request references a
quoteId, so the rider pays the fare and surge they agreed to even if surge changes a second later. - Accept can fail with 409. Offers expire, and the server, not the phone, decides who gets the trip.
4. Data model
| Data | Store | Why |
|---|---|---|
| Live driver location and status | In-memory geo index sharded by region (custom service or Redis GEO), entries expire after ~30 s | Soft state, 500k writes/s, sub-10 ms nearby queries |
| Location history | Kafka → data lake / time-series store | Replayable stream for ETAs, fraud checks, receipts and analytics |
| Trips | Sharded relational DB (MySQL/Postgres) or a strongly consistent document store | Transactional state changes, conditional updates, audit history |
| Riders, drivers, vehicles | Relational, cached | Profile data, low write rate |
| Surge multipliers per cell | Key-value cache with short TTL | Recomputed every minute or two; read by every quote |
| Payments and ledger | Separate payment system with its own database | Different consistency, compliance and audit needs. See Design a Payment System |
CREATE TABLE trips (
trip_id BIGINT PRIMARY KEY,
rider_id BIGINT NOT NULL,
driver_id BIGINT,
state VARCHAR(24) NOT NULL, -- REQUESTED, MATCHING, DRIVER_ASSIGNED, ...
quote_id VARCHAR(32) NOT NULL, -- locked fare and surge
pickup_lat DOUBLE PRECISION, pickup_lng DOUBLE PRECISION,
dropoff_lat DOUBLE PRECISION, dropoff_lng DOUBLE PRECISION,
final_fare NUMERIC(10, 2),
version INT NOT NULL DEFAULT 0, -- bumped on every transition
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL
);
-- Assign a driver only if nobody else has: exactly one winner.
UPDATE trips
SET driver_id = :driver, state = 'DRIVER_ASSIGNED', version = version + 1, updated_at = now()
WHERE trip_id = :trip AND state = 'MATCHING';
-- 1 row updated -> this driver got the trip; 0 rows -> canceled or already assigned5. High-level architecture
Phones keep a persistent connection to an edge gateway. The location service ingests updates and publishes them to Kafka, from which the geo index keeps the latest position of every driver. The trip service owns the trip state machine; when a ride is requested it asks pricing for the locked quote and dispatch for a driver, and dispatch queries the geo index and the ETA service. Completed trips flow to payments as events. Press play to follow each path.
6. Deep dive: ingesting locations
- Keep only the latest in the hot path. The geo index needs one position per driver. History goes to Kafka and on to cheaper storage for analytics, ETA training and dispute resolution.
- Adapt the update rate. Every ~4 s while online is a common figure, faster during a trip or when moving quickly, slower when parked. Fewer updates mean less battery drain and fewer writes.
- Reject bad fixes. GPS jumps in urban canyons. Drop points that imply impossible speeds, ignore timestamps older than the last accepted one, and snap positions to the road network (map matching) before using them for ETAs.
- Expire silently. Each driver entry carries a TTL refreshed by updates; a phone that loses signal or crashes disappears from search within ~30 s without any explicit 'offline' message.
- Partition by geography. Updates are routed to the shard that owns the driver's region, so each in-memory index only handles its own city's traffic. See Sharding & Partitioning.
7. Deep dive: geospatial indexing
The core query is 'available drivers within r km of this point'. A relational table with separate indexes on latitude and longitude is a poor fit: a B-tree can range-scan one dimension, so the database finds every driver in a thin latitude band around the globe and then filters by longitude. Geospatial indexes map two dimensions onto cells so that nearby points share a key. The simulation above shows the two classic approaches, geohashes and quadtrees.
Geohash
- Interleave longitude and latitude bits, then encode 5 bits per base32 character
- Each extra character makes the cell 32× smaller; a shared prefix means a shared cell
- Works as a plain string key in any store (Redis GEO uses a 52-bit geohash as a sorted-set score)
- Fixed grid: busy downtown cells and empty rural cells have the same size
Quadtree
- Recursively split a square into four children when it holds more than K points
- Adapts to density: tiny cells in Manhattan, huge cells over farmland
- Natural in memory; a lookup walks from the root to a leaf
- Moving points need removes and inserts, and splits or merges, as drivers move
Hexagonal grid (H3)
- Uber open-sourced H3 in 2018: hexagons at 16 resolutions
- All six neighbors are the same distance away (squares have edge and corner neighbors)
- Good for aggregating supply, demand and surge per area
- Google S2 (cells on a cube projected onto the sphere) is a popular alternative
| Geohash length | Cell size (approx., at the equator) | Typical use |
|---|---|---|
| 4 | 39 km × 19.5 km | A metro area |
| 5 | 4.9 km × 4.9 km | A district; coarse supply counts |
| 6 | 1.2 km × 0.61 km | Nearby drivers in a city |
| 7 | 153 m × 153 m | A few blocks |
| 8 | 38 m × 19 m | A building or pickup spot |
- 1
Pick a precision
Choose a cell size comparable to the search radius (geohash length 6 for ~1 km in a city, or H3 resolution 8–9).
- 2
Collect cells
Compute the pickup point's cell and its neighbors; widen by another ring if the radius is larger than a cell.
- 3
Read buckets
Each cell maps to the set of available drivers currently inside it, so the candidate set is a handful of in-memory lookups.
- 4
Filter precisely
Drop drivers beyond the radius by haversine distance, and those with the wrong vehicle type or status.
- 5
Rank by ETA
Hand the shortlist to the ETA service; road time, not distance, decides the match.
8. Deep dive: matching and dispatch
The simplest dispatcher is greedy: when a request arrives, offer it to the available driver with the lowest pickup ETA. It is easy to reason about but locally optimal: giving the nearest driver to rider A might leave rider B, a block away, with a 12-minute wait. Large platforms improve on this in several ways.
Greedy, one request at a time
- Offer to the best driver by ETA; on decline or timeout, try the next
- Lowest latency per request
- Can make poor global choices at busy moments
Batched matching
- Collect requests and drivers over a short window (a second or two)
- Solve an assignment problem minimizing total pickup time
- Better overall wait times for a tiny added delay
Look-ahead dispatch
- Consider drivers about to finish a trip nearby
- Use demand forecasts to position idle drivers
- More complex; needs good ETA and forecast models
Whatever the policy, the system must guarantee that a driver is offered one ride at a time and that a trip ends up with one driver. Dispatchers run as many instances, so two of them can pick the same idle driver in the same millisecond. Two guards solve it: a short-lived driver reservation (a lock with a TTL, taken before the offer is sent) and the conditional update on the trip row when the driver accepts. See ACID, BASE & Isolation Levels and Distributed Transactions.
9. Deep dive: the trip state machine
REQUESTED ──► MATCHING ──► DRIVER_ASSIGNED ──► DRIVER_ARRIVED ──► IN_PROGRESS ──► COMPLETED ──► PAID
│ │ │ │
▼ ▼ ▼ ▼
NO_DRIVERS CANCELED_BY_RIDER CANCELED_BY_RIDER / NO_SHOW PAYMENT_FAILED
CANCELED_BY_DRIVER (fee may apply) (retry, then collect later)
(back to MATCHING)| Transition | Triggered by | Guard |
|---|---|---|
MATCHING → DRIVER_ASSIGNED | Driver accepts an offer | WHERE state = 'MATCHING'; driver reservation held |
DRIVER_ASSIGNED → DRIVER_ARRIVED | Driver taps 'arrived' (or a geofence fires) | Driver near pickup point |
DRIVER_ARRIVED → IN_PROGRESS | Driver starts the trip | Optional PIN check from the rider |
IN_PROGRESS → COMPLETED | Driver ends the trip | Compute final fare; write outbox event |
DRIVER_ASSIGNED → MATCHING | Driver cancels | Release the driver; re-dispatch with priority |
* → CANCELED_BY_RIDER | Rider cancels | Fee rules depend on the state and elapsed time |
10. Deep dive: ETAs
ETAs drive matching, the price quote and what the rider sees, so they are computed constantly. A routing engine runs shortest-path searches over a road graph whose edge weights are travel times, updated from the speeds observed in drivers' own GPS traces. Plain Dijkstra's Algorithm is too slow for continent-sized graphs at this request rate, so engines use A* Pathfinding and preprocessing techniques such as contraction hierarchies that answer queries in milliseconds.
- Live traffic: aggregate recent speeds per road segment from the location stream; fall back to historical speeds for that hour and weekday.
- Learned correction: a model adjusts the routing engine's estimate using features such as time of day, weather and pickup type. Uber described a deep learning model for this, DeepETA, in 2022.
- Batch queries: dispatch asks for ETAs from 10–20 drivers to one pickup at once (a one-to-many query), which routing engines answer far faster than 20 separate searches.
- Cache coarse answers: cell-to-cell ETAs for the next few minutes serve fare estimates cheaply; precise ETAs are computed only for real candidates.
11. Deep dive: surge pricing
When requests in an area outpace available drivers, wait times explode. Surge pricing raises prices in that area, which both reduces marginal demand and draws drivers toward it. It is a streaming aggregation per cell: count demand (requests and app opens) and supply (available drivers) over a sliding window, and turn the ratio into a multiplier.
12. Deep dive: the payments handoff
- 1
Authorize up front
When the ride is requested or starts, place an authorization hold on the rider's card for the estimated fare, so a declined card is discovered before the trip, not after.
- 2
Capture after completion
On
TripCompleted, capture the final amount (which may differ from the hold within limits) using the trip ID as the idempotency key. - 3
Retry safely
Kafka redelivers events and PSP calls time out; idempotency keys make every retry safe. Failed captures move the trip to
PAYMENT_FAILEDand into a collection flow. - 4
Record both sides
A double-entry ledger records the rider charge, the platform fee and the driver's earnings; driver payouts are batched later. See Design a Payment System.
13. Scaling, bottlenecks and failures
| Failure or hotspot | Mitigation |
|---|---|
| Geo index node lost | It is soft state: a replacement rebuilds from the Kafka stream or simply from the next round of updates, which arrive within ~4 s |
| New Year's Eve in one city | Split the city's shard by cell ranges; autoscale location ingestion; batched matching reduces wasted offers |
| Dispatch instance crashes mid-offer | Driver reservations expire via TTL; the trip stays in MATCHING and another instance resumes dispatch |
| Rider cancel races driver accept | Both are conditional updates on the trip's state; exactly one wins and the other gets a clear error |
| ETA service slow | Fall back to cached cell-to-cell ETAs or straight-line estimates for ranking. See Resilience Patterns |
| Data center failure | Trip DB replicated across zones and regions; Uber has described using state held on drivers' phones to help restore in-flight trips after a failover |
| Payment provider outage | Trips complete normally; payment events queue up and are captured when the provider recovers |
- Stateless services (trip, pricing, dispatch workers) scale horizontally; the stateful pieces are the geo index (soft) and the trip DB (hard). See Scalability.
- Rate limits and abuse checks on requests and cancellations protect drivers and stop fake demand from triggering surge. See Rate Limiting.
- Observability: match rate, time to match, pickup ETA accuracy and offer acceptance per city are the health metrics that matter. See Observability.
Implementation
Encodes points as geohashes, keeps drivers bucketed by cell, and answers 'drivers within r km' by scanning the surrounding rings of cells and filtering by haversine distance.
import math
from dataclasses import dataclass
BASE32 = "0123456789bcdefghjkmnpqrstuvwxyz"
KM_PER_DEG = 111.32
def encode(lat: float, lng: float, precision: int) -> str:
lat_lo, lat_hi, lng_lo, lng_hi = -90.0, 90.0, -180.0, 180.0
out, bits, ch, lng_bit = [], 0, 0, True
while len(out) < precision:
if lng_bit:
mid = (lng_lo + lng_hi) / 2
if lng >= mid:
ch, lng_lo = (ch << 1) | 1, mid
else:
ch, lng_hi = ch << 1, mid
else:
mid = (lat_lo + lat_hi) / 2
if lat >= mid:
ch, lat_lo = (ch << 1) | 1, mid
else:
ch, lat_hi = ch << 1, mid
lng_bit = not lng_bit
bits += 1
if bits == 5:
out.append(BASE32[ch])
bits, ch = 0, 0
return "".join(out)
def cell_degrees(precision: int) -> tuple[float, float]:
total = precision * 5
return 180 / 2 ** (total // 2), 360 / 2 ** math.ceil(total / 2)
def haversine_km(a_lat, a_lng, b_lat, b_lng) -> float:
p = math.pi / 180
h = (math.sin((b_lat - a_lat) * p / 2) ** 2
+ math.cos(a_lat * p) * math.cos(b_lat * p) * math.sin((b_lng - a_lng) * p / 2) ** 2)
return 2 * 6371 * math.asin(math.sqrt(h))
def cells_around(lat: float, lng: float, precision: int, rings: int) -> set[str]:
d_lat, d_lng = cell_degrees(precision)
c_lat = (math.floor((lat + 90) / d_lat) + 0.5) * d_lat - 90
c_lng = (math.floor((lng + 180) / d_lng) + 0.5) * d_lng - 180
cells = set()
for dy in range(-rings, rings + 1):
for dx in range(-rings, rings + 1):
y = c_lat + dy * d_lat
if -90 < y < 90:
x = (c_lng + dx * d_lng + 540) % 360 - 180 # wrap the antimeridian
cells.add(encode(y, x, precision))
return cells
@dataclass
class Driver:
id: str
lat: float
lng: float
class GeoIndex:
def __init__(self, precision: int = 6):
self.precision = precision
self.cells: dict[str, dict[str, Driver]] = {}
self.cell_of: dict[str, str] = {}
def upsert(self, d: Driver) -> None:
cell = encode(d.lat, d.lng, self.precision)
prev = self.cell_of.get(d.id)
if prev is not None and prev != cell:
self.cells.get(prev, {}).pop(d.id, None) # crossed a cell boundary
self.cells.setdefault(cell, {})[d.id] = d
self.cell_of[d.id] = cell
def nearby(self, lat: float, lng: float, radius_km: float, limit: int = 20) -> list[Driver]:
d_lat, d_lng = cell_degrees(self.precision)
min_side = min(d_lat * KM_PER_DEG, d_lng * KM_PER_DEG * math.cos(math.radians(lat)))
rings = max(1, math.ceil(radius_km / min_side))
found = []
for cell in cells_around(lat, lng, self.precision, rings):
for drv in self.cells.get(cell, {}).values():
km = haversine_km(lat, lng, drv.lat, drv.lng)
if km <= radius_km:
found.append((km, drv))
found.sort(key=lambda t: t[0])
return [drv for _, drv in found[:limit]]Key takeaways
- Driver locations are high-volume soft state: keep the latest position in an in-memory geo index, stream history to a log, and let stale entries expire.
- Geospatial indexes turn 2D proximity into cell keys (geohash, quadtree, S2 or H3); always search the neighboring cells and then filter by true distance.
- Rank candidates by road ETA, not straight-line distance; batched matching improves overall wait times at busy moments.
- Guarantee one driver per trip and one trip per driver with a TTL reservation plus a conditional state update.
- Model the trip as an explicit state machine with conditional transitions and outbox events that drive payments and notifications.
- Shard everything real-time by geography; surge is a per-cell streaming aggregation locked into each quote.
Common pitfalls
- Writing every location update to a relational database row, which cannot sustain 500k writes/s and gains nothing.
- Searching only the pickup's own geohash cell and missing a driver 50 m away across a boundary.
- Matching on straight-line distance, which sends drivers across rivers and highways.
- Letting two dispatchers offer the same driver different rides, or assigning on accept without a conditional update.
- Calling the payment provider synchronously in the trip-completion path, so a PSP outage blocks trips.
Interview tips
- Estimate location writes first (drivers ÷ update interval); it immediately justifies in-memory soft state.
- Explain geohash precision and the neighbor search, and mention quadtrees for uneven density and H3 for aggregation.
- Walk through a request-to-accept race (rider cancels while driver accepts) and show how conditional updates resolve it.
- Keep pricing and payments decoupled from matching, and say why: availability and latency of the core loop.
Real-world applications
- Uber: has described location updates every few seconds from driver apps, open-sourced the H3 hexagonal grid (2018) and the Ringpop sharding library (2015), and published work on ETA prediction (DeepETA, 2022) and batched matching.
- Lyft, Grab, Ola, Bolt and DiDi run the same core loop of location ingestion, geo index, dispatch and surge, with market-specific variations.
- Food delivery (DoorDash, Uber Eats) adds restaurant preparation time to the matching problem and often batches several orders per courier.
- Redis GEO commands (
GEOADD,GEOSEARCH) and PostGIS provide geospatial indexing for smaller location-based apps.
Test yourself
2 million online drivers each send a location every 4 seconds. What write rate must the location pipeline sustain?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.