Design Ride Sharing

How to design a ride-hailing backend: location updates, finding nearby drivers, matching without double assignment, and what interviewers ask.

Case study24 minLesson 3 of 8
On this page
  1. Clarify the problem
  2. Estimate the scale
  3. Define the API (optional)
  4. Model the data
  5. High-level design
  6. Deep dives
  7. Bottlenecks and failures
  8. What a strong answer sounds like
  9. Follow-up questions

A ride-sharing service lets a rider request a car from their current location and matches the request with a nearby available driver. The rider and the driver then both follow the trip on a map until it ends.

The question is popular because it has three hard parts. Drivers send location updates far more often than riders send requests, so writes greatly outnumber reads. The service has to search for drivers by location instead of by key. Finally, several riders may compete for the same driver at the same moment, and the system must never give one driver to two riders. The steps below follow A Framework for Any Design.

Clarify the problem

The first five minutes
Interviewer

Design a ride-sharing service.

You

I will focus on the core flow: a rider requests a trip, the system matches a nearby driver, and both follow the trip on a map. Are pricing, payments and shared rides in scope?

Interviewer

No, another team provides the price quote.

You

How many drivers are online at peak, and how many rides are there per day?

Interviewer

Assume about one million drivers online at peak and 10 million rides a day.

You

Then these are my priorities. A driver must never be assigned to two riders, a match should take a few seconds, and positions on the map may be at most a few seconds old. I can lose a location update, because the next one replaces it, but I cannot lose a trip record, because billing depends on it.

  • Functional requirements: Drivers report their location. Riders request a ride. A nearby driver receives an offer and accepts or declines it. Both sides see progress live, and a trip can be cancelled until it starts.
  • Non-functional requirements: A driver is never on two trips at once, so assignment needs strong consistency. A match completes within about 5 seconds, locations are at most about 5 seconds old, and trip records are durable.
  • Out of scope: Payments, pricing, shared rides, ratings and driver onboarding.

Estimate the scale

  • Location updates: One million drivers each sending every 4 seconds produce 250,000 writes a second. At about 100 bytes each, that is 25 MB/s of incoming data.
  • Ride requests: 10 million rides a day divided by 86,400 seconds is about 116 requests a second, or about 350 a second at three times the average. Location writes outnumber requests about 700 to 1.
  • Latest positions: One million drivers at about 100 bytes each is 100 MB, which fits in the memory of one machine.
Estimate: Location write rate

How many location updates per second arrive at peak?

You know
  • 1 million drivers online at peak
  • Each driver app sends its position every 4 seconds

Show the working
  1. 106 drivers ÷ 4 s = 250,000 updates a second

Estimate 250 thousand/s (anything from 100 thousand/s to 1 million/s is a good answer)

Each update only replaces the previous position, which points to an in-memory store of latest positions.

Your turn: Define the API

Write down how a driver's location update travels, how a rider requests a trip, and how an offer reaches a driver and is accepted. Decide how the apps stay connected to the server.

Compare with a model answer

Drivers keep a persistent connection that carries locations up to the server and offers down to the driver. Riders create a trip with an idempotency key, so a retried request does not create a second trip. Accepting an offer names the offer id, so a late accept is refused and a repeated accept is harmless.

Define the API Optional

Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.

Driver and rider API
Driver connection (WebSocket), app to server:
  location { lat, lng, heading, speed, sent_at }      every 4 s, no reply
  status   { "available" | "offline" }
 
Driver connection, server to app:
  offer { offer_id, trip_id, pickup, expires_in_s: 15 }
Driver connection, app to server:
  accept { offer_id }
    -> accepted { trip }  |  refused: offer expired or already answered
 
POST /v1/trips   Idempotency-Key: 7f3a...
  body { pickup, dropoff, quote_id }
  202 { trip_id, state: "MATCHING" }
POST /v1/trips/{id}/cancel     200 | 409 trip already in progress or completed
Rider connection, server to app: trip state changes, driver position

The decision worth arguing about is how location updates travel. An HTTP request every 4 seconds from a million phones is 250,000 requests a second, and each one carries headers and may need a new connection. A persistent connection carries small messages cheaply, and the server needs one anyway to push offers. Location updates are never retried, because the next one arrives 4 seconds later and is fresher. See realtime communication for the connection servers.

