Design it yourself · Chapter 24

Design a ride-hailing app

Design an Uber-style ride-hailing app from scratch: requirements, estimates, a geospatial index for nearby drivers, matching without double booking, live tracking, and hot vs cold data.

IntermediateInterview priority: High40 min
On this page
  1. The problem: find a moving car, fast
  2. Step 1: pin down the requirements
  3. Step 2: quick estimates
  4. Step 3: the API
  5. Step 4: build the design
  6. Key decisions
  7. Where this breaks
  8. In the interview
  9. Where to go next
  10. Quiz

The problem: find a moving car, fast

A rider taps "Request". Within a few seconds the app must find a free driver nearby, get them to accept, and then show both people each other's position live on a map. Thousands of cars are moving all the time, so "nearby" changes every second.

A rider asks; the service finds a driver within seconds

  1. Last design: a ride-hailing app like Uber. Riders ask for a ride; the app finds a nearby driver within seconds, and both watch each other’s car move live on the map.

The interesting part is not the trips (there are surprisingly few of them) but the locations: a constant stream of position updates that must be searchable by "near this point" almost the moment they arrive. This is a first design; the full case study (linked at the end) goes deeper.

Step 1: pin down the requirements

Your turn: what would you ask?

List the functional and non-functional requirements you would agree on, and what you would leave out.

Compare with our answer

A strong answer mentions: riders request a ride and see nearby cars and an ETA · drivers go online and accept or decline offers · live location of the car during pickup and trip · trip states through to completion and payment · a match within a few seconds · a driver never assigned to two riders · location data can be seconds old but trips and payments must be durable · out of scope: pricing and surge details, pooled rides, payments internals.

Functional

  • Drivers go online and their app reports location.
  • Riders see nearby cars, request a ride, and get matched with a driver who accepts.
  • Both see each other's live position until pickup, then the trip is tracked to the destination.
  • Trips end with a fare and a payment (handled by a separate payments service).

Non-functional

  • Match within ~5–10 seconds; nearby-driver queries in tens of milliseconds.
  • Never assign one driver to two trips, and never lose a trip or a payment.
  • Locations may be a few seconds stale; that is fine.

Out of scope: surge pricing, pooled rides, ratings, payment processing internals.

Step 2: quick estimates

Assume 120,000 drivers online at peak across all cities, each sending a position every 10 seconds, and about 3 million trips a day.

QuantityWorkingResult
Location updates120,000 ÷ 10 s12,000 / s, all day
Size of "latest position" data120,000 × ~100 bytes≈ 12 MB (fits in memory easily)
Location history, if kept12,000/s × 100 B × 86,400≈ 100 GB / day
New trips3 M ÷ 86,400 s≈ 35 / s average, ~100 / s at peak
Nearby-car lookups (app opens, requests)a few thousand / s
Live connectionsdrivers + riders on trips~100,000–200,000

Sanity check: if a trip lasts ~20 minutes, 100 new trips a second at peak means about 120,000 trips in progress, which is the most 120,000 drivers can handle. Trip volume is bounded by the number of drivers.

The shape is clear. Locations are a high-volume stream of tiny, short-lived values where only the latest matters. Trips are low volume but must be stored safely and consistently.

Step 3: the API

POST /v1/drivers/me/status     {online: true}
WS   /v1/drivers/me/stream     ← offers;  → {lat, lng, heading, ts} every 10 s
GET  /v1/drivers/nearby?lat=..&lng=..          → [{driver_id, lat, lng, eta}]
POST /v1/trips                 {pickup, dropoff}  → {trip_id, state: REQUESTED}
POST /v1/trips/{id}/accept     (driver)
WS   /v1/trips/{id}/stream     → live driver position for the rider

Drivers keep a WebSocket (a long-lived, two-way connection) open, so the server can push trip offers instantly and the app can send positions cheaply without a new HTTP request each time. See APIs: REST, gRPC and WebSockets.

Step 4: build the design

Finding nearby drivers: a geospatial index

