Design Uber (ride dispatch)

Uber, Ola and Lyft connect a rider who needs a car with a nearby driver, within seconds. Two things make it hard. First, drivers move all the time, so the system must track hundreds of thousands of moving points. Second, matching must be fair and safe: one driver must never be promised to two riders, and a rider must not wait because the first driver ignored the request. Geohash and quadtree indexes are in the specialized indexes lesson, so here we use them and focus on tracking, matching and the trip lifecycle.

1. Requirements and Scope

Functional requirements:

  • A rider requests a ride from a pickup point to a destination, and sees a fare estimate and an ETA (estimated time of arrival).
  • The system finds a nearby available driver and offers the ride. The driver accepts or declines.
  • The rider sees the driver's car moving on the map until the trip starts and ends.
  • Trips go through states (requested, assigned, in progress, completed) and are paid at the end.

Non-functional requirements:

  • Fast matching: a driver is found and offered the ride in a few seconds.
  • No double booking: one driver gets at most one ride at a time.
  • Fresh locations: a driver's position is at most a few seconds old.
  • Highly available in every city. A trip in progress must never be lost.

Out of scope: payment internals (see the payment system lesson), maps and route calculation, driver onboarding, and ride sharing.

2. Estimation

  • Rides: 20 million a day. 20,000,000 ÷ 86,400 ≈ 231 per second, and about 4 times that at peak: 925 ride requests per second. This is small.
  • Location updates: on average 600,000 drivers are online. Each phone sends its position every 4 seconds. 600,000 × 86,400 ÷ 4 ≈ 13 billion updates a day, 150,000 per second on average and 250,000 per second at peak (1 million online). At about 100 bytes each, that is 25 MB/s.
  • Current locations in memory: 5 million drivers × 100 bytes = 500 MB. Tiny. History is not kept here. It is streamed to a data lake for analytics (13 billion × 50 bytes ≈ 650 GB a day).
  • Active trips (Little's law): a trip lasts about 20 minutes (1,200 s). At peak, 925 per second × 1,200 s ≈ 1.1 million trips in flight. Each streams the driver's position to the rider every 4 seconds: about 277,000 pushes per second.
  • Matching queries: 925 per second, each reading about 9 nearby cells. About 8,300 cell reads per second. Cheap.

The takeaway: writes dominate. The hard load is 250,000 location updates per second, not the 925 ride requests. The location index must be built for constant updates.

3. API

  • Driver app, over a WebSocket: location {lat, lng, heading} every 4 seconds, and status {available | offline}. The server sends offer {rideId, pickup, fare}, and the driver replies accept or decline.
  • POST /v1/rides/estimate with pickup and destination returns fare and ETA.
  • POST /v1/rides with pickup, destination and an idempotency key returns 202 and a rideId. Matching continues in the background.
  • GET /v1/rides/{id} returns state, driver and position. Live updates come over a WebSocket or server-sent events (see the real-time lesson).
  • POST /v1/rides/{id}/cancel.

4. Data Model

  • Trips (trip_id, rider_id, driver_id, pickup, destination, state, fare, version, created_at) in a relational or sharded SQL database, sharded by trip ID. It is the source of truth and needs transactions and a strict state order.
  • Live driver state in memory (Redis): where each driver is, and whether they are available. It changes constantly and can be rebuilt in seconds from the next updates, so it does not need to be durable.
  • Location history goes to Kafka and then a data lake, for analytics, safety and surge pricing.

5. High-Level Design

flowchart LR
  D["Driver app"] <--> GW["Gateways: WebSocket"]
  R["Rider app"] --> RS["Ride service"]
  GW --> LS["Location service"]
  LS --> IDX[("Driver index: Redis, by grid cell")]
  LS -.-> K[["Kafka: locations and trip events"]]
  RS --> M["Matching service"]
  M --> IDX
  M --> GW
  RS --> TDB[("Trips DB")]
  K --> PAY["Payment, notifications, surge pricing"]
  1. Drivers keep a WebSocket open to a gateway. Each position update goes to the location service, which updates the driver index.
  2. A rider request goes to the ride service. It saves the trip as REQUESTED and asks the matching service to find a driver.
  3. Matching reads the index near the pickup, picks candidates, reserves one and sends the offer to that driver through the gateway.
  4. When the driver accepts, the ride service sets the trip to ASSIGNED. From then on, the driver's position updates are also forwarded to the rider.
  5. Trip events go to Kafka. Payment, notifications and analytics consume them without slowing the trip.

6. Tracking Drivers

The map is divided into cells (geohash or the H3 hexagon grid, see the specialized indexes lesson). The index keeps, for each cell, the set of available drivers inside it, plus each driver's latest position. A cell about half a kilometre across is a good size for a city.

public void updateLocation(long driverId, double lat, double lng) {
    String newCell = grid.cellOf(lat, lng);
    String oldCell = redis.opsForValue().getAndSet("driver:cell:" + driverId, newCell);

    if (oldCell != null && !oldCell.equals(newCell)) {                       // the driver crossed into another cell
        redis.opsForSet().remove("cell:" + oldCell, String.valueOf(driverId));
    }
    redis.opsForSet().add("cell:" + newCell, String.valueOf(driverId));
    redis.opsForValue().set("driver:pos:" + driverId, lat + "," + lng, Duration.ofSeconds(30));   // expires if the app goes quiet
}
  • Most updates change only the position, not the cell. So most are one cheap write.
  • A silent driver disappears. The position key expires after 30 seconds. A search ignores any driver without a fresh position, and removes that driver from the cell set.
  • Sharding: the index is split by city, and big cities by cell range, so 250,000 writes per second are spread over many Redis nodes (see the sharding lesson). Matching is local: a request touches only the cells around the pickup point.
  • No database in this path. Driver positions are never written to the trips database. They live in memory and flow to Kafka.

7. Matching and Dispatch

Strategy How it works Good Problem
Nearest driver first Offer to the closest available driver. If declined or no reply, the next one Simple and fast Each decision is local, so the overall wait can be higher
Broadcast to several Offer to the 3 to 5 nearest at once, first to accept wins Quick acceptance Wasted offers; drivers see rides vanish
Batch matching Collect requests for 2 seconds, then assign drivers to riders to minimize the total wait Better overall result A small added delay; more complex

Start with nearest-first and mention batch matching as the improvement. The steps for one request:

  1. Take the pickup cell and its neighbours. Collect the available drivers with fresh positions.
  2. Rank them by road ETA (from the maps service), not straight-line distance. A driver across a river can be close on the map and far by road. Take the top few.
  3. Reserve the first driver with an atomic operation, send the offer, and wait about 15 seconds.
  4. Accept: create the assignment. Decline or no reply: release the reservation and offer to the next driver.
public Optional<Long> dispatch(String rideId, Location pickup) {
    List<Candidate> ranked = candidates.nearby(pickup, 5);                    // available, fresh, sorted by ETA

    for (Candidate c : ranked) {
        // atomic: only one ride can hold a driver at a time (SET key value NX EX 15)
        Boolean reserved = redis.opsForValue()
                .setIfAbsent("reserve:driver:" + c.driverId(), rideId, Duration.ofSeconds(15));
        if (!Boolean.TRUE.equals(reserved)) continue;                             // someone else got this driver

        Reply reply = offers.sendAndWait(c.driverId(), rideId, Duration.ofSeconds(15));
        if (reply == Reply.ACCEPT) return Optional.of(c.driverId());
        redis.delete("reserve:driver:" + c.driverId());                           // declined or timed out
    }
    return Optional.empty();                                                      // widen the search, or tell the rider
}
  • The reservation prevents double booking. If two rides pick the same driver at the same moment, only one SET ... NX succeeds. The other moves to the next driver. The 15-second expiry also frees the driver if the matching service crashes.
  • If no driver is found: widen the radius, then retry for a short time, then tell the rider.
  • Driver accepts after the offer expired: the reservation is gone, so the ride service rejects the accept with a clear message.

8. The Trip Lifecycle

State Who triggers it What happens
REQUESTED then MATCHING Rider Trip saved; matching starts
ASSIGNED Driver accepts Driver marked busy; rider sees the car and ETA
ARRIVED Driver app (near pickup) Rider is notified
IN_PROGRESS Driver starts the trip Fare meter and route recording begin
COMPLETED Driver ends the trip Final fare calculated; payment started; driver becomes available
CANCELLED Rider, driver or system Driver released; a fee may apply depending on the state

Each change is a conditional update that checks the current state and version: UPDATE trips SET state='ASSIGNED', driver_id=?, version=version+1 WHERE trip_id=? AND state='MATCHING' AND version=?. Out-of-order or repeated events (a double tap, a retry) do nothing. Each change publishes an event to Kafka for payment, notifications and analytics.

9. ETA, Price and Payment

  • ETA comes from a maps and routing service that knows the road network and live traffic. The dispatch system calls it and does not build it (see the proximity service lesson).
  • Surge pricing: a stream job counts open requests and available drivers per cell every minute. When demand is much higher than supply, a price multiplier is applied for that cell. Show it to the rider before they confirm.
  • Payment: after COMPLETED, a payment service charges the saved method, using the trip ID as the idempotency key (see the payment system lesson). If the charge fails, the trip stays complete and the payment is retried.

10. Worked Example: Kavya Rides from Indiranagar

  1. Kavya requests a ride in Indiranagar, Bengaluru. The ride service saves trip t-501 as REQUESTED and starts matching.
  2. The matching service reads her cell and its 8 neighbours: 14 available drivers with fresh positions. It ranks them by road ETA and takes the top 5.
  3. At the same moment, another rider's request picks driver Mohan as well. Both try SET reserve:driver:mohan ... NX. Kavya's wins. The other request moves to its second choice.
  4. Mohan has 15 seconds to answer. His phone is in a tunnel, so he does not reply. The reservation expires, and the next driver, Anita, gets the offer. She accepts in 6 seconds.
  5. The trip becomes ASSIGNED. For the next minutes, Anita's position updates are forwarded to Kavya's app every 4 seconds.
  6. Anita starts and ends the trip. The trip is COMPLETED, the fare is charged with idempotency key t-501, and Anita becomes available again.

11. Scaling and Failures

  • Location service and gateways are stateless and scale by connection count and update rate. If a gateway dies, drivers reconnect and the next update restores their position.
  • Driver index lost: it rebuilds itself within one update cycle (4 seconds) as drivers keep sending positions. Matching is slightly worse for a moment, but no trip is lost, because trips live in the database.
  • Matching service crash: reservations expire after 15 seconds. The ride service finds trips stuck in MATCHING and starts matching again. Matching is safe to repeat.
  • Trips database is replicated across zones, sharded by trip ID. A trip in progress keeps working even if matching is down, because it needs only the trip row and the location stream.
  • Regions: each city is served by its nearest region. A city's drivers and riders do not interact with other cities, so cities are natural shards.
  • Monitoring: time from request to assignment, offer acceptance rate, share of requests with no driver, location update lag, and trips stuck in a state for too long.

12. Common Pitfalls

  • Writing every location update to the main database. 250,000 writes per second will overwhelm it. Keep live positions in memory.
  • Straight-line distance for ranking. Use road ETA.
  • No atomic reservation, so two riders get the same driver.
  • No offer timeout, so one unresponsive driver blocks a rider.
  • Never expiring stale drivers, so riders are matched to phones that went offline.
  • Updating trip state without checking the current state, so retries and races corrupt the trip.
  • Charging without an idempotency key, so a retry charges the rider twice.

13. Interview Questions

  1. How do you find nearby drivers quickly? Divide the map into cells (geohash or H3). Keep a set of available drivers per cell in memory. Search the pickup cell and its neighbours, then rank by road ETA.
  2. How do you handle 250,000 location updates per second? Keep positions in memory, not in the trips database. Most updates only change a position. Shard the index by city and cell range, and stream history to Kafka for analytics.
  3. How do you stop two riders from getting the same driver? An atomic reservation per driver with a short expiry, such as SET NX EX. Only one request wins, and it expires if the matching service dies.
  4. What if the driver does not respond? The offer times out after about 15 seconds, the reservation is released, and the next candidate gets the offer.
  5. How do you handle trip states? A strict state machine with conditional updates on the current state and version, so repeats and out-of-order events change nothing. Events go to Kafka.
  6. How does the rider see the car moving? While the trip is active, the driver's updates are forwarded over a WebSocket or server-sent events to the rider, every few seconds.
  7. Nearest driver or batch matching? Nearest-first is simple and fast. Batch matching collects requests for a couple of seconds and assigns drivers to minimize the total wait. It gives better results at busy times for a small added delay.