Design: ride hailing (Uber, Lyft)

In one sentence

Drivers stream GPS every few seconds into an in-memory index of H3 cells; a request searches nearby cells, ranks drivers by road ETA, claims one atomically, and a trip state machine runs to payment.

Locations flow into an in-memory index; dispatch reads it, offers one driver at a time, and only an atomic claim creates the trip.

How it works

  • Assume 1M online drivers × one ping per 4 s ≈ 250k writes/s: keep only the latest position, in memory.
  • Index drivers by H3 cell; a request searches its cell plus neighbor rings, then ranks by road ETA.
  • Offer one driver at a time; acceptance is a conditional write, so a driver never gets two trips.
  • A durable trip state machine emits an event per transition for notifications, ETA and billing.
  • Surge compares demand with supply per cell, smoothed across neighbors and over time.

Check yourself

Answer to mark it learned; your answers aren't scored.

Two riders 200 m apart request at the same moment. Both dispatcher instances pick driver 7, who sees two offers and accepts both. What fixes this?

Go deeper

Do this round in 45 minutes System design round
Full explanation

Requirements

Functional: a rider requests a ride and sees price and ETA; nearby drivers get the offer; both see live location; the trip ends in payment. Non-functional: match within seconds, never give one driver two trips, locations fresh within seconds, a city's spike or outage stays in that city. Assume 1M online drivers at peak, each sending GPS every 4 s: ~250k writes/s.

Questions I'd ask: one city or global? Shared rides? How fresh must locations be? Who owns pricing?

High-level design

Location service: driver apps keep a persistent connection to gateways. Each update moves the driver in an in-memory geo index (driver → H3 cell, cell → drivers), sharded by region, keeping only the latest position. The raw stream also goes to a log for ETA models and analytics.

Dispatch: take the rider's cell plus neighbor rings, filter fresh available drivers, rank by road ETA, not straight-line distance, and offer to the best one with a ~15 s timeout (assumption). Acceptance is a conditional write: AVAILABLE → ON_TRIP only if still available, so two dispatchers can't book one driver.

Trip service: a durable state machine, REQUESTED → DRIVER_ASSIGNED → ARRIVED → IN_PROGRESS → COMPLETED (or CANCELLED). Each transition emits an event for notifications, ETA updates and billing.

The hard parts

Write-heavy, short-lived data. A position is stale within seconds, so it lives in memory, not in a database; a lost shard refills from the next round of pings. Airports and stadiums create hot shards: split them finer.

Surge. Every minute or so, compare open requests with available drivers per cell and set a multiplier, smoothed across neighbors and over time so prices don't flicker.

Code H3 cell index and an atomic driver claim
pythonH3 cell index and an atomic driver claim
import h3, redis

r = redis.Redis()          # one Redis per region shard
RES = 9                    # ~0.105 km² hexagons (H3 resolution table)

def update_location(driver: str, lat: float, lng: float) -> None:
    cell = h3.latlng_to_cell(lat, lng, RES)
    old = r.hget("driver:cell", driver)
    pipe = r.pipeline()
    if old and old.decode() != cell:
        pipe.srem(f"cell:{old.decode()}", driver)    # moved: leave the old cell
    pipe.sadd(f"cell:{cell}", driver)
    pipe.hset("driver:cell", driver, cell)
    pipe.set(f"fresh:{driver}", 1, ex=15)          # stale after ~3 missed pings
    pipe.execute()

def nearby(lat: float, lng: float, k: int = 2) -> list[str]:
    cells = h3.grid_disk(h3.latlng_to_cell(lat, lng, RES), k)  # 19 cells for k=2
    ids = {d.decode() for c in cells for d in r.smembers(f"cell:{c}")}
    return [d for d in ids if r.exists(f"fresh:{d}")]

# Compare-and-set in one Lua call: only one dispatcher can win a driver
CLAIM = r.register_script("""
if redis.call('GET', KEYS[1]) == 'AVAILABLE' then
  redis.call('SET', KEYS[1], 'ON_TRIP:' .. ARGV[1])
  return 1
end
return 0""")

def claim(driver: str, trip_id: str) -> bool:
    return CLAIM(keys=[f"state:{driver}"], args=[trip_id]) == 1
Real example

A rider at a café requests a ride. Dispatch takes her res-9 cell plus two neighbor rings (19 cells, ~2 km²) and finds 12 drivers with fresh pings. The ETA service ranks them by road: driver 3 is 2 minutes away; driver 5 is closer in a straight line but across a river, 9 minutes. Driver 3 gets the offer, declines, and driver 8 accepts. The claim flips driver 8 from AVAILABLE to ON_TRIP, the trip moves to DRIVER_ASSIGNED, and both apps get the event.