Creating a trip returns 202 because the match has not happened yet, and the rider learns the outcome over their connection.

Your turn: Model the data

Decide which data may be lost and which must be durable. Sketch where driver positions, driver status and trips are stored.

Compare with a model answer

Latest positions are disposable, so they live in memory, indexed by map cell, and expire when a driver goes quiet. Driver status decides who gets which driver, so it needs conditional writes. Trips are the durable record and live in a database.

Model the data

Records
-- in memory, sharded by region; rebuilt from incoming updates within seconds
driver_pos:  driver_id -> { lat, lng, cell, updated_at }   expires after 30 s
cell_index:  cell -> set of available driver_ids
 
-- durable, strongly consistent per row
drivers:     driver_id PK, state,        -- offline | available | offered | on_trip
             offer_id NULL, trip_id NULL, version INT
trips:       trip_id PK, rider_id, driver_id NULL, state, pickup, dropoff,
             created_at, updated_at, version INT
 
-- append-only, partitioned by trip_id
trip_points: (trip_id, sent_at) PK, lat, lng

The service uses three stores because the three kinds of data have different needs. The latest positions go in an in-memory store such as Redis, because anything lost there is restored by the next update. Driver status and trips go in a relational database, or in any store that supports conditional writes on a single row, because correct assignment depends on being able to say "update this row only if its state is still available". Trip points are a large append-only log that is read by trip id, which suits a wide-column store such as Cassandra.

Your turn: High-level design

Draw the path of a location update and the path of a ride request. Decide where matching reads data and where it writes.

Compare with a model answer

Driver updates flow through a driver gateway into an in-memory geo index. A ride request goes to a trip service, and a matching service reads candidate drivers from the geo index and claims one with a conditional write on that driver's row. The offer goes out to the driver through the gateway.

High-level design

Locations flow into an in-memory geo index. Matching reads candidates from it but claims a driver in the durable driver-state store.Rider app to Trip service (request ride); Driver app to Driver gateway (location / 4 s); Driver gateway to Geo index (update); Trip service to Trips DB; Trip service to Matching service (find driver); Matching service to Geo index (nearby); Matching service to Driver state (claim); Matching service to Driver gateway (offer); Driver gateway to Trip service (trip positions), asynchronous.Rider appDriver appTrip serviceDriver gatewayMatching serviceGeo indexTrips DBDriver staterequest ridelocation / 4 supdatefind drivernearbyclaimoffertrip positions

request and replyasynchronous message

