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/GEOSEARCH uses 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:

  1. The passenger's cell plus 1-2 rings of neighbors.
  2. The free drivers in them, say 50 candidates.
  3. Re-sort by road ETA, not straight-line distance (because of a river or traffic, the nearest point can be the farthest).
  4. 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.