A naive query computes the distance from the rider to all 120,000 drivers, or runs WHERE lat BETWEEN … AND lng BETWEEN … on a table that is being updated 12,000 times a second. Both are wasteful: we only care about a few square kilometres.

Cut the map into cells; check your cell and its neighbours

  1. To find nearby drivers fast, the city map is cut into a grid of small cells, using schemes like geohash. A geospatial index, kept in memory, knows which drivers are in each cell. “Drivers near me” means checking your cell and its neighbours.

Cut the map into a grid of cells and keep, in memory, the set of drivers in each cell. A geohash is a common way to name the cells: it encodes latitude and longitude into a short string where each extra character makes the cell smaller (6 characters ≈ 1.2 km × 0.6 km), and nearby points usually share a prefix.

Check your cell and its 8 neighbours, then filter by true distance

"Drivers near me" becomes: compute your cell, read that cell and its 8 neighbours, then keep the free drivers whose true distance (or better, estimated driving time) is within range. That is nine small set lookups instead of 120,000 distance calculations. Redis has this built in (GEOADD, GEOSEARCH, implemented with geohash-encoded sorted sets), and Uber built its own hexagonal grid, H3, for the same purpose.

The location path

Driver positions flow through gateways into an in-memory geo index

Each update travels: driver app → WebSocket gateway → location service → geo index. The location service overwrites the driver's last position (removing them from their old cell if they moved) and sets an expiry: a driver who sends nothing for ~30 seconds drops out of the index automatically. Nothing about this path needs a disk-based database. If history is needed (for analytics, disputes or ETA models), updates are also appended to a log such as Kafka and saved to cheap storage in bulk.

The geo index is sharded by city or region: riders in Paris never need drivers in Tokyo, so each region's index lives on its own nodes, and busy cities can be split further by cell.

Matching and the trip path

Matching offers the trip to the best nearby driver

  1. Matching then offers the trip to the best nearby driver. Once matched, both phones hold a live connection, so the car’s position streams to the rider every few seconds.

The trip is stored durably; the driver is assigned with a conditional update

  1. The rider's request creates a trips row in the database with state REQUESTED.
  2. The matcher asks the geo index for free drivers nearby, ranks them by estimated time to pickup, and offers the trip to the best one, with a timeout of ~15 seconds.
  3. If they decline or time out, the next driver gets the offer.
  4. On accept, the assignment is a conditional update: the trip moves to ACCEPTED only if it is still REQUESTED, and the driver moves to BUSY only if still AVAILABLE. If either check fails, the accept is rejected.

From then on, the rider's app subscribes to the trip, and the driver's location updates are forwarded to the rider's connection every few seconds.

Two kinds of data

Hot path in memory, cold path in a durable database

  1. Notice the two kinds of data. Locations are the hot path: huge volume, short-lived, fine in memory. Trips and payments are the cold path: lower volume, but they must be stored safely and consistently in the database.
Locations (hot path)Trips and payments (cold path)
Volume12,000 writes/s~35–100 writes/s
LifetimeSecondsYears
CorrectnessLatest value wins; losing one update is harmlessMust be durable and consistent
StoreIn-memory geo index, sharded by regionRelational database (e.g. Postgres), replicated

Treating these differently is the key insight of the whole design. Writing every location update into the trips database would make it 100 times busier for data nobody needs a minute later.

Key decisions

Which geospatial index?

OptionHowGood atWeak at
Geohash grid (e.g. Redis GEO)Fixed rectangular cells named by prefixSimple; built into Redis; easy to shard by prefixFixed cell size: dense downtowns have crowded cells, rural ones are empty
QuadtreeSplits a cell into four whenever it holds too many pointsAdapts to densityHarder to update with fast-moving points; rebalancing
Hexagonal grid (H3)Hexagons at several resolutionsNeighbours are all the same distance away; good for ETAs and surge zonesAnother library and concept to explain
Database geo index (PostGIS)R-tree-style index on a tableRich queries; durableToo slow to update 12,000 times a second for data that changes constantly

Choice: an in-memory geohash (or H3) grid, sharded by region. It is the simplest thing that meets the write rate.