Locations flow into an in-memory geo index. Matching reads candidates from it but claims a driver in the durable driver-state store.
A location update, then a ride requestUse the arrows or ← → keys
  1. A location update, then a ride request, step 1Rider app to Trip service; Driver app to Driver gateway; Driver gateway to Geo index; Trip service to Trips DB; Trip service to Matching service; Matching service to Geo index; Matching service to Driver state; Matching service to Driver gateway; Driver gateway to Trip service, asynchronous.Rider appDriver appTrip serviceDriver gatewayMatching serviceGeo indexTrips DBDriver state
    D7 cell
    dr5ru7

    1Driver D7 sends a position, and the gateway overwrites it in the geo index.

  2. A location update, then a ride request, step 2Rider app to Trip service; Driver app to Driver gateway; Driver gateway to Geo index; Trip service to Trips DB; Trip service to Matching service; Matching service to Geo index; Matching service to Driver state; Matching service to Driver gateway; Driver gateway to Trip service, asynchronous.Rider appDriver appTrip serviceDriver gatewayMatching serviceGeo indexTrips DBMATCHINGDriver state
    trip
    T1

    2A rider requests a ride. The trip service first writes the trip as MATCHING, so a crash cannot lose the request.

  3. A location update, then a ride request, step 3Rider app to Trip service; Driver app to Driver gateway; Driver gateway to Geo index; Trip service to Trips DB; Trip service to Matching service; Matching service to Geo index; Matching service to Driver state; Matching service to Driver gateway; Driver gateway to Trip service, asynchronous.Rider appDriver appTrip serviceDriver gatewayMatching serviceGeo index9 cells, 14Trips DBDriver state
    trip
    T1
    best
    D7, 2 min

    3Matching reads the available drivers in the pickup cell and its 8 neighbours, which gives 14 drivers, and ranks the closest few by driving time.

  4. A location update, then a ride request, step 4Rider app to Trip service; Driver app to Driver gateway; Driver gateway to Geo index; Trip service to Trips DB; Trip service to Matching service; Matching service to Geo index; Matching service to Driver state; Matching service to Driver gateway; Driver gateway to Trip service, asynchronous.Rider appDriver appTrip serviceDriver gatewayMatching serviceGeo indexTrips DBDriver stateD7 offered
    trip
    T1
    D7
    offered

    4Matching claims D7 with a conditional write that sets offered only if D7 is still available. The write succeeds.

  5. A location update, then a ride request, step 5Rider app to Trip service; Driver app to Driver gateway; Driver gateway to Geo index; Trip service to Trips DB; Trip service to Matching service; Matching service to Geo index; Matching service to Driver state; Matching service to Driver gateway; Driver gateway to Trip service, asynchronous.Rider appDriver appTrip serviceDriver gatewayMatching serviceGeo indexTrips DBDriver stateclaim refused
    trip
    T1
    D7
    offered

    5A matcher for another rider tries to claim D7 at the same moment. The condition fails, so it moves to its next candidate.

  6. A location update, then a ride request, step 6Rider app to Trip service; Driver app to Driver gateway; Driver gateway to Geo index; Trip service to Trips DB; Trip service to Matching service; Matching service to Geo index; Matching service to Driver state; Matching service to Driver gateway; Driver gateway to Trip service, asynchronous.Rider appDriver appoffer, 15 sTrip serviceDriver gatewayMatching serviceGeo indexTrips DBDriver state
    trip
    T1
    D7
    offered

    6The offer goes to D7 through D7's gateway, and D7 has 15 seconds to answer.

  7. A location update, then a ride request, step 7Rider app to Trip service; Driver app to Driver gateway; Driver gateway to Geo index; Trip service to Trips DB; Trip service to Matching service; Matching service to Geo index; Matching service to Driver state; Matching service to Driver gateway; Driver gateway to Trip service, asynchronous.Rider appDriver appTrip serviceDriver gatewayMatching serviceGeo indexTrips DBDriver stateD7 on_trip
    trip
    T1
    D7
    on_trip

    7D7 accepts. In the first of two writes, matching moves D7 to on_trip only if offer o-981 is still live.

  8. A location update, then a ride request, step 8Rider app to Trip service; Driver app to Driver gateway; Driver gateway to Geo index; Trip service to Trips DB; Trip service to Matching service; Matching service to Geo index; Matching service to Driver state; Matching service to Driver gateway; Driver gateway to Trip service, asynchronous.Rider appDriver appTrip serviceDriver gatewayMatching serviceGeo indexTrips DBASSIGNEDDriver state
    trip
    T1
    D7
    on_trip

    8The second write moves T1 to DRIVER_ASSIGNED, only if it is still MATCHING. If the rider had cancelled, it would fail and D7 would be released.

  9. A location update, then a ride request, step 9Rider app to Trip service; Driver app to Driver gateway; Driver gateway to Geo index; Trip service to Trips DB; Trip service to Matching service; Matching service to Geo index; Matching service to Driver state; Matching service to Driver gateway; Driver gateway to Trip service, asynchronous.Rider appDriver appdownTrip serviceDriver gatewayMatching serviceGeo indexTrips DBDriver stateoffer expired
    trip
    T1
    D7
    available

    9If D7 never answers, the offer expires, D7 returns to available, and matching tries the next candidate.

1 / 9

Deep dives

Handling 250,000 location updates a second

Each location update replaces the previous one, so live positions need no history, no replicas and no durable writes, only a fast overwrite. If a geo index node dies, its drivers reappear on the replacement node within 4 seconds, when their next updates arrive.

