SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
  • Geohash
  • Quad Trees
  • R-Trees
  • S2 and H3
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Advanced Data Topics/Geospatial Structures

Geohash

Turn a place on the map into a short text code, so nearby places share the same start.

⏱ 12 min readIntermediateInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A geohash turns a place on the map (latitude and longitude) into a short piece of text, like 9q8yyk. The longer the text, the smaller and more exact the area.

  • The map is cut in half again and again. Each cut adds one bit to the code. Every 5 bits become one letter or digit.
  • Places that are close together usually share the same start of the code. So a normal text index can answer β€œwhat is near here?”.
  • The catch: two places can be very close but sit on different sides of a cell edge, so their codes look different. You must also check the neighbouring cells.

02Concept: What is it?

A place on Earth needs two numbers: latitude (north or south) and longitude (east or west). Databases are good at searching one number, such as a sorted column. They are not good at searching two numbers at the same time. Geohash solves this by squeezing the two numbers into one string.

Here is how it works. Start with the whole world as one box. Ask: is the place in the west half or the east half? Write down 0 or 1. Then ask: north half or south half? Write down 0 or 1. Keep taking turns (longitude, latitude, longitude, ...). After every 5 answers, turn the 5 bits into one character from a 32-letter alphabet (0-9 and b-z, without a, i, l, o). That text is the geohash.

Cutting the map in halves
🌍Whole world1 big box
→↓east or west? 1 bit
β—§Halfwest or east
→↓north or south? 1 bit
β—©Quarterand so on
→↓5 bits = 1 character
πŸ“9q8yya small cell
Each answer halves the area. More characters means a smaller cell.

The result is a grid of rectangles. Every rectangle has its own code, and a longer code is a smaller rectangle inside the shorter one. So 9q8y contains 9q8yy, 9q8yz and so on. This prefix rule is what makes geohash useful for search.

🧠One-way rule
Same start of the code means close together. But close together does not always mean the same start. Two shops across the street can have totally different codes if a cell edge runs between them.

03Real-Life Example

🍡The Postcode for Every Doorstep
Imagine a country where every address is a postcode that gets longer the more exact you want to be. β€œ9q” is a big region, β€œ9q8” is a city, β€œ9q8yy” is a few streets, and β€œ9q8yyk” is a single block. To find a pizza shop near you, you just ask the post office for everything that starts with your postcode. You do not need a map. The only trap is that a shop on the next street can be in a different postcode, so you also ask for the postcodes of the streets around you.
Postcodes
Geohash
A postcode
A geohash string
Longer postcode = smaller area
More characters = smaller cell
Same start means same region
Shared prefix means inside the same bigger cell
Ask for all codes that start with mine
A prefix query on a normal index
A shop just over the border has a different code
Neighbours across a cell edge have different hashes
Also ask for the streets around mine
Search the 8 neighbouring cells too
Finding places near me
πŸ“±My locationlat, lon
→↓encode
πŸ”€My cell9q8yy
→↓+ 8 neighbours
πŸ—„οΈIndex lookupprefix match
→↓sort by distance
πŸ“Nearest places
Compute your cell, add its 8 neighbours, fetch by prefix, then sort by real distance.

04Why Do We Need It?

πŸ”ŽTwo numbers become one
A single string can be stored and sorted in any normal database or key-value store.
⚑Fast nearby search
Nearby places share a prefix, so one range or prefix query finds a whole area.
🧩Easy to shard
Use the first few characters as a partition key, so each region lives on its own machine.
🎚️Pick your own detail
Short hash for a city view, long hash for a street. You just cut the string.
🧰Simple to build
A few lines of code and no special database engine. Many stores already support it.
πŸ”’Blurs on purpose
Keeping only a short hash hides the exact spot, which helps privacy.
Geohash lets any database answer β€œwhat is near here?” with a plain text lookup, as long as you remember to check the neighbouring cells.

05Where Do We Use It?

