# S2 geometry

> S2 geometry is a library for working with shapes on a sphere, including a hierarchical grid of cells covering Earth. In system design, S2 cells turn locations and search regions into indexable keys so you can find nearby objects or aggregate geographic activity without scanning every record.

Source: https://sysround.com/concepts/s2-geometry
Updated: 2026-11-05


## How s2 geometry works

S2 projects the six faces of a cube onto a sphere. Each face is a level-0 cell, and each cell splits into four children, down to level 30. Cells are curved quadrilaterals rather than latitude-longitude rectangles; cells at the same level have similar, but not equal, areas.

Each cell has a 64-bit S2CellId encoding its face, position along a Hilbert space-filling curve, and level. Descendants of a cell occupy a contiguous ID range. This makes hierarchical range scans possible, but numerical closeness between IDs is not a reliable measure of geographic distance.

For a point index, convert latitude and longitude to an S2 cell at a chosen level and index records by that cell ID. For example, a driver record might contain driver_id, cell_id, coordinates, and last_seen. You can store membership under a composite key such as (cell_id, driver_id), while retaining coordinates for final distance checks.

For a nearby query, construct a spherical search cap and ask a region coverer for cells whose union contains it. The covering usually includes space outside the requested region. If records use one fixed cell level, query covering cells at that level; alternatively, index leaf IDs and scan each covering cell's descendant range. Mixed-level coverings require explicit containment or range handling, not simple equality against fixed-level keys.

Retrieve candidates, deduplicate when necessary, and apply the actual geographic predicate, such as spherical distance within 3 kilometers. For moving objects, update cell membership when they cross a boundary and expire stale positions. S2 narrows the search; it does not provide freshness, exclusive driver assignment, road distance, or travel-time estimates.

## Worked example: Finding drivers within 3 kilometers

Suppose a ride-hailing service tracks 100,000 online drivers, each reporting a location every 5 seconds: about 20,000 location updates per second. Store each driver's latest coordinates and timestamp, plus membership in a fixed-level S2 cell. For a pickup request, cover a 3-kilometer spherical cap with cells at that level and fetch their driver memberships. If those lookups return 800 candidates and exact distance checks retain 520, only those 520 proceed to freshness, availability, and routing checks. These candidate counts are illustrative, not S2 guarantees. On cell changes, use versioned updates and expire obsolete entries. Finally, reserve the selected driver atomically; spatial proximity alone cannot prevent two requests from assigning the same driver.

## Trade-offs

- **Cell precision versus query fan-out.** Smaller cells reduce irrelevant candidates but require more cell lookups to cover the same search area.
- **Covering size versus filtering work.** A coarser covering uses fewer ranges but admits more false positives that must be removed with exact geographic checks.
- **Spatial locality versus uneven load.** Nearby records are convenient to group, but a busy downtown cell can become a hot partition and may need finer cells or additional partitioning.
- **Moving-object freshness versus write cost.** Frequent location updates and boundary crossings increase index maintenance, while delayed updates can miss objects near their current position.
- **Global geometry versus modeling limits.** S2 handles spherical regions across poles and the antimeridian, but cells are not equal-area and spherical distance does not capture roads or barriers.
- **Hierarchical flexibility versus implementation complexity.** Variable-level cells support adaptive coverings, but storage queries must correctly handle ancestors, descendants, and 64-bit ID ordering.

## When to use it in a system design interview

- You need radius or region searches over drivers, couriers, profiles, listings, or restaurants without scanning the entire dataset.
- The service operates globally, including near the antimeridian or poles, and needs consistent spherical geometry.
- You need geographic rollups at several resolutions, such as neighborhood demand and broader regional supply.
- Queries cover irregular regions or variable radii, making hierarchical region coverings useful.
- You want geographic cache keys or partitions, and can separately address density skew and acceptable spatial approximation.

## How to bring it up in the interview

