Skip to content

Lesson 30 of 38Case studies

Design a Ride-Sharing App

Design Uber-style matching with high-rate location updates, geohash indexing, nearby-driver search, trip states, and surge.

20 min read0/4 questions

Ride-sharing is a system design classic because it is a moving target: millions of drivers report their location every few seconds, and a rider expects a match in seconds from whoever is closest right now. Ordinary database indexes do not answer "who is near this point?" well, so you need a geospatial index, and you need to keep it fresh at hundreds of thousands of writes a second.

Requirements

Functional

  • Drivers go online and their app sends its location every few seconds.
  • A rider sees nearby cars on the map and requests a ride from a pickup point.
  • The system matches the rider with a nearby available driver, who accepts or declines.
  • Both sides track the trip live: driver arriving, trip in progress, completed.
  • Price is quoted up front, with surge pricing when demand outstrips supply.

Non-functional

  • Match within a few seconds; location on the map no more than a few seconds old.
  • A driver is never given two trips at once, and a ride is never given to two drivers.
  • Highly available in every city; an outage strands people.

Out of scope: payments (see the payments lesson), routing and maps engine internals, ratings, driver onboarding, pooled rides.

Back-of-the-envelope numbers

QuantityMathResult
Drivers online at peakabout 3 million
Location updates3M drivers / every 4 sabout 750,000 writes/s
Rides20M a day / 86,400about 230 requests/s (peak about 1,000/s)
Live location state3M × about 100 bytesabout 300 MB (fits in memory)
Location history750k/s × 100 B × 86,400about 6.5 TB a day (cold storage)

The striking number is 750,000 writes a second for location, against only about 1,000 ride requests a second. The latest location is small enough to live in memory, and it is constantly overwritten, so it should never sit in a disk-based relational table.

Quick check
Where should the current location of each online driver live?
Need a nudge? A hint rules out a wrong answer.

API

// driver app, over a persistent WebSocket
{ "type": "location", "lat": 51.5079, "lng": -0.1270, "heading": 92, "ts": 1792500000 }
 
POST /v1/rides/quote     { "pickup": {...}, "dropoff": {...} }   → { "quote_id": "q_7", "price": 1840, "surge": 1.4 }
POST /v1/rides           { "quote_id": "q_7" }                    → { "ride_id": "r_91", "status": "matching" }
GET  /v1/rides/r_91                                                → { "status": "driver_arriving", "driver": {...}, "eta_s": 180 }
POST /v1/rides/r_91/accept   (driver)
POST /v1/rides/r_91/cancel

Data model

  • driver_locations (in memory): driver_id → (lat, lng, geohash, status, updated_at), plus an index from geohash cell to the drivers in it.
  • trips (Postgres, sharded by city): ride_id, rider_id, driver_id, status, pickup, dropoff, quote, timestamps. The status column is guarded by a state machine.
  • location history: an append-only stream (Kafka) written to object storage for analytics, fraud, and fare disputes.

High-level design

Ride-sharing architecture
Real-time locationRider appRider appDriver appDriver appRider APIRider APIDriver gw: WebSocketsDriver gwWebSocketsMatchingMatchingPricing: surgePricingsurgeTrips: per cityTripsper cityGeo index: in memoryGeo indexin memoryLocations: KafkaLocationsKafkaHistory: S3HistoryS3HTTPSwsquotestatenearbyofferupdate

Location write path. Every 4 seconds each driver's app sends a ping over its WebSocket. The gateway updates the driver's cell in the in-memory geo index and appends the ping to a stream for history.

1/7

Deep dive 1: geospatial indexing with geohash

To find "drivers near me" you need nearby points to be near each other in the index. A geohash does that by turning a latitude and longitude into a short string. It splits the world in half by longitude (one bit), then by latitude (another bit), over and over, and writes the bits in base 32. Each extra character makes the cell 32 times smaller. Points that share a prefix are in the same cell.

LengthCell size (roughly)
439 km × 20 km
54.9 km × 4.9 km
61.2 km × 0.6 km
7153 m × 153 m

Here is central London at precision 6. The rider stands in gcpvj0.

Geohash cells around the rider (precision 6)
westeast
northgcpvhcgcpvj1gcpvj3
gcpvhbgcpvj0gcpvj2
southgcpuuzgcpuvpgcpuvr

The rider's pickup point encodes to gcpvj0, a cell about 1.2 km wide. Every driver ping is also encoded, and the index maps each cell to the drivers inside it.

1/4

Here is the encoder and a nearby-driver search. It finds the 9 cells, collects drivers in them, then sorts by real distance.

