Design a Proximity Service Like Yelp: Geohash vs Quadtree & Spatial Indexing
Why BETWEEN lat_min AND lat_max Doesn't Scale
WHERE latitude BETWEEN ... AND longitude BETWEEN ...) fails because standard B-Tree indexes optimize one dimension at a time. Filtering 200 million businesses across latitude leaves millions of rows still requiring intersection with longitude.(lat, lon) into 1D spatial indexes so range lookups run in milliseconds.Proximity Service Geohash vs Quadtree
1. Read vs. Write Asymmetry
- Search QPS: 100M DAU × ~5 searches/day $\approx 5,000\text{ QPS}$ (Peak: 15K+ QPS).
- Business Updates: New restaurants open or change hours rarely (writes are tiny and can tolerate seconds of eventual consistency via nightly/CDC cache sync).
- Total Data: 200M businesses fit comfortably in ~200 GB for full details, and only ~1.7 GB for
(business_id, lat, lon)spatial index entries!
2. Geospatial Indexing Strategies Compared
Approach A: Geohash (Base32 Grid Encoding)
9q8zn).- Property: Longer shared prefix = closer geographic distance.
- Precision Guide: Level
4($\approx 39\text{km} \times 19\text{km}$), Level5($\approx 4.9\text{km} \times 4.9\text{km}$), Level6($\approx 1.2\text{km} \times 0.6\text{km}$). - Critical Boundary Gotcha: Two stores 50 meters apart across a prime grid boundary can have completely different prefixes! Solution: Always query the target geohash cell plus its 8 surrounding neighbor cells (
9cells total) in parallel! - Redis Native Support:
GEOADD/GEOSEARCHstores 52-bit geohashes inside sorted sets out of the box.
Approach B: Quadtree (In-Memory Adaptive Tree)
- Superpower: Adapts dynamically to population density! Manhattan splits deeply into city blocks, while the Pacific Ocean remains a single leaf node.
- Memory: Storing
(lat, lon, business_id)for 200M entries in a Quadtree requires ~1.7 GB RAM—easily fits in memory on a single replicated cluster of read nodes!
| Index Engine | Density Adaptation | Update Complexity | Best Infrastructure Fit |
|---|---|---|---|
| Geohash + Redis | Static grid size | Very easy (HSET/GEOADD) | Dynamic businesses / Redis clusters |
| Quadtree (In-Memory) | Adaptive to dense cities | Rebalance on inserts (rebuild nightly) | Static discovery (Yelp/Maps POI) |
| Google S2 / Uber H3 | Uniform hexagons/spherical cells | Low distortion near poles | Ride-sharing / dynamic pricing grids |
3. Production Caching Architecture
- Geohash Index Cache:
geohash_prefix -> [business_id_1, business_id_2, ...] - Business Detail Cache:
business_id -> { name, address, rating, hours, photo_urls }
(lat, lon, radius) to the matching Geohash precision + 8 neighbors, unions cached IDs in parallel, computes exact Haversine distance filtering, and batch-hydrates business details from Redis in < 20ms.