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

S2 and H3

Cut the whole Earth into cells (squares or hexagons) used by Google, Uber and others.

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

01Quick Summary

S2 and H3 are two systems that cut the whole Earth into small cells, each with its own ID. Once every place has a cell ID, "what is near here?" becomes a quick lookup of IDs instead of a hard maths problem.

  • S2 (from Google) wraps the Earth in a cube and splits each face into square-like cells, four times smaller at each level.
  • H3 (from Uber) covers the Earth with hexagons, each cell split into seven smaller ones at each resolution.
  • Both give you a level (or resolution): a higher level means smaller cells and a longer, more exact ID.

02Concept: What is it?

A latitude and longitude pair is exact, but it is hard to search by "nearby". A cell system fixes that: every point is mapped to the cell that contains it, at a chosen size. All points in the same cell share the same ID. To find nearby points, you look up that cell and its neighbour cells.

Cells are nested. A big cell has a set of smaller child cells inside it, so you can zoom in or out by choosing a different level. IDs are plain numbers, so a normal database index can store and search them.

From a point to a cell ID to a lookup
📍lat, lnga rider
→↓pick a level
🔷Cell IDone number
→↓add neighbours
🧩A few cell IDsnearby area
→↓index lookup
🚗Nearby drivers
The point is turned into a cell, the cell and its neighbours are listed, and the database is asked for those cell IDs.

Why squares or hexagons matter

Neighbour distances
Square cell (S2 style)
⬜8 neighbourssides and corners, 2 distances
Hexagon cell (H3)
⬡6 neighboursall one distance
A hexagon has 6 neighbours, all the same distance away. A square has 4 side neighbours and 4 corner neighbours that are about 1.4 times farther.
🧠The cell is the key
A cell ID is just a number. You can store it in a column, put an index on it, group by it, or use it as a partition key. That is why these systems are so handy in a distributed database.

03Real-Life Example

🍵A City Cut Into Numbered Tiles
Imagine a city map covered with numbered floor tiles. To find the coffee shops near you, you do not measure the distance to every shop. You find your tile number, and look at the shops listed for your tile and the tiles around it. If you want a rougher answer, you use bigger tiles made of several small ones. If you want a closer answer, you use smaller tiles. Every shop is simply written in the list for its own tile.
Tiled city map
S2 and H3
A numbered floor tile
A cell with an ID
Your tile number
The cell that contains your point
Tiles around yours
Neighbour cells (a ring of cells)
Bigger tiles made of small tiles
Parent and child cells (a lower level)
Tile size you pick
The level (S2) or resolution (H3)
A shop list for each tile
A database index keyed by cell ID
Hexagonal tiles in a honeycomb
H3's hexagon cells

04Why Do We Need It?

🔎Nearby = lookup
Searching by cell ID uses ordinary indexes and avoids measuring the distance to every point.
🌍Whole Earth
Designed for the sphere. Cells are fairly even in size, and the poles and the date line need no special code.
🪆Zoom in and out
Move between levels by taking a parent or a children list of a cell.
🗄️Easy to store and shard
A cell ID can be a partition key, so a city or a region lives on one shard.
📊Group and count
Group by cell to make heat maps, demand maps and surge-pricing areas.
🧮Covering a shape
Turn a region (a city, a delivery zone) into a list of cells for matching.
Turn the map into numbered cells, and "what is near me?" becomes "give me these few cell IDs".

05Where Do We Use It?

