← Building blocks

Find things near a point

Real-time & streamingsenior

"Drivers within 2 km" is a 2-D query that a B-tree cannot answer.

Say it like this

Nearby search is a two-dimensional range query, so I bucket positions into fixed cells with a geohash, query the rider cell plus its eight neighbours from Redis GEO, and rank the candidates by road ETA.

Basic solution

Encode location into cells (geohash, H3, S2) and query the target cell plus its neighbours; or use a spatial index.

Redis GEOH3S2PostGISquadtrees for static points

Nearby search over cells

The rider cell and its eight neighbours are fetched together, filtered for freshness, then the top candidates are ranked by road ETA rather than straight-line distance.

How it works

  1. Each driver position update is encoded into a cell id: a geohash prefix of the chosen precision, or an H3 / S2 cell at the chosen resolution. Nearby positions get the same cell id, which turns a two-dimensional "near" question into an equality lookup.
  2. The index stores cell → set of (driver id, lat, lng, updated_at). In Redis GEO this is one sorted set per region, where each member's score is its interleaved geohash, so members that are close on the map are close in the sorted order.
  3. A nearby query computes the rider's cell and its 8 neighbours, because a rider standing near a cell edge has close drivers in the next cell over.
  4. It fetches the members of those 9 cells (or runs GEOSEARCH with a radius, which does the neighbour expansion internally), drops drivers whose last update is too old or who are not available, then ranks the rest by distance.
  5. If too few candidates remain, it widens to the next ring of cells or a coarser cell; if too many, it caps the list and keeps the nearest.
  6. The top few are passed to an ETA service that replaces straight-line distance with travel time over the road network.

Picking the cell size

  • Geohash precision 6 is ~1.2 km × 0.6 km; precision 5 is ~5 km × 5 km. Choose so a typical search touches a handful of cells with tens of drivers each.

Worked example

Ride matching in a large city

  • 50K active drivers in the metro, 1,000 match requests per minute at peak.
  • Geohash precision 6 over a 40 km × 40 km city ≈ 2,000 cells, so ~25 drivers per cell on average, a few hundred in the centre. That is the right density: a 9-cell query returns a workable candidate list.
  • A query reads 9 cells ≈ 225 candidates average, up to ~2,000 downtown; filter to available and updated within 15 s, leaving maybe 50; rank by distance, send the top 10 to ETA.
  • Redis GEOSEARCH on a sorted set of 50K members returns a 2 km radius in well under a millisecond; 17 queries/s is nothing, so the index is never the bottleneck.
  • Updates: 50K drivers every 4 s = 12.5K GEOADD/s. One Redis node handles that; shard by city when you reach many cities.
  • Memory: 50K members × ~100 B ≈ 5 MB per city.

Variants and when each wins

Geohash with sorted sets (Redis GEO)

  • Fixed rectangular cells whose ids share a prefix when they are near each other, stored in a sorted set. It is trivial to run and is the default; cells distort with latitude and the edge effect needs the neighbour query.

H3 / S2 cells

  • Hexagonal (H3) or spherical (S2) cells that nest into finer levels, with uniform neighbours and good ring queries. They win at Uber and Google scale where cell distortion matters; they bring a library dependency and a learning curve.

Quadtree

  • A tree that splits any crowded cell into four smaller ones, so dense areas get finer cells automatically. It wins for mostly static points such as restaurants; rebalancing under constantly moving drivers is expensive.

R-tree / PostGIS

  • A spatial index inside a relational database with rich queries: polygons, distance joins. It wins for mostly static data that needs those queries; it is slower for high-frequency point updates.

Use Redis GEO or H3 for moving objects; a quadtree or PostGIS for static places.

Failure modes

Edge effect

  • A rider at a cell border sees no drivers while one is 100 m away. It happens because only the rider's own cell was queried and the nearby driver is in the next cell. Fix it by always including the 8 neighbours, or by using a radius search that expands cells internally.

Dense-city hot cell

  • One downtown cell holds 2,000 drivers and every query there scans all of them. It happens because the cell size is fixed regardless of density. Fix it by using a finer precision in dense regions (hierarchical cells), or by capping candidates per cell and sorting by freshness.

Stale positions

  • Riders get matched to drivers who left the area minutes ago. It happens because index entries are never expired. Fix it by storing updated_at with each entry, filtering on it at read time, and sweeping entries older than 60 s.

Region shard outage

  • No matches in one city. It happens because that city's Redis node is down. Fix it with a replica and automatic failover, and remember the index is rebuildable from the location stream within seconds, so recovery is a replay.

Straight-line ranking

  • The "nearest" driver is across a river with no bridge. It happens because candidates were ranked by straight-line distance only. Fix it by ranking the top candidates by road ETA from a routing service, not by haversine distance.

Interviewer follow-ups

Answer out loud before you open each one.

Why is a quadtree a poor fit for drivers but fine for restaurants?

A quadtree splits cells as points accumulate, which is ideal when points are static and the tree is built once. Drivers move every few seconds, so nodes constantly split and merge, and the in-memory tree needs locking and rebalancing. Fixed cells make an update a single key write.

What geohash precision gives roughly 1 km cells?

Precision 6, which is about 1.2 km by 0.6 km. Precision 5 is around 5 km, precision 7 around 150 m. Pick the one where a 9-cell query covers your typical search radius with tens, not thousands, of candidates per cell.

How do you shard the index for many cities?

By region, since nearby queries never cross cities. Each region gets its own Redis sorted set (or node) keyed by a region id derived from a coarse cell. Updates and queries both carry the region, so routing is a lookup, and one region outage does not affect the others.

How do you go from nearby candidates to a match?

Filter to available and fresh, rank the top ten by road ETA from a routing service, then run the offer protocol: lock the best driver, offer with a timeout, and on decline move to the next. The geo index only produces candidates; matching is a separate service.

Connections

Built on
Geohash and hierarchical cells (H3, S2) · Quadtree
Pairs with
Ingest millions of position updates · Make sure only one worker does it · Shard by region · Expire data automatically
Pulls against
Default to a relational database
Used in
Ride Matching (Uber / Lyft)

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon EC2 Auto ScalingMatcher, ETA serviceCompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad
Amazon ElastiCacheRedis GEOMemorystoreAzure Managed RedisRedis, Valkey, Memcached
Amazon Kinesis Data StreamsLocation streamPub/SubEvent HubsApache Kafka, Redpanda, Apache Pulsar