Spatial Queries with Geohash: Inside 'Vehicles Near Me'

In the fall of 2019, the sales team promised a new feature (without asking us, classic): the customer would click a point on the map, and "the 10 available vehicles closest to this point" would be listed within seconds. An attractive promise for freight and delivery companies. I wrote the first prototype in an afternoon: a single query that calculated the Haversine distance for every row in the table holding the last location of 12,000 vehicles and sorted the results. In the test environment, with 300 vehicles, it took 15 milliseconds. In production, with 12,000 vehicles, 900 milliseconds, and this query was going to run 40-50 times per second during delivery hours. On its own, it was maxing out a CPU core.

"Vehicles near me" is a feature that looks innocent but is full of landmines. That fall, we learned this step by step.

The Silent Failure of the Latitude-Longitude Index

The first improvement is the one that occurs to everyone: filter first with a rough rectangle, then run the distance calculation on what's left. WHERE lat BETWEEN ... AND ... AND lng BETWEEN ... We also added a composite (lat, lng) index. The time dropped from 900 to 210 milliseconds, but EXPLAIN was discouraging: the index only helped along the latitude dimension. A B-tree is a one-dimensional structure; it was reading all of the thousands of rows that fell within the lat range and eliminating them against the lng condition one by one. A query at Istanbul's latitude was also running vehicles in Ankara and Izmir, at the same latitude, through the index. That's the answer you get when you ask a two-dimensional question of a one-dimensional data structure.

The right tools were actually clear: either a real spatial index (R-tree) or an encoding that cleverly folds space into a single dimension. We started with the second, because the thing called geohash fit into our existing infrastructure with zero additional components.

Folding the World Letter by Letter

The beauty of the geohash idea is this: you split the world in two, then split each part in two again, and so on; with each split, you interleave the latitude and longitude bits. When you write the resulting bit string in base32 characters, you get a string like "sxk9m". The critical property is this: a common prefix means spatial proximity. Every point starting with sxk9m is inside the same 5-character cell (roughly 5 km × 5 km). So the "what's near me" question turns into an ordinary B-tree's favorite thing: a LIKE 'sxk9m%' prefix search.

The application side was simple. We added an 8-character geohash column to the last-location table (8 characters ≈ a 38 m × 19 m cell), and the write layer computes and writes the hash on every location update. On the query side, we find the 5-character cell of the clicked point, fetch the vehicles matching that prefix, then run the real Haversine calculation on the remaining 50-100 candidates and sort them. The coarse filter comes from the index, the fine filter from the math. Time: 6 milliseconds on average. From 210 down to 6.

The clicked point is converted to a geohash cell, candidates are fetched with a prefix search, filtered with Haversine and the result returns in 6 ms.
The coarse filter comes from the index, the fine filter from the math.

The Truck That Vanished at the Cell Boundary

Then a distribution manager called: "There's a vehicle parked right next to my depot, and your system is suggesting one 4 kilometers away." We checked, and he was right. The depot's location happened to fall on the edge of a geohash cell, while the vehicle right next to it was in the neighboring cell. A prefix search only looks at a single cell; the other side of the boundary can have an alphabetically completely different prefix. In fact, with geohash's Z-curve folding, the codes of two physically adjacent cells can look completely unrelated.

The standard remedy is to run the query on the center cell plus its 8 neighbors (north, south, east, west and the four diagonals). Computing neighbor cells is an off-the-shelf algorithm; we use the nine prefixes in a single query like an IN list, and scanning nine prefixes still takes a few milliseconds. With this fix, the "can't see the vehicle right next to me" complaints stopped. But we also learned this: if your search radius exceeds the cell size, even 9 cells aren't enough. We tied the radius to prefix length: searches up to 2 km run on 5-character cells, and those up to 500 meters on 6-character cells. If you set up the radius-to-prefix mapping wrong, you either get incomplete results or scan half the city.

A single-cell search misses the neighboring vehicle across the boundary; scanning the center cell and its eight neighbors ends the complaint.
If radius and prefix length aren't matched, results are incomplete or the scan is needlessly wide.

So Why Not an R-tree?

The honest answer: partly historical baggage. Our main database was a 5.7 that had been inherited from MySQL 5.6, and when SPATIAL index support came to InnoDB with 5.7, we had only just migrated; we didn't want to entrust a critical query to a feature that had seen little testing in production. An R-tree does real two-dimensional search by nesting rectangles inside boxes, and it has no such thing as a boundary problem; today I'd tell anyone starting from scratch not to skip a look at PostGIS or MySQL 8 SPATIAL. But in our case, geohash had two extra trump cards. The first is portability: we also used the same hash value as a key prefix in Redis and as an in-memory map key inside the application; an R-tree is locked inside the database, while geohash seeps in everywhere. The second: live vehicle locations are updated hundreds of times per second, and everything we read at the time suggested that maintaining an R-tree under heavy updates was more expensive than a B-tree, and we didn't have time to test that.

Let me also share the rough ruler we kept at hand when choosing prefix length: 4 characters is roughly 39 km × 19.5 km (city), 5 characters 4.9 km × 4.9 km (district), 6 characters 1.2 km × 0.6 km (neighborhood), 7 characters 153 m × 153 m (street), 8 characters 38 m × 19 m (building). Each character adds 5 bits, and because the bits are distributed alternately between latitude and longitude, the cells alternate between elongated and square. Rather than memorizing this ruler, we built it into the query layer; a radius comes in, and the prefix length comes out of a function.

As geohash prefix length grows, the cell shrinks: 4 characters is city scale, 5 district, 6 neighborhood, 7 street and 8 characters building scale.
When a radius comes in, a function picks the prefix length from this ruler.

In the next evolution of the system, we carried the same pattern over to Redis. Live locations were already kept in memory; once we grouped the keys by geohash prefix, the "vehicles in this cell" question was answered from Redis in microseconds, and MySQL was freed from this class of queries entirely. (Redis 3.2 also had the GEORADIUS command, which uses geohash internally as well; we had already built our own prefix scheme, so it stayed that way.) The same idea working unchanged across three separate layers (SQL LIKE, Redis keys, an in-memory map) is, to me, geohash's least-known virtue.

A year later, the same geohash column turned out to be useful for something we hadn't expected: a regional density heat map. With GROUP BY LEFT(geohash, 4) at city scale and LEFT(geohash, 6) at neighborhood scale, we could get vehicle density in a single query. Infrastructure built for spatial data spilling over to the analytics side for free was the sweetest side income of this choice.

Back to the measurement summary: naive Haversine 900 ms, bounding box + composite index 210 ms, geohash prefix + 9 neighbors + fine filtering 6-9 ms. Rows read per query dropped from 12,000 to 80 on average. And most importantly, the CPU peaks during delivery hours flattened out; this feature no longer even gets a line in capacity planning.

Let me close with a warning about edge cases: geohash cells get distorted as you approach the poles, and cell widths change because of longitude compression. At Türkiye's latitudes it didn't cause any practical problems, but if you're building a system that operates globally, test your cell size assumptions against latitude. If you're at a similar crossroads in spatial query design (geohash, R-tree, or both), write to us here; I'll tell you firsthand what sinks at which scale.