#🧱 Building Block: Geospatial Index
#Overview
A geospatial index encodes 2D coordinates (latitude/longitude) into a structure optimized for proximity queries — "find all points within X km of this point." Common implementations include Geohash, S2 cells, and PostGIS.
#Key Concepts
- Geohash: Encodes lat/lon into a base-32 string where shared prefixes = geographic proximity. Precision grows with string length (6 chars ≈ 1.2 km × 0.6 km cell).
- S2 Geometry (Google): Divides the sphere into a hierarchy of cells using a Hilbert curve. Better area uniformity than Geohash at the poles.
- PostGIS: PostgreSQL extension adding geometry types and spatial operators (
ST_DWithin,ST_Distance). Uses R-tree (GiST) indexes. - R-Tree Index: A tree structure grouping nearby objects in minimum bounding rectangles; efficient for range and nearest-neighbor queries.
- Bounding Box Pre-filter: Convert radius search into lat/lon min/max box, filter with index, then do precise Haversine distance check.
- Haversine Formula: Calculates great-circle distance between two lat/lon points — used for final precision filter after index lookup.
#When to Use
- Proximity Matching: "Show users within 10 km" — core use case for dating apps, ride-sharing, local search.
- Geo-fencing: Trigger events when an entity enters/exits a polygon boundary.
- Spatial Aggregation: Count or group entities by geographic region (e.g., heatmaps).
#When NOT to Use
- When location queries are rare — a standard indexed lat/lon column with Haversine math at query time may be enough.
- When user count per area is very small — overhead of spatial index isn't justified.
#Trade-offs
- Pros: Massive speedup for radius queries; Geohash allows caching by cell; S2 gives better cell uniformity.
- Cons: Geohash has edge-case boundary bugs (two close points in adjacent cells have different prefixes); setup overhead; stale location data requires TTL management.
#Used In This Repo
- Tinder Feed (#26) — Geohash-based candidate lookup for geographic proximity matching