Pythongeohash_nearby.py
from math import asin, cos, radians, sin, sqrt B32 = "0123456789bcdefghjkmnpqrstuvwxyz" def geohash(lat: float, lon: float, precision: int = 6) -> str: lat_r, lon_r = [-90.0, 90.0], [-180.0, 180.0] out, ch, bits, even = [], 0, 0, True while len(out) < precision: rng, val = (lon_r, lon) if even else (lat_r, lat) mid = (rng[0] + rng[1]) / 2 if val >= mid: ch, rng[0] = ch * 2 + 1, mid else: ch, rng[1] = ch * 2, mid even, bits = not even, bits + 1 if bits == 5: out.append(B32[ch]) ch, bits = 0, 0 return "".join(out) def km(a, b): lat1, lon1, lat2, lon2 = map(radians, (*a, *b)) h = sin((lat2 - lat1) / 2) ** 2 + cos(lat1) * cos(lat2) * sin((lon2 - lon1) / 2) ** 2 return 6371 * 2 * asin(sqrt(h)) # Cell size at precision 6 (15 bits of longitude, 15 of latitude).DLAT, DLON = 180 / 2**15, 360 / 2**15 def nine_cells(lat, lon): return {geohash(lat + dy * DLAT, lon + dx * DLON) for dy in (-1, 0, 1) for dx in (-1, 0, 1)} drivers = { "d1": (51.5079, -0.1270), "d2": (51.5150, -0.1400), "d3": (51.5010, -0.1200), "d4": (51.5300, -0.1000), "d5": (51.4800, -0.2000),}index = {}for d, pos in drivers.items(): index.setdefault(geohash(*pos), []).append(d) rider = (51.5074, -0.1278)cells = nine_cells(*rider)candidates = [d for c in cells for d in index.get(c, [])]print("rider cell:", geohash(*rider))for d in sorted(candidates, key=lambda d: km(rider, drivers[d])): print(f"{d}: {km(rider, drivers[d]):.2f} km")print("not searched:", sorted(set(drivers) - set(candidates)))
Output
Press Run (⌘ Enter) to see what happens.

Driver d2 is only about 1.2 km away but sits outside the 9 cells. Real dispatchers widen the search (more rings of cells, or a coarser precision) until they have enough candidates.

Alternatives. A quadtree splits a square into four whenever it holds too many points, so dense downtown areas get small cells and empty countryside gets big ones. Uber built H3, a grid of hexagons, because every hexagon's six neighbours are the same distance away. Redis GEO (GEOADD, GEOSEARCH ... BYRADIUS) stores geohash-like scores in a sorted set and gives you radius queries out of the box. All of them do the same job: turn "near" into a cheap lookup.

Quick check
Riders want drivers within about 2 km. Which geohash precision should the index use for its cells?
Need a nudge? A hint rules out a wrong answer.

Deep dive 2: matching and the trip state machine

Matching is not "closest wins". The dispatcher ranks candidates by ETA (a car 400 m away across a river may be 12 minutes out), driver heading, and acceptance rate. It offers the ride to one driver at a time (or a few in parallel in busy cities) with a short timeout.

The crucial rule is that a driver and a ride are claimed atomically. Two riders' requests may pick the same nearby driver at the same moment. A conditional write settles it: SET driver:42:lock ride_91 NX EX 15 in Redis, or UPDATE drivers SET status = 'offered' WHERE id = 42 AND status = 'available'. Whoever changes the row wins; the other moves to the next candidate.

Trip states
  1. requestedrider confirmed a quote
  2. matchingoffers out to drivers
  3. driver_assigneda driver accepted
  4. driver_arrivedat the pickup point
  5. in_progressrider on board
  6. completedfare calculated, payment captured
  7. canceledby rider, driver, or timeout

The rider confirms. The trip enters matching while offers go out. If no driver accepts within about a minute, it ends canceled with a 'no cars available' message.

1/5
Put it in order6 steps

Put the happy-path trip states in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Quick check
Two ride requests pick driver 42 within the same millisecond. What prevents the driver getting both?
Need a nudge? A hint rules out a wrong answer.

Deep dive 3: surge pricing (high level)

Surge raises prices where riders outnumber drivers, which both rations rides and pulls drivers toward busy areas. The ingredients:

  1. Every minute, for each hexagon or geohash cell, count open requests (demand) and available drivers (supply) from the location and request streams.
  2. Compute a ratio and map it to a multiplier with caps and smoothing, so prices do not flicker between 1.0x and 2.5x every minute.
  3. Store the multiplier per cell in a cache; the quote service reads it. The quote locks the price for a few minutes so the rider pays what they saw.

A stream processor (Flink or Kafka Streams) does the counting in sliding windows. It is a read-mostly cache from the request path's point of view.

Bottlenecks, failures, and 10x scale

  • Location write load. Shard the geo index by city or region: London's drivers never need to be in the same process as Tokyo's. Within a big city, shard by cell.
  • Gateway failure. Drivers reconnect to another gateway. Their location goes stale for a few seconds; drivers with no ping for 30 seconds are treated as offline.
  • Hot spots. A stadium emptying produces thousands of requests in one cell. Batch-match riders and drivers in that area every couple of seconds instead of one at a time.
  • Data center loss. Run each city in an active region with a warm standby; trips in flight are recoverable from the trips table and the drivers' apps, which keep local state.
  • 10x: more geo shards (cities are independent, so this is easy), more gateways, and send pings less often when a car is parked or moving slowly.
Key terms
geohash
A string encoding of a location; each extra character shrinks the cell, and points sharing a prefix share a cell.
neighbour cells
The 8 cells around a geohash cell, searched too because a nearby point may sit across a cell edge.
quadtree
A tree that splits a region into four quadrants whenever it holds too many points, adapting to density.
ETA ranking
Ranking drivers by estimated drive time from the routing engine, not straight-line distance.
atomic claim
A conditional write that only one competing request can win, used so a driver is never double-booked.
surge multiplier
A per-area price factor derived from the ratio of ride demand to available drivers.