Trade-offs +3 · −3

+ You gain

  • A cell-keyed in-memory index turns "drivers near me" into a handful of set lookups.
  • An atomic claim on driver state makes double-booking impossible, whatever the race.
  • Region sharding isolates cities: one city's spike or outage stays local.

− You pay

  • The index is volatile: losing a shard blanks a region until the next pings arrive.
  • Hot spots like airports and stadiums overload one shard or cell.
  • Sequential offers add the timeout per decline; batched matching is better but more complex.

Use it when

Two-sided real-time marketplaces with moving supply: ride hailing, delivery couriers, field-service dispatch.

Avoid it when

Static locations (store finders, real estate): a database spatial index like PostGIS is enough, with no streaming index.

Numbers to know 4
  • Assume 1M online drivers × 1 ping / 4 s ≈ 250k location writes/s at peak.
  • H3 average cell: res 8 ≈ 0.74 km² (edge ~530 m); res 9 ≈ 0.105 km² (edge ~200 m).
  • A hex disk of radius k covers 1 + 3k(k+1) cells: 7 for k = 1, 19 for k = 2.
  • Rule of thumb: one Redis instance handles ~100k simple ops/s, so shard the geo index by region.
Common pitfalls 4
  • Searching only the rider's own cell: a driver 50 m away across the edge is invisible.
  • Ranking by straight-line distance: rivers and one-way streets make the nearest driver the slowest.
  • Writing every GPS ping to the primary database: 250k writes/s of data stale in seconds.
  • Trusting the client's trip state: validate every transition on the server with a version check.
Interview questions 3

Answer out loud first, then reveal.

Why not store driver locations in PostgreSQL with PostGIS?Show answer

PostGIS is great for static points, but this data is write-heavy and short-lived: ~250k updates/s, each obsolete 4 s later, and every one would rewrite an index entry and the WAL. I keep only the latest position in memory, keyed by H3 cell and sharded by region, and send the raw stream to a log for history and ETA training. Losing a shard costs seconds, because drivers resend. PostGIS still fits trip history and geofences.

How do you guarantee a driver never gets two trips?Show answer

The driver's state is the single source of truth, and acceptance is a compare-and-set: AVAILABLE → ON_TRIP only if still AVAILABLE. The losing dispatcher just offers its next candidate. To avoid wasted offers, I also mark a driver OFFERED with a ~15 s lease, so only one offer is live at a time. The accept call is idempotent on (driver, trip), so a retried tap neither fails nor assigns twice.

How would you compute surge pricing?Show answer

Per H3 cell, say resolution 8, every minute or so: open requests and app opens versus available drivers, computed from the request and location streams. A pricing model maps that ratio to a multiplier, smoothed with neighboring cells and the previous value, so prices don't jump at a cell edge or flicker. The quote is locked into the trip for a short window, so the rider pays what they accepted.

Deep dive 3

Location ingestion and the geo index

Pings arrive over persistent connections (WebSocket or gRPC streams) to stateless gateways, which update the index shard that owns the region. The index holds driver → cell and cell → drivers, plus a TTL so silent drivers drop out. Uber built H3 because hexagons have one distance to every neighbor and reduce error as people move; geohash cells are rectangles, so diagonal neighbors sit farther away. Either way, search neighbor cells, not just the rider's. Redis GEO is an alternative: a sorted set of 52-bit geohashes queried with GEOSEARCH.

Matching without double-booking

Rank candidates by road ETA from a routing service, adjusted for direction of travel and acceptance likelihood. Offer to one driver at a time by marking them OFFERED with a lease that expires on timeout, so no one else offers them meanwhile. Acceptance is a compare-and-set on the driver's state; the losing dispatcher moves to its next candidate. Make accept idempotent on (driver, trip), so a double tap or a retried request doesn't fail or double-assign. At high load, matching a batch of riders and drivers every few seconds can beat greedy nearest-first.

Trip state machine and surge

The trip service owns every transition and validates it server-side with a version check, so a stale client can't move COMPLETED back to IN_PROGRESS. Each transition is an event (outbox pattern), consumed by notifications, ETA, billing and the payment system when the trip completes. Surge runs on the streams: per cell (say res 8, ~0.74 km²) every minute or so, demand versus available supply maps to a multiplier, smoothed with neighbors and the previous value. The quoted price is locked into the trip, so the rider pays what they accepted.