The geo index is sharded by region, so a ride request reads one shard. At 50 km/h a car moves about 56 metres between updates and a precision-6 cell is about 600 metres on its short side, so a driver changes cell only about once in 10 updates; the rest just overwrite coordinates.

Positions of drivers who are on a trip are the only ones kept. The gateway appends them to a stream that feeds the trip-points store and the rider's screen.

Finding nearby drivers

Computing the distance to a million drivers for every request is too slow. Instead the map is divided into cells, the index keeps a set of available drivers per cell, and a request looks only at the cells around the pickup. There are three common ways to divide the map.

A geohash divides the map into rectangular cells and names each cell with a short string. It interleaves the bits of the latitude and the longitude and encodes them in base 32, so each extra character makes the cell 32 times smaller, and a cell of precision 6 is about 1.2 km wide and 0.6 km high. Nearby cells usually share a prefix, and moving a driver is one removal from a set and one insertion into another. The cost is that cells have a fixed size, so a downtown cell may hold hundreds of drivers, and two neighbouring cells can have unrelated names.

A quadtree splits a square into four smaller squares whenever it contains too many points, so the cells shrink where drivers are dense. That suits static data such as restaurants. With 250,000 moves a second, the tree would split and merge constantly.

A hexagon grid, such as the one provided by H3, has cells where every neighbour is the same distance away, so a ring of cells around a point is even. It needs a library, and it helps mainly when uniform distances matter.

Ways to index driver positions
OptionGood atBad atPick it when
Geohash cells Usual defaultNearby points share a prefix, and moving a driver is a cheap set update.Cells have a fixed size, so dense areas have crowded cells.Points that move constantly and are searched within a known radius.
QuadtreeCells adapt to the density of the points.Constant movement causes constant splitting and merging.Points that rarely move, such as restaurants or shops.
Hexagon gridEvery neighbour is at the same distance, so rings of cells are even.It needs a library, and the cell ids are not human readable.Uniform distances matter, for example when pricing by area.

The part of this design that interviewers probe most is the neighbour-cell problem. A rider standing near the edge of a cell may have the nearest driver 50 metres away on the other side of the border, in a cell with a completely different string. For that reason the search always covers the pickup cell and its 8 neighbours, an area of about 9 × 1.2 × 0.6 ≈ 6.5 km². If that area contains too few drivers, the search widens by one more ring of cells or moves to a coarser precision.

Straight-line distance is only a filter for choosing candidates. A driver 300 metres away on the other side of a river may be 10 minutes away by road, so the matcher takes the closest few candidates and ranks them by estimated driving time from a routing service.

Matching without double assignment

Suppose two riders both see driver D7 as the closest. If both matchers read D7 as available and both write that D7 is assigned, D7 ends up with two trips. This read-then-write race is the part of the design interviewers care about most, and there are three ways to prevent it.

The first is a conditional write on the driver's row, shown below. The matcher sends one atomic statement that sets the state to offered only if the state is currently available. The database applies the two competing statements one after the other, so exactly one of them updates a row and the other updates none. This needs no extra component, but it requires a store in which writes to one row are linearisable. A store that accepts writes for the same key on several replicas and resolves conflicts by last-write-wins would let both claims succeed, and a quorum read followed by a quorum write does not help, because two clients can both read "available" before either writes.

Claiming a driver
UPDATE drivers
SET    state = 'offered', offer_id = 'o-981', version = version + 1
WHERE  driver_id = 'D7' AND state = 'available';
-- 1 row updated: we own the offer.  0 rows: someone else got there first.

The second option is to give each region a single matcher that processes requests one at a time. With only one writer there is no race, and the matcher can also look at several waiting riders together and choose the best combination. The cost is that the matcher is a bottleneck and a single point of failure. It is worth it in very dense areas, where batching requests produces better matches.

The third option is a distributed lock for each driver. A lock can expire while its holder is paused, and then a second matcher takes it while the first still believes it holds it. The write itself must therefore still check the driver's state, and once that check exists the lock adds nothing.