Offer to one driver, or to several?

OptionGood atWeak at
One at a timeSimple; drivers never race; fairEach decline adds up to 15 s
Several at once, first accept winsFaster matchingDrivers who lose the race are annoyed; needs the conditional update even more

Choice: one at a time, with a short timeout. If matching is slow in a busy period, offer to two or three at once and let the conditional update pick the winner.

Where this breaks

In the interview

Your turn: the requirement changes

Product wants shared rides: a driver can carry up to three riders going in similar directions, picking up a new rider mid-trip. What changes?

Compare with our answer

A driver is no longer simply "free" or "busy": they have remaining seats and a planned route. The geo index must return drivers who are available or on a shared trip with seats, near the pickup. Matching becomes a route problem: estimate the detour for existing riders and accept only if it stays under a limit (say 5–10 minutes) and the ETA for the new rider is good. The trip model changes: a driver has one route with several pickups and drop-offs, each rider has their own trip linked to it. The conditional update now checks seat count and route version, so two matchers can't fill the last seat twice. Fares are split and estimated up front.

A strong answer mentions: capacity instead of a free/busy flag · searching drivers already on trips · detour and ETA limits in matching · a route with multiple stops in the data model · concurrency on the last seat via a conditional update or version.

Your turn: spot the bugs

A design stores every driver location update as a new row in the main Postgres trips database, finds nearby drivers with ORDER BY distance(lat, lng, :rider) LIMIT 10 over all drivers, and assigns a driver by reading their status and then writing BUSY in two separate statements. What goes wrong?

Compare with our answer
  • Location rows in the trips database: 12,000 inserts a second (about 1 billion rows a day) into the system of record, for data that matters for seconds. Keep latest positions in an in-memory geo index; stream history to a log.
  • Full scan for nearby drivers: computes the distance to every driver on every request. Use geohash or H3 cells and check only nearby cells.
  • Read-then-write assignment: two matchers both read AVAILABLE, both write BUSY, and the driver gets two trips. Use a conditional update (WHERE status = 'AVAILABLE') or a lock with an expiry.
  • No expiry: drivers who lose signal remain "available" forever.

A strong answer mentions: separating hot location data from the trips database · a cell-based geo index · a conditional update or compare-and-set for assignment · expiring stale locations.

Where to go next

Ride-hailing on one page
  • 120,000 drivers × 1 update / 10 s = 12,000 writes/s; latest positions ≈ 12 MB, so keep them in memory.
  • Trips: ~3 M/day ≈ 35/s (≈ 100/s peak), bounded by drivers ÷ trip length. Store them durably in a relational database.
  • Geo index: geohash or H3 cells; "nearby" = your cell + 8 neighbours, then filter by distance or ETA. Redis GEO works.
  • Location path: WebSocket gateways → location service → in-memory index, sharded by region; overwrite, expire after ~30 s; history to Kafka if needed.
  • Matching: rank nearby free drivers by ETA, offer one at a time with a ~15 s timeout.
  • No double booking: conditional update on trip and driver state (or a lock with expiry); idempotent accept.
  • Live tracking: forward the driver's updates to the rider's connection.
  • Breaks: ghost drivers (expiry), hot cells (smaller cells, batch matching), lost index node (rebuilt from the next 10 s of updates).
Interactive labBuild it yourself on the design boardOpens in the ByteAtlas lab. Your progress is saved in this browser.
Check what stuck

1. 120,000 online drivers each send a location every 10 seconds. Where should their latest positions live?

2. A rider stands near the edge of a geohash cell. Why does the query check the 8 neighbouring cells too?

3. Two matchers offer driver 7 to different riders at the same moment, and both see "accepted". What is the right protection?

4. About how many new trips per second should you expect at peak with 120,000 drivers and trips averaging 20 minutes?

5. A driver's phone loses signal, but riders keep being offered that car for the next hour. What fix belongs in the design?

6. The node holding one city's in-memory geo index crashes. What is the impact?

Score 60% or more and the lesson is marked complete.

Passing the quiz also marks it complete. Progress is saved in this browser only.