- Start with the query contract: radius search, nearest neighbors, polygon containment, or geographic aggregation. Explain that S2 supplies spatial indexing primitives, not the complete search or ranking system.
- Describe the full read path: construct a region, generate its covering, fetch candidates through a compatible index, apply exact filters, and rank. Interviewers will probe boundary cases and whether the covering can miss valid results.
- Choose cell resolution using expected density, search radius, candidate count, and lookup cost rather than naming a level without justification. Explain how you would measure those costs in dense and sparse regions.
- For moving entities, discuss versioned updates, stale-entry expiration, and cell transitions. Interviewers may ask whether delayed or reordered updates can remove a newer location or leave duplicate memberships.
- Separate spatial indexing from storage ownership and correctness. Explain how hot cells are distributed, and why finding a nearby driver still requires an independent atomic assignment step.

## Common mistakes

- Looking only in the query point's cell, or a fixed set of adjacent cells, without proving that they cover the requested radius.
- Treating the cell covering as the final answer instead of filtering candidates against the requested distance or polygon.
- Using mixed-level covering IDs as equality keys against a fixed-level index, which misses records stored under descendant cells.
- Assuming S2 cells have equal area or that sorting by cell ID produces nearest-neighbor order.
- Assuming S2 solves road-aware ETA, moving-object consistency, load balancing, or exclusive resource assignment.

## Interview questions where it comes up

- [Design a ride hailing app like Uber](https://sysround.com/questions/design-uber): S2 can index rapidly changing driver locations and generate nearby candidates before routing and exclusive assignment.
- [Design a food delivery app like DoorDash](https://sysround.com/questions/design-doordash): Spatial cell lookups help dispatch find nearby available couriers while location freshness and assignment remain separate concerns.
- [Design a dating app like Tinder](https://sysround.com/questions/design-tinder): S2 provides a geographic candidate index for radius-based discovery before exclusion, privacy, and ranking filters.
- [Design a restaurant review app like Yelp](https://sysround.com/questions/design-yelp): Nearby restaurant discovery needs spatial candidate retrieval followed by exact distance checks and relevance ranking.
- [Design Uber surge pricing](https://sysround.com/questions/design-surge-pricing): S2 cells can define spatial aggregation regions for demand and supply, with explicit handling of sparse data and boundary effects.
- [Design a weather app](https://sysround.com/questions/design-weather-app): S2 cells can group nearby weather reads for geographic cache reuse when cell resolution respects forecast accuracy requirements.
- [Design Facebook Marketplace](https://sysround.com/questions/design-facebook-marketplace): S2 supports nearby listing retrieval without scanning all listings, while exact distance filtering preserves search boundaries.

## FAQ

### What is an S2 cell?

An S2 cell is a region in a hierarchical grid on a sphere. Earth starts with six face cells, and each subdivision creates four children. A 64-bit cell ID identifies the cell and supports efficient hierarchy operations.

### How does S2 geometry compare with geohash and H3?

Geohash encodes latitude-longitude rectangles as prefixes, S2 uses a hierarchy of spherical quadrilateral cells, and H3 uses a mostly hexagonal grid with pentagons. S2 provides exact parent-child containment and spherical region operations, while H3 is often useful for neighborhood-based aggregation. Choose based on query shape, hierarchy requirements, and available database support rather than assuming one is universally faster.

### How do you find nearby points using S2 cells?

Cover the search region with S2 cells, retrieve indexed points contained in those cells, and filter them using the actual distance or containment predicate. Ensure the covering and storage index agree on levels or use descendant-range scans. For nearest-neighbor queries without a fixed radius, expand the search with a valid stopping rule rather than treating cell ID order as distance order.

## Related concepts

- [Geohash](https://sysround.com/concepts/geohash)
- [H3 hexagonal grid](https://sysround.com/concepts/h3)
- [Quadtree](https://sysround.com/concepts/quadtree)
- [Partitioning strategies](https://sysround.com/concepts/data-partitioning)


---
SysRound (https://sysround.com) is an AI practice tool for system design interviews: a voice or typed AI interviewer, a shared whiteboard, then feedback on every skill and a model answer. Its feedback is AI-generated and can be wrong.