🚕Ride hailing
Match riders with nearby drivers, and compute demand and price by area (H3 was built at Uber for this).
🗺️Maps and search
Find places near a point, or inside a view. S2 is used in several Google products.
🍔Delivery
Match couriers and restaurants, and draw delivery zones as cells.
🗃️Databases
Some databases use S2 for geospatial indexes (for example MongoDB's 2dsphere index).
📈Analytics
Aggregate events by cell to see where things happen.
🌦️Weather and sensors
Bucket readings into even cells to compare areas.

06Types / Parts / How It Works

S2 vs H3 at a glance

S2H3
Cell shapeSquare-like (four-sided) cells on a cubeHexagons (plus 12 pentagons)
Made byGoogleUber
Children of a cell4, and they fit exactly inside7, and they fit only roughly
Levels0 to 300 to 15 (resolutions)
Neighbours8 (sides and corners, two distances)6 (all one distance)
Cell IDA 64-bit number, with a space-filling curve (Hilbert) so near cells often have near IDsA 64-bit number
Strong atExact nesting, covering a region with a few cells of mixed sizesEven neighbour distance, smooth maps, analytics

How the cells are built

The two ideas
S2
🧊Cube around Earth
→↓
⬜6 faces
↓split into 4, repeat
🔢Cell ID on a curvenearby cells, nearby numbers
H3
🔷Icosahedron20 triangle faces
→↓
⬡Hexagon grid
↓about 7 children each
🔢Cell IDresolution inside the ID
S2 splits each square into four, again and again. H3 puts a hexagon grid over the Earth, and each cell has about seven children.
📝Hexagons are not perfect
Hexagons cannot cover a sphere alone. H3 needs 12 five-sided cells at every resolution (they are placed in the sea where possible). A hexagon's children do not fit exactly inside it, so a parent's area is only approximately the union of its children.
VisualizerSquares vs hexagons, and how cells grow with the levelClick a cell and compare the distances to its neighbours on squares and on hexagons. Then slide the level to see the number of cells and the cell area change.
Which system?
Click a cell to pick it. Cyan = your cell, amber = exactly 2 steps away, dark amber = closer.
Neighbours (1 step)
6
all sides, no corners
Distance to them
all 1.00
1.00 = nearest neighbour
Ring at 2 steps
1.73 to 2.00
farthest is 1.15x the nearest
Cells within 2 steps
19
including your own
On hexagons, all 6 neighbours are the same distance away, so 'one step' means one distance. A ring of cells is closer to a circle. That is why H3 is liked for 'what is nearby' and for spreading values (like prices) smoothly.
Cells covering the Earth
14.1 million
2 + 120 x 7^resolution
Average cell area
36.13 km²
Earth area / cells
Children per cell
7
fits only roughly

Counts are exact for the formulas shown. Areas are averages: real cells vary in size a little, depending on where they are on the Earth. H3 also has 12 five-sided cells at every resolution, which this flat patch does not show.

07How to Use It / Steps / Implementation

Finding nearby points with cells

  1. 1
    Pick a level
    Match the cell size to the question. A few hundred metres suits 'cars near me'. A few kilometres suits 'which part of town'.
  2. 2
    Turn each point into a cell ID
    When a record is saved (a driver, a shop), compute its cell ID at that level and store it in a column.
  3. 3
    Index the cell ID
    A normal index is enough. It can also be a partition or shard key.
  4. 4
    Find the search cells
    For a point and a radius, take the point's cell plus the ring of neighbour cells that covers the radius (k steps away).
  5. 5
    Query by those IDs
    Fetch rows whose cell is in the list. This is the cheap, wide first step.
  6. 6
    Filter by real distance
    Cells are a rough shape. Compute the exact distance for the few candidates and drop any that are too far.
  7. 7
    Zoom if needed
    Use the parent cell for a wider view, or the children for finer detail.
💡Cells find candidates, maths finds the answer
A cell lookup gives you a small set of possible points. Always finish with an exact distance check, because a cell edge can sit between two points that are very close.
⚠️Points near a border
A point right at the edge of a cell has near neighbours in the next cell. That is why you must search the neighbour cells too, not only the cell that contains the point.

08Key Terms to Know

TermMeaning in easy words
CellOne small area of the Earth's surface, with its own ID
Cell IDA number (64-bit) that names a cell, and also tells its level
S2Google's system that splits a cube around the Earth into nested square-like cells
H3Uber's system that covers the Earth with nested hexagon cells
Level / resolutionHow small the cells are: higher means smaller cells and longer IDs
Parent and childA cell and the smaller cells inside it, one level down
Neighbours / ringThe cells touching a cell, and the cells exactly k steps away from it
Cell coveringA list of cells that together cover a region such as a city or a circle
Hilbert curveA way of visiting a grid so that cells close in space are often close in the order. S2 uses it
Pentagon cellsThe 12 five-sided cells that H3 needs to close up the sphere
GeohashA simpler, older text-based grid system. See the Geohash topic

09Pros, Cons and Trade-offs

✅ Pros
  • Turns 'near me' into index lookups
  • Works for the whole sphere
  • Nested levels let you zoom easily
  • IDs are plain numbers, easy to store and shard
  • Ready-made libraries in many languages
⚠️ Cons
  • Cells are only a rough shape, so you need an exact check
  • A border can split nearby points into two cells
  • Need to choose a level, and the right one depends on the question
  • Hexagon children do not fit exactly, and H3 has 12 pentagons
  • Cell sizes differ a little across the globe

Trade-offs

ChoiceWe gainWe lose
Higher level (smaller cells)Tighter, more exact resultsMore cells to search, longer lists
Lower level (bigger cells)Few lookupsMore candidates to filter
H3 hexagonsEven neighbour distance, smooth analyticsChildren only roughly nest
S2 squaresExact nesting, flexible region coveringTwo neighbour distances
Cells vs a spatial index (R-Tree)Simple numbers in a normal index, easy to shardNeeds the neighbour search and a final distance check
Cells vs GeohashBetter shapes and coverage of the whole sphereA heavier library to learn

10Common Problems and Mistakes

Common mistakes

  1. Searching only the point's own cell. Close points just across a border are missed.
  2. Skipping the exact distance check. Cells give candidates, not final answers.
  3. A level that is too fine or too coarse. Too fine means huge cell lists. Too coarse means a lot of filtering.
  4. Assuming cells are the same size everywhere. Areas vary a little. Do not use cell area as exact maths.
  5. Assuming a hexagon's children cover it exactly. They only approximately do.
  6. Mixing levels by accident. An ID at one level will not match IDs at another unless you convert to the parent or child.
  7. Ignoring the lat/lng order. Some libraries use (lat, lng), others use (lng, lat). Mixing them puts points on the other side of the world.

Things to watch

🔥Hot cells
A busy city centre cell gets much more traffic. Use a finer level there, or split the load.
🧭Dateline and poles
Good libraries handle them. A hand-made grid often does not.
🔁Moving points
A driver who moves needs a new cell ID. Update the index when they cross a border.
📏Big radius
A large circle needs many cells. Use a coarser level or a mixed-level covering.

11Real-World Examples

🚕Uber
Created H3 and uses it for matching, demand maps and dynamic pricing zones.
🗺️Google
Created S2 and uses it inside many location products.
🍃MongoDB
Its 2dsphere index is based on S2 cells.
🚚Logistics
Delivery companies group orders and couriers by cell to plan routes.
📈Analytics tools
Several analytics and map tools can aggregate and draw data as H3 hexagons.
🏙️City data
Teams group trips, sensors or incidents by cell to compare neighbourhoods.
📝Note
Libraries exist for many languages, and exact cell counts and sizes are in each project's documentation. Check the version you use.
Mini case: find drivers within about 1 km
📍Riderlat, lng
→↓cell + ring of 2
🔷19 cell IDshexagons
→↓index lookup
🚗30 candidates
→↓exact distance
✅6 drivers
Cell lookup Final answer
Cells narrow it to a few candidates. An exact distance check gives the final list.

12Related Topics to Read Next

Geohash→

A simpler text-based way to name cells on a map.

Quad Trees→

The splitting-into-four idea, as a tree.

R-Trees→

Another way to search maps, built from boxes.

Sharding→

Cell IDs make good shard keys for location data.

Indexing→

The ordinary index that makes cell lookups fast.

Consistent Hashing→

Another way to spread keys, like cell IDs, over machines.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: the Earth cut into nested cells, each with a number ID.
  • ✔S2: Google, square-like cells, 4 children, exact nesting, levels 0 to 30.
  • ✔H3: Uber, hexagons, about 7 children, 6 equal-distance neighbours, resolutions 0 to 15.
  • ✔Search: point to cell, add neighbour ring, query by IDs, then filter by exact distance.
  • ✔Level: higher means smaller cells. Pick it to fit the question.
  • ✔Watch: border points, lat/lng order, hot cells, mixed levels.
  • ✔Store: a cell ID is a number, so index it or use it as a shard key.
  • ✔One line: “Name every place by a tile number, then look up tiles instead of measuring distances.”
← Previous
R-Trees
Next →
Bloom Filters