Practice this topic in a realistic system design interview
Many location-based systems need to answer one question quickly:
What places are near this point?
Geohash helps answer it by turning a latitude and longitude into a short string. Nearby places often share the same starting characters, so a regular database index can find them with a simple prefix search.
In this chapter, we'll learn what a Geohash is, how it turns a latitude and longitude into a short string, how systems use it to find nearby places, and the edge cases you need to handle when using it.
Imagine you're building a food delivery app. When a user opens the app, you want to show them all restaurants within 500 meters of their location.
Each restaurant has a latitude and a longitude. So a straightforward approach is to store them in two separate columns in a relational database and add an index on each one:
The problem is that a traditional database index, like a B-tree, organizes data in one dimension. It can quickly find restaurants within a latitude range. Or within a longitude range. But filtering by both ranges together is much less efficient.
If the database starts with the latitude index, it finds restaurants in a narrow strip that stretches all the way around the world, and then has to filter those results by longitude. With millions of restaurants, that means scanning a lot of unnecessary data just to find a few nearby places.
What we need is a way to represent a two-dimensional location as a single value that a regular database index can search efficiently.
Geohashing solves this problem by converting a location into a short string of letters and numbers.
Each Geohash represents a rectangular area on the map, rather than a single point, and its length decides how large that area is. A shorter Geohash covers a larger area. A longer one narrows it down to a smaller area inside it.
For example, around San Francisco:
9q8y covers an area roughly the size of a city.9q8yyk covers a neighborhood-sized cell inside it.9q8yyk8 covers a cell about the size of a city block.Geohashing also has another useful property. Nearby locations often share the same starting characters, also called a prefix. So a question about two-dimensional distance turns into a string prefix search, which a regular database index can handle efficiently.
Gustavo Niemeyer created Geohash in 2008. It became popular because a Geohash is just a string: you can store it in a normal column, sort it, search it by prefix, and index it with a B-tree.
Geohash encoding has three steps:
To understand how a Geohash is created, let's start with longitude. Longitude ranges from -180 to +180 degrees.
First, we divide this range into two halves at 0. If our location falls in the left half, we write down a 0. If it falls in the right half, we write down a 1.
Next, we take the half that contains our location and divide it in half again, recording another 0 or 1 depending on where the location falls. We repeat this process, narrowing the range by half each time. After several steps, we have a sequence of bits that pins the longitude to a very narrow range.
We follow the same process for latitude, which ranges from -90 to +90 degrees.
Let's walk through an example using San Francisco, which sits at roughly 37.8 degrees latitude and -122.4 degrees longitude. We'll use 37.7749, -122.4194 for the exact values.
Starting with longitude, -122.4 falls to the left of 0, so our first bit is 0. This narrows the range to -180 to 0. Next, it's also to the left of -90, so the second bit is 0. But it's to the right of -135, so the third bit is 1.
| Step | Range | Midpoint | Value | Bit |
|---|---|---|---|---|
| 1 | [-180, 180] | 0 | Left of midpoint | 0 |
| 2 | [-180, 0] | -90 | Left of midpoint | 0 |
| 3 | [-180, -90] | -135 | Right of midpoint | 1 |
| 4 | [-135, -90] | -112.5 | Left of midpoint | 0 |
| 5 | [-135, -112.5] | -123.75 | Right of midpoint | 1 |
The first five longitude bits are:
Now let's do the same for latitude. Since 37.8 is above 0, our first bit is 1. It's below 45, so the second bit is 0. And since it's above 22.5, the third bit is 1.
| Step | Range | Midpoint | Value | Bit |
|---|---|---|---|---|
| 1 | [-90, 90] | 0 | Above midpoint | 1 |
| 2 | [0, 90] | 45 | Below midpoint | 0 |
| 3 | [0, 45] | 22.5 | Above midpoint | 1 |
| 4 | [22.5, 45] | 33.75 | Above midpoint | 1 |
| 5 | [33.75, 45] | 39.375 | Below midpoint | 0 |
The first five latitude bits are:
We keep dividing the ranges and recording bits until we reach the level of precision we need.
Now we have two sequences of bits, one for longitude and one for latitude. The next step is to combine them into a single sequence, and Geohashing does this by interleaving the bits.
We take the first longitude bit, followed by the first latitude bit, then the second longitude bit, the second latitude bit, and so on:
This keeps both dimensions balanced as we add more bits. Each longitude bit narrows the area horizontally, while each latitude bit narrows it vertically. So with every additional pair of bits, the rectangle gets smaller in both directions.
This way of mixing bits is also known as a Morton code, or Z-order curve. It turns a 2D point into one ordered value while keeping many nearby points close together in that order.
Finally, we split the combined sequence into groups of five bits. Each group becomes a single character, using an alphabet of 32 letters and digits, known as Base32:
The letters a, i, l, and o are left out because they are easy to misread.
For our San Francisco example, the first ten bits produce the characters 9 and q:
That's why every Geohash around San Francisco starts with 9q. If we keep going to 8 characters, we get:
The full flow looks like this:
Every step is deterministic, so the same coordinates always produce the same string. That is what lets a Geohash work as a plain index key.
Each character in a Geohash adds five more bits, which divide the current cell into 32 smaller cells. So the more characters we add, the smaller and more precise the area becomes.
Approximate cell sizes near the equator:
| Length | Cell Width | Cell Height | Roughly the size of |
|---|---|---|---|
| 1 | 5,000 km | 5,000 km | A continent |
| 2 | 1,250 km | 625 km | A large country or region |
| 3 | 156 km | 156 km | A metro region |
| 4 | 39.1 km | 19.5 km | A city |
| 5 | 4.9 km | 4.9 km | A town or district |
| 6 | 1.2 km | 0.61 km | A neighborhood |
| 7 | 153 m | 153 m | A city block |
| 8 | 38 m | 19 m | A building |
| 9 | 4.8 m | 4.8 m | A room-sized area |
| 10 | 1.2 m | 0.6 m | Finer than most GPS readings |
These sizes are approximate and vary with latitude. Cell height stays about the same, but cell width shrinks as you move toward the poles. In San Francisco, at about 38 degrees north, a 6-character cell is closer to 1 km wide.
In practice, you choose the Geohash length based on how precise your searches need to be. We'll see how to pick it for a radius search in Section 9.
Since each extra character narrows down the previous cell, Geohashes naturally form a hierarchy.
The Geohash 9q8 covers a larger area that contains every smaller cell starting with 9q8. Similarly, 9q8y covers a smaller area that contains every cell sharing that prefix.
This means two locations with a long common prefix fall within the same small cell, so they must be fairly close to each other. For example, if two restaurants have Geohashes that start with the same six characters, they're in the same neighborhood-sized area.
This is what makes Geohashing useful for indexing. Locations in the same cell share a common prefix, so their Geohashes sit next to each other in a sorted database index, which makes them easy to find together.
Now let's see how we can use Geohashing in our food delivery app.
When a restaurant is added, we calculate its Geohash and store it in a regular string column. We keep the raw latitude and longitude too, since we'll need them later to compute exact distances. We then create an ordinary index on the Geohash column:
In PostgreSQL, the text_pattern_ops option lets LIKE 'prefix%' queries use the index. Other databases have their own rules for when a prefix match can use an index.
To find restaurants within a particular cell, we simply run a prefix query. For example, we might search for all restaurants whose Geohashes start with a specific six-character prefix:
The database can handle this efficiently with an index range scan. It jumps to the first matching Geohash and scans forward until the strings no longer match the prefix. You can also write the same query as an explicit string range:
That range means "all strings starting with 9q8yyk" because m comes right after k in the Geohash Base32 alphabet.
So we get location-based searches from a regular index, in almost any database, without special spatial support. However, there's an important limitation to this approach.
Suppose a user is standing near the edge of a Geohash cell, and there's a restaurant just 50 meters away, on the other side of the boundary.
Even though the restaurant is nearby, it belongs to a different cell. So its Geohash might share only a short prefix with the user's Geohash. In some cases, they might not share any prefix at all.
For example, two locations on opposite sides of the equator or the prime meridian can be just a few meters apart, yet their Geohashes may start with completely different characters:
These two points are about 2 meters apart, but their Geohashes don't share a single character.
This means that if we only search within the user's cell, we could miss restaurants that are actually very close.
If two locations share a long Geohash prefix, we know they're relatively close. But just because two locations are close doesn't mean they'll share a long prefix.
This is the most common Geohash bug: the search works in a demo, then misses results near cell edges in production.
The standard solution is to search the neighboring cells as well.
Every Geohash cell has eight neighbors. There's one to the north, south, east, and west, along with four diagonal neighbors at the corners. Together with the user's own cell, they form a three-by-three grid of nine cells.
Here is the grid around our San Francisco cell 9q8yyk:
So instead of searching just one cell, we search all nine. Now any restaurant within one cell's width and height of the user lands somewhere in that grid, even if it's on the other side of a boundary.
The query becomes a set of prefix scans:
We can calculate these neighbors directly from the Geohash string, and most Geohash libraries already provide a function for this. The implementation at the end of this chapter includes one.
And nine small index lookups are still far cheaper than scanning a strip that stretches around the world.
For this nine-cell search to work correctly, we need to choose the right cell size. Each cell should be at least as wide and as tall as our search radius.
For our 500 meter search, a six-character Geohash works well. These cells are about 1.2 kilometers wide and 600 meters tall. So even if the user is standing near a cell boundary, the three-by-three grid reaches at least 600 meters in every direction, which covers the full 500 meter radius.
But what if we use seven characters? Those cells are only about 150 meters across. So searching just nine of them could miss restaurants that are 400 meters away.
On the other hand, with five characters, the nine-cell grid would be about 15 kilometers on each side. That still works, but it returns far more restaurants than we need.
| Length | Cell size | 9-cell grid | Result for a 500 m search |
|---|---|---|---|
| 5 | 4.9 km × 4.9 km | ~15 km × 15 km | Correct, but far too many candidates |
| 6 | 1.2 km × 0.6 km | ~3.6 km × 1.8 km | Correct, with a small candidate set |
| 7 | 153 m × 153 m | ~460 m × 460 m | Can miss restaurants 400 m away |
So the goal is to choose the longest Geohash whose cells are still large enough to cover our search radius.
If no single precision fits well, for example when the radius is much larger than one cell, you can generate every cell that covers the search area instead of using a fixed 3×3 grid. It's also worth measuring candidate counts in both dense and sparse regions before settling on a precision.
There's one more step we need to handle.
The nine Geohash cells form a rectangle, but we're looking for restaurants within a 500 meter radius, which is a circle. So some restaurants in those cells, especially near the corners, could be farther than 500 meters from the user.
To filter them out, we calculate the actual distance between the user and each candidate restaurant, usually with the Haversine formula or a database distance function. Then we keep only the ones within 500 meters and sort them by distance:
This two-step approach is common in spatial queries:
Now let's put everything together and walk through the complete flow.
When a user opens the app, the service takes their location and converts it into a six-character Geohash. It then calculates the eight neighboring cells and runs prefix queries to find restaurants across all nine. Next, it calculates the actual distances, filters out restaurants beyond 500 meters, and sorts the rest by distance before returning them.
Whenever a restaurant is added or changes its location, we calculate its Geohash and update the database.
We can use a similar approach for moving objects, like delivery drivers. Whenever a driver sends a location update, we recalculate their new Geohash and update their stored location.
Drivers can send updates every few seconds, so the write path needs some care:
In a real app, the location filter is usually combined with other filters, such as whether the restaurant is open or delivers to the user's area:
Besides the cell boundary problem, Geohashing has a few other limitations worth understanding.
Geohashing divides latitude and longitude into equal intervals, but those intervals don't represent the same physical distance everywhere on Earth.
As we move toward the poles, lines of longitude get closer together, making Geohash cells narrower in actual distance. At the equator, one degree of longitude is about 111 km. Near the poles, it approaches zero. As a result, a cell near the equator covers a much larger area than a cell with the same Geohash length near the poles.
Another limitation is that Geohashing uses a fixed grid that doesn't adapt to how data is distributed.
For example, a cell in a busy city might contain thousands of restaurants, while a cell of the same size in a rural area might contain none. This means searches in densely populated areas can return a large number of candidates that need to be filtered by actual distance. The grid itself doesn't automatically adjust to handle these differences in density.
Points just east and just west of the 180° longitude line are physically close, but they sit at opposite ends of the longitude range, so their Geohashes are completely different. Neighbor calculations there need wraparound logic. Near the poles, cells become very thin, and the 3×3 grid gets less reliable.
Most apps never need to handle these cases. If yours does, a spherical index such as S2 handles them better.
Geohashing is useful for more than just finding nearby places.
Since it groups locations into cells, we can also use it to aggregate data across different areas.
For example, suppose we want to build a heat map showing where ride requests are coming from. We can count the number of requests in each six-character Geohash cell and display those counts on a map.
If we want to zoom out and see a larger area, we can simply shorten the Geohash prefixes and combine the counts of the smaller cells. This lets us analyze location data at different levels of detail.
Geohash prefixes can also help us distribute location data across servers. For example, we could assign all drivers whose Geohashes start with 9q to the same group of servers.
However, the uneven distribution of locations creates a challenge here as well. A partition covering a busy city might receive far more traffic than one covering a rural area. To handle this, we may need to divide busy regions into smaller partitions or allocate more servers to them.
Geohashing is also used in many real-world systems.
Redis uses Geohash-based encoding to store location data in sorted sets, with each location represented by a numeric score. This allows Redis to efficiently narrow down nearby locations using score ranges, before filtering them by actual distance.
Use GEOSEARCH for new code instead of the older GEORADIUS command. Redis works well for live data like driver locations, as long as the active data fits in memory.
Elasticsearch supports Geohash grid aggregations, which let us group documents by geographic area. This is the heat map idea from the previous section, built into the search engine. It also supports regular distance queries on geo_point fields:
And many applications simply store Geohashes in a regular database column and use an ordinary index to support location-based queries, just like we did in Section 6.
This flexibility is one of the biggest advantages of Geohashing. We can use it with many existing databases and indexing structures, without always needing a dedicated spatial database.
That said, if your database already has strong geospatial support, such as PostGIS in PostgreSQL or 2dsphere indexes in MongoDB, it's often simpler to use that for nearby queries. Geohash is still handy there as a key for sharding, caching, or grouping data by area.
Geohashing is a good choice when you need fast proximity searches using a regular database or key-value store. It's also useful for grouping locations by area, such as when building heat maps.
However, it's not always the best option.
| Method | Strengths | Weaknesses | Good Fit |
|---|---|---|---|
| Geohash | Simple string key, prefix scans, works with any ordered index | Boundary issues, rectangular cells, distortion near the poles | Nearby search on a regular database, heat maps, sharding |
| Quadtree | Adapts to dense and sparse areas | Usually custom code; needs rebalancing as data changes | Uneven data, in-memory spatial indexes |
| S2 | Consistent coverage of the whole globe, handles the poles and Date Line | More complex than Geohash | Global systems, covering areas with cells |
| H3 | Hexagonal cells of similar size, all neighbors at the same distance | Cells don't nest perfectly | Spatial analytics, marketplace balancing, heat maps |
| R-tree | Indexes shapes as well as points; overlap and intersection queries | Needs spatial database support (e.g. PostGIS) | Delivery zones, geographic boundaries |
The following implementation is small enough to study. It includes encoding, decoding, neighbor lookup, and distance filtering.
For production code, prefer a maintained library. Edge cases around poles, Date Line wrapping, precision, and query covering are easy to get wrong in small ways that are hard to notice.
Expected output:
A Geohash converts a latitude and longitude into a short string by repeatedly dividing each range in half and interleaving the resulting bits.
Each additional character divides the current cell into 32 smaller cells, so longer Geohashes represent smaller, more precise areas.
Since locations in the same cell share a common prefix, an ordinary database index can find nearby places with simple prefix searches.
However, two nearby points can fall on opposite sides of a cell boundary, so we search the user's cell along with its eight neighbors. We choose a precision where the cells are large enough to cover the search radius, and then filter the candidates by their actual distance.
10 quizzes