πŸ•Nearby search
Restaurants, shops, drivers and friends near a user.
πŸš•Ride matching
Group drivers and riders by cell to find a close match quickly.
πŸ”΄Redis geo commands
Redis stores places in a sorted set, using a geohash-style number as the score.
πŸ”Search engines
Elasticsearch can group results into geohash cells for map views.
πŸƒDatabase indexes
Some databases (such as MongoDB's older 2d index) build on the same idea.
πŸ—ΊοΈHeat maps
Count events per cell to draw busy areas on a map.

06Types / Parts / How It Works

How big is a cell?

Each extra character makes the cell about 32 times smaller. These sizes are approximate and measured at the equator. Cells get narrower towards the poles.

CharactersCell size (about)Good for
15,000 km Γ— 5,000 kmA huge part of the world
3156 km Γ— 156 kmA region
439 km Γ— 19.5 kmA big city
54.9 km Γ— 4.9 kmA district
61.2 km Γ— 0.6 kmA few streets
7153 m Γ— 153 mA city block
838 m Γ— 19 mA building
94.8 m Γ— 4.8 mA room or a parking spot
Area of one cell, 4 characters39 km Γ— 19.5 km
Area of one cell, 5 charactersabout 1/32 of that
Area of one cell, 6 charactersabout 1/1000 of 4 characters

The edge problem

Close, but different hashes
Cell A: 9q8yy
πŸ“You
Cell B: 9q8yz
πŸ•Pizza shop5 m away
Your cell Neighbour cell
Two points a few metres apart can fall on opposite sides of a cell edge. A search in one cell alone would miss the other.

Other things to know

IdeaWhat it means
Z-order curveTaking turns between longitude and latitude bits walks the map in a zig-zag order. Nearby cells are often next to each other in that order, but not always.
Neighbour cellsA cell has 8 neighbours. Searching all 9 cells fixes the edge problem for small search circles.
Variable precisionYou choose the length. Too short returns too many places, too long returns too few.
Shape of cellsCells are rectangles that are narrower near the poles, so a cell is not a perfect circle of distance.
VisualizerGeohash map: cells, prefixes and the edge problemPick a place and change the hash length. Watch the cell size change. Then search one cell only, and turn on the 8 neighbours to see which places are missed.
You are at
9q8zn9q8yy9q8yy9q8zn9q8zj9q8yu9q8yy9q8yv

Cyan = you, green = returned by the search, dashed amber ring = the truly nearest place, purple = neighbour cells.

Your hash
9q8yy
25 bits
Cell size
3.9 km Γ— 4.9 km
width Γ— height
Cells searched
1
Places returned
2
nearest missed
Hashes (shared start with yours in cyan)
Ferry9q8zn1.5 km
Ballpark9q8yy1.9 km
Wharf9q8zn2.4 km
Mission9q8yy3.6 km
Peaks9q8yv5.1 km
Presidio9q8zj5.3 km
Park9q8yu7.2 km
The search returned 2 place(s) but missed the closest one: Ferry Building is only 1.5 km away, in another cell. Neighbours across a cell edge have different hashes.

Real geohash encoding (base 32, longitude bit first). Coordinates are approximate and distances are straight-line estimates. Each extra character adds 5 bits, so cells become 32 times smaller.

07How to Use It / Steps / Implementation

Finding places near a point

  1. 1
    Store a geohash with every place
    Compute it once when the place is saved, with a fixed length such as 7 or 8. Put an index on that column.
  2. 2
    Choose a length that fits the search radius
    Pick the length where one cell is about as big as your search circle. A 1 km search suits about 6 characters.
  3. 3
    Encode the user's location
    Use the same length. This is the centre cell.
  4. 4
    Add the 8 neighbours
    Compute the cells around the centre cell, so places just over an edge are included.
  5. 5
    Fetch by prefix
    Query for rows whose geohash starts with any of the 9 codes. This is a fast index range scan.
  6. 6
    Filter by real distance
    Compute the true distance (for example with the haversine formula), drop places outside the radius and sort the rest.
πŸ’‘Use a library for neighbours and edges
Finding neighbour cells by hand is easy to get wrong near the poles and near the 180Β° line. Use a well-tested library or the built-in geo features of your database.
⚠️A cell is not a circle
The 9-cell search returns a square-ish area that is bigger than your circle. Always do the final distance check. Otherwise you will show places that are too far away.

08Key Terms to Know

TermMeaning in easy words
Latitude / longitudeThe two numbers that give a place on Earth: north-south and east-west
GeohashA short string that names a rectangular cell on the map
PrecisionHow many characters the hash has. More characters means a smaller cell
PrefixThe start of a string. A hash that starts with another hash lies inside it
Base 32The 32-symbol alphabet geohash uses (0-9 and b-z without a, i, l, o)
CellOne rectangle of the grid, named by one geohash
NeighboursThe 8 cells touching a given cell
Edge problemClose places in different cells have different hashes
Z-order curveThe zig-zag order made by taking turns between the two coordinates
HaversineA formula for the distance between two points on a sphere
Bounding boxA rectangle on the map, used to limit a search

09Pros, Cons and Trade-offs

βœ… Pros
  • Works with any ordinary index or key-value store
  • Very simple idea and easy to code
  • Prefix length gives free zoom levels
  • Easy to shard by region
  • Good enough for most β€œnear me” features
⚠️ Cons
  • Close places can have very different hashes
  • Needs neighbour cells to be correct
  • Cells are distorted near the poles
  • Cells are rectangles, so distance is only approximate
  • Cell size jumps by 32 times per character, with no in-between

Trade-offs

ChoiceWe gainWe lose
Longer hashA more exact area and fewer places to filterMore cells to search for a large radius
Shorter hashFewer cells to look upMany more places to filter by distance
Search 9 cellsNo missed neighbours across edgesMore lookups and extra rows to throw away
Search 1 cellFastest, simplest queryMisses close places on the other side of an edge
GeohashSimple and works everywhereUneven cells and the edge problem
S2 or H3 cellsMore even cells and better neighbour handlingA special library and a more complex idea

10Common Problems and Mistakes

Common mistakes

  1. Searching only one cell. The nearest place is often just across an edge, and you will miss it.
  2. Trusting the prefix as a distance. Same prefix means close, but a different prefix does not mean far.
  3. Skipping the final distance check. The 9 cells cover more than your circle.
  4. Using a very long hash for a big radius. You would need hundreds of cells. Pick a shorter length instead.
  5. Swapping latitude and longitude. Mixing up the order puts everything in the wrong ocean.
  6. Hot cells. Using a short prefix as a shard key puts a whole busy city on one machine.

Things to watch

🧊Poles and the date line
Cells are strange near the poles and across the 180Β° line. Test these places.
πŸ”₯Busy cells
A big city has far more data than a desert. Shard by a longer prefix there.
πŸ“Wrong precision
If results are too many or too few, the hash length does not fit the radius.
🚢Moving objects
A driver changes cell often. Updating the index on every move can be costly.

11Real-World Examples

πŸ”΄Redis GEO
GEOADD and GEOSEARCH store places in a sorted set using a geohash-based score.
πŸ”Elasticsearch
A geohash grid aggregation counts documents per cell to draw maps.
πŸƒMongoDB
The older 2d index is built on geohash ideas, while newer 2dsphere indexes use spherical cells.
πŸš—Ride and delivery apps
Group drivers and orders by cell as a first, quick filter.
πŸ—ΊοΈMap dashboards
Counting events per cell gives a heat map at any zoom level.
πŸ”’Privacy blur
Sharing only a short hash tells an area but not the exact home.
πŸ“Note
Product details change between versions. Check the current documentation before relying on a specific behaviour.
Mini case: find cafes within 500 m
πŸ“±Userlat, lon
→↓length 6
πŸ”€9 cellscentre + 8 neighbours
→↓prefix queries
πŸ—„οΈIndex~40 cafes
→↓distance filter
β˜•12 cafeswithin 500 m
Neighbours plus a final filter give a correct and fast answer.

12Related Topics to Read Next

Quad Trees→

Another way to cut the map, but the cells split only where there are many points.

R-Trees→

Index boxes and shapes, not just points.

S2 and H3β†’

Cell systems with more even shapes and better neighbours.

Indexing→

Geohash search works because a normal index can do a prefix scan.

Sharding→

A hash prefix is a natural key for splitting data by region.

Key-Value Databases→

Redis stores geohash-scored places in a sorted set.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”What: a short string naming a rectangle on the map. More characters, smaller cell.
  • βœ”How: halve the map again and again (longitude, latitude, ...). 5 bits make one base-32 character.
  • βœ”Prefix rule: same start means inside the same cell. The reverse is not always true.
  • βœ”Search: encode, add the 8 neighbours, prefix-query, then filter by real distance.
  • βœ”Length: match the cell size to the search radius. 6 characters is about 1 km.
  • βœ”Weak spots: cell edges, poles, rectangular cells, hot cells.
  • βœ”Used in: Redis GEO, Elasticsearch geohash grid, ride and delivery apps, heat maps.
  • βœ”One line: β€œTurn two coordinates into one string, so a plain index can find what is near.”
← Previous
Ring Buffer
Next β†’
Quad Trees