AI Hints
Home›System Design Tutorial›Case Study: Crawling and Location
System Design · Lesson 107 of 120

Nearby Search: Geohash

Finding close drivers.

⏱ 2 min read▶ Video at 2:10:04🎓 Free
Watch this lesson in the System Design courseWatch on YouTube ↗Full System Design course

A ride sharing app needs to answer, which drivers are within two kilometres of this rider? There are a million drivers, all moving. Checking the distance to every one, for every request, is far too slow.

Nearby Search: Geohash
From the video: Nearby Search: Geohash
  • Drivers within 2 km?
  • A million moving drivers
  • Checking all is too slow

Geohashing a location

A geohash turns a location into a short string. Nearby places usually share the same starting characters. It works by repeatedly halving the map, and recording which half the point is in. Run it. Two points a few streets apart in London share their first six characters. A point in Paris starts completely differently.

geohash.pypython
BASE32 = "0123456789bcdefghjkmnpqrstuvwxyz"

def geohash(lat, lon, length=7):
    lat_r, lon_r, bits, out, even = [-90, 90], [-180, 180], [], "", True
    while len(out) < length:
        r, v = (lon_r, lon) if even else (lat_r, lat)
        mid = (r[0] + r[1]) / 2
        bits.append(int(v >= mid))
        r[0 if v >= mid else 1] = mid
        even = not even
        if len(bits) == 5:
            out += BASE32[int("".join(map(str, bits)), 2)]
            bits = []
    return out

print("London A:", geohash(51.5072, -0.1276))
print("London B:", geohash(51.5079, -0.1281))
print("Paris:   ", geohash(48.8566, 2.3522))
Output
London A: gcpvj0e
London B: gcpvj0d
Paris:    u09tvw0

Using geohashes

To find nearby drivers, store each driver under their geohash prefix, in a fast store like Redis. For a rider, compute their geohash, and look up drivers in that cell and its eight neighbours, because the rider could be near an edge. Then check exact distances for just those few drivers.

keyvalue
Storedrivers by geohash cell
Look uprider's cell + 8 neighbours
Thenexact distance, few drivers
Updateas drivers move

Summary

A geohash turns locations into strings, where shared prefixes mean nearby. Look up the rider's cell and its neighbours, then check exact distances. Next, matching riders with drivers.

Key takeaways
  • Location to string
  • Shared prefix = nearby
  • Cell + neighbours
Next up: Ride Matching — drivers and riders