Design a Cab Booking System: Geohash, Matching and Locks
How millions of driver location updates are stored, how nearby drivers are found without scanning everyone, and how one driver is never given two rides.
A cab booking system matches a rider who needs a ride with a nearby available driver, within a few seconds. Behind that simple experience are two hard problems: storing a continuous stream of location updates from every driver, and searching that data by geography.
Calculating the distance from the rider to every driver and sorting the result does not scale beyond a small city. These notes explain the spatial indexing that replaces it, and the concurrency control that prevents double booking.
1. Requirements
- Functional: a rider sees nearby drivers, requests a ride, and is matched with a driver.
- Functional: both sides see live location during the trip.
- Functional: fare calculation and payment (state it, then keep it out of the deep dive).
- Non-functional: matching completes within a few seconds.
- Non-functional: a driver must never be assigned to two rides at once. Correctness matters more than speed here.
- Workload: write-heavy, because every active driver sends location updates continuously.
2. Scale estimation
Assume 1 million active drivers, each sending a location update every 4 seconds. That is 250,000 writes per second. Assume 10 million rides per day, about 115 ride requests per second on average and several hundred at peak. Location writes outnumber ride requests by three orders of magnitude, so the location pipeline is the component to design most carefully.
The latest location is small: a driver ID, latitude, longitude and timestamp, well under 100 bytes. One million drivers fit in about 100 MB of memory, so the current-location index can live entirely in RAM.
3. API
# Driver app, every few seconds (over a persistent connection in practice)
PUT /api/v1/drivers/me/location
Body: { "lat": 28.6139, "lng": 77.2090, "heading": 120, "ts": 1767225600 }
# Rider app
GET /api/v1/drivers/nearby?lat=28.61&lng=77.20&radius=3000
POST /api/v1/rides
Body: { "pickup": {...}, "drop": {...}, "vehicleType": "sedan" }
Response: 202 Accepted { "rideId": "r_5531", "status": "MATCHING" }
# Driver app
POST /api/v1/rides/{rideId}/accept
POST /api/v1/rides/{rideId}/decline4. Storing driver locations
Only the most recent location of a driver is needed for matching, and it is overwritten every few seconds. Writing each update to a disk-based relational database would waste a great deal of I/O on data that is obsolete almost immediately.
The latest location is therefore kept in an in-memory store such as Redis, with a short TTL. If a driver's app stops sending updates, the entry expires and the driver automatically disappears from search results. If trip history is needed for billing or analytics, the same updates are also published to a queue and written to durable storage asynchronously, off the critical path.
5. Finding nearby drivers: geohash
A normal database index sorts by one dimension. Location has two, latitude and longitude, so an ordinary index cannot answer 'which points are near this point' efficiently. A spatial index solves this by converting two dimensions into one.
A geohash divides the world into a grid. It splits the map into cells, splits each cell again, and continues; each split adds a character to a string. The result is that every cell has a short code, and cells that share a longer prefix are closer together. A six-character geohash covers roughly 1.2 km by 0.6 km; a seven-character one about 150 metres square.
Each driver is indexed under the geohash of their current cell. To find drivers near a rider, compute the rider's cell and look up drivers in that cell and its eight neighbours. The neighbours are required because a rider standing at the edge of a cell may have the nearest driver just across the boundary. This reduces the candidate set from a million drivers to a few dozen, and only for those is an exact distance calculated.
Redis supports this directly through its geospatial commands, which store members in a sorted set scored by geohash. Alternatives worth naming are quadtrees, which subdivide adaptively so dense areas get smaller cells, and hexagonal grid systems.
# Driver location update (the index is sharded by city / region)
GEOADD drivers:delhi:available 77.2090 28.6139 driver:1042
# Rider requests a ride: nearest 10 available drivers within 3 km
GEOSEARCH drivers:delhi:available FROMLONLAT 77.2100 28.6145
BYRADIUS 3 km ASC COUNT 10 WITHDISTDriver app --location--> Location service --> Redis geo index (latest position, TTL)
|
+--> Kafka --> Trip history store / analytics
Rider app --request--> Ride service --> Matching service --> Redis geo index (candidates)
| |
| +--> ETA service (road network + traffic)
| +--> Lock: SET lock:driver:{id} NX EX 15
v +--> Notification to driver (push / WebSocket)
Rides DB (SQL): ride state machine
REQUESTED -> MATCHED -> ARRIVING -> IN_TRIP -> COMPLETED6. Matching
The matching service takes the candidate drivers, ranks them, and offers the ride to the best one. The driver has a short time, for example 15 seconds, to accept. If the driver declines or does not respond, the offer moves to the next candidate. Offering to one driver at a time avoids several drivers accepting the same ride; some systems instead broadcast to a small group and take the first acceptance.
The ride itself is a state machine stored in a relational database, because its transitions must be consistent and are tied to payment.
7. Preventing double booking
Two riders in the same area request a ride in the same second, and the nearest driver for both is the same person. If both matching requests read 'driver is available' and then both assign the driver, one driver has two rides. This is a race condition.
The solution is to acquire a lock on the driver with an atomic operation before sending the offer. In Redis, the command SET with the NX option writes the key only if it does not already exist, in a single step. Exactly one of the two requests succeeds; the other sees the driver as taken and moves to the next candidate.
The lock carries a TTL. If the matching service crashes while holding the lock, or the driver never responds, the lock expires on its own and the driver becomes available again. Without a TTL, a failure would leave the driver locked indefinitely. When the driver accepts, the ride and the driver's status are updated in the database in one transaction, which is the durable guarantee behind the short-lived lock.
8. Rank by ETA, not distance
Straight-line distance is misleading. A driver 400 metres away on the other side of a river or a highway divider may need ten minutes to arrive, while a driver 900 metres away on the same road needs three. After the geohash lookup produces candidates, an ETA service estimates the driving time for each one using the road network and current traffic, and candidates are ranked by that time.
9. Additional considerations
- Sharding: partition the location index by city or region, since a rider is only ever matched with drivers in the same area.
- Dense areas: a fixed cell size returns too many drivers downtown and too few in suburbs. Expand the search radius progressively, or use an adaptive structure such as a quadtree.
- Live tracking: during a trip the driver's location is pushed to the rider over a WebSocket.
- Surge pricing: computed per cell from the ratio of ride requests to available drivers.
- Reliability: the location index is rebuilt naturally within seconds after a failure, because drivers keep sending updates.
Interview summary
- Requirements: fast matching, no double booking, write-heavy location updates.
- Location updates: latest position in an in-memory store with a TTL.
- Nearby search: geohash cells, searching the rider's cell and its neighbours.
- Matching: atomic lock on the driver with a TTL, then a transactional ride update.
- Ranking: by ETA on the road network, not straight-line distance.
Summary
Driver locations are a high-volume stream of short-lived data, so the latest position is kept in memory with a TTL. A geohash index turns 'find nearby drivers' into a lookup of a few grid cells. An atomic lock with a TTL guarantees that one driver receives one ride, and candidates are ranked by estimated arrival time.
Puneet Tiwari
Full Stack Developer
