Video in progress
How do you build "find the nearest drivers" in a taxi app for millions of drivers?
A driver's location arrives every 3-5 seconds, so I write it not to a DB but to an in-memory geo index (geohash or H3 cells). The search takes the drivers in the passenger's cell and its neighbors and sorts them by real distance or travel time.
📖 Answer
The numbers: 1 million active drivers each send a location every 4 seconds, so 250 thousand writes per second. 99% of those go stale after a few seconds. Storing that kind of data in a relational DB and updating an index on every write is a waste.
The geo index. We divide the globe into cells:
- Geohash is a simple string prefix, and Redis
GEOADD/GEOSEARCHuses it internally. The downside is that cell shape changes with latitude, and it's awkward at the boundaries between neighbors. - H3 (hexagonal cells): all neighbors are at the same distance, and it's easy to get the surroundings with a "k ring". Widely used on big platforms.
The index: cellId → {driverId, lat, lng, ts} in memory, sharded by city or region. When a driver leaves a cell, they're removed from the old cell and added to the new one. If there's no signal for 30 seconds, they drop out automatically.
The search:
- The passenger's cell plus 1-2 rings of neighbors.
- The free drivers in them, say 50 candidates.
- Re-sort by road ETA, not straight-line distance (because of a river or traffic, the nearest point can be the farthest).
- Send the offer; one offer per driver at a time, which needs a short lock here.
Scaling: a city naturally maps to its own shard, because a search is almost never between cities. In a dense center the cell size is smaller, and on the outskirts larger.
Reliability: losing locations isn't a problem, since they come back in 5 seconds. So it's acceptable to keep this layer in memory only, with no replicas. Trip history and payments are completely different, with reliable storage.
Sign up to mark studied questions and save your progress.