After the claim, the offer works as a lease that lasts 15 seconds. Accepting it takes two conditional writes in a fixed order and not one transaction, because the driver row and the trip row may live in different stores. The first write moves the driver to on_trip if the offer is still live, and the second moves the trip to DRIVER_ASSIGNED if it is still MATCHING. If the second write fails because the rider cancelled, the driver is released. If the service crashes between the two writes, the driver app retries the accept with the same offer_id, and a sweeper releases any driver whose trip_id points to a trip that is not theirs.

The trip state machine

Many actors can change a trip at the same time. The rider may cancel while the driver accepts, or a timeout may fire while the driver taps "arrived". To keep the result predictable, the trip service only allows the moves in the table below, and every move is a conditional update on (trip_id, state, version). If a cancel and an accept arrive together, exactly one of them finds the state it expects, and the other gets a conflict and the app shows the real state of the trip.

FromToTriggered by
MATCHINGDRIVER_ASSIGNEDA driver accepts a live offer.
MATCHINGNO_DRIVERSNo driver accepts in 60 seconds.
DRIVER_ASSIGNEDDRIVER_ARRIVEDThe driver taps "arrived" near the pickup point.
DRIVER_ARRIVEDIN_PROGRESSThe driver starts the trip.
IN_PROGRESSCOMPLETEDThe driver ends the trip.
Any state before IN_PROGRESSCANCELLEDThe rider or the driver cancels.

Bottlenecks and failures

At ten times the load there would be 2.5 million location updates a second, and the geo index would need smaller regional shards. A dense city can be split by cell prefix. Matching would reach about 3,500 requests a second, so driver state should be partitioned by region.

When this failsWhat happensWhat you do
A geo index shardRequests in that region find no candidates for a few seconds.Route the updates to a standby node, which fills up again in about 4 seconds.
A driver gateway serverThe drivers connected to it lose their connection.The apps reconnect to another gateway, and offers that were in flight expire and go to the next driver.
The matching serviceNew requests wait in the MATCHING state.Run several stateless matchers, which is safe because the conditional write prevents double assignment.
The driver-state primaryNo new claims can be made.Fail over to a replica that has every committed write. Matching pauses briefly, which is better than a double assignment.
A driver's phoneIts location updates stop.The position expires after 30 seconds and the driver drops out of the index.

What a strong answer sounds like

LevelWhat the answer does
JuniorStores positions in a database table, queries by distance, and handles the race only when prompted.
Mid-levelEstimates the update rate, keeps positions in memory, and uses geohash cells together with their neighbours.
SeniorSeparates disposable positions from durable assignments, claims drivers with a conditional write and names the store guarantee, models the trip as a state machine, and ranks by driving time.
Defending the matching designStrong answer
Interviewer

Two matchers pick the same driver at the same moment. What happens?

You

Both try the same conditional update, which sets the driver to offered only if the driver is still available. The store applies the two updates one after the other on that row, so one gets "1 row updated" and the other gets zero and moves on to its next candidate. This only works if one leader or consensus group owns the row, so I would not keep driver state in a store that merges concurrent writes.

Follow-up questions

How would you support surge pricing?

Count open requests and available drivers in each cell every minute, and publish a price multiplier for each area from the ratio of the two. Smoothing the multiplier across neighbouring cells avoids a price that jumps at a cell border.

How do you estimate the arrival time?

A routing service computes it over the road graph using live traffic data. It runs a shortest-path search such as Dijkstra's algorithm. It is expensive, so matching calls it only for the few candidates that pass the straight-line filter.

What if a driver's GPS jumps by a kilometre?

The gateway rejects updates that imply an impossible speed, such as a kilometre in 4 seconds, and keeps the last good position instead. Positions are also snapped to the road network before matching or billing, which removes smaller errors.

Do you offer a ride to one driver at a time or to several?

Offering to one driver at a time, nearest first, is simplest and avoids drivers racing for the same trip, but a decline or a timeout costs up to 15 seconds. Offering to the best three at once is faster, though it needs the first accept to win through the same conditional write on the trip, and the other drivers must be told the offer is gone. Most designs start with one at a time and shorten the offer time in busy areas.

Self-review: ride sharing0 of 12

After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".

Before drawing

Numbers and interfaces

Design and depth

Failure