Open a maps or review app, tap "Restaurants near me", and a list sorted by distance appears almost at once. Behind that list is a proximity service: given a point and a radius, it returns the businesses inside the circle, nearest first. The hard part is the index. A database finds rows by ID or by a range of one value, but "everything within 2 km of this point" is a two-dimensional question.
This post designs a Yelp-style nearby search step by step: requirements and capacity, the API and data model, geohash, quadtrees, S2 and H3, PostGIS, and scaling the read path, with an architecture diagram you can copy.
Requirements and capacity
Functional:
- Return the businesses within a radius of the user's location, nearest first, one page at a time.
- Let business owners add, update and remove businesses.
- Show each business on its own detail page.
Non-functional:
- Fast, highly available search; reads far outnumber writes.
- New or moved businesses may appear in search the next day; confirm this with the product owner, because it shapes the design.
- User locations are personal data, so keep raw coordinates out of long-lived logs, including load balancer access logs that record the query string.
Assume 100 million businesses, 50 million daily users and five searches per user per day:
| Quantity | Calculation | Result |
|---|---|---|
| Searches per day | 50M users × 5 | 250 million |
| Average search rate | 250M ÷ 86,400 s | ≈ 2,900 per second |
| Peak search rate | 2 × average | ≈ 5,800 per second |
| Business updates | 1% of 100M per day ÷ 86,400 s | ≈ 12 per second |
| Geo index | 100M × (8-byte ID + 8-byte cell) | ≈ 1.6 GB raw per geohash length |
| Business rows | 100M × ~1 KB | ≈ 100 GB |
Two conclusions follow. Reads outnumber writes by roughly 250 to 1, and the geo index fits in the memory of one machine. So the design replicates the index instead of sharding it, and keeps business details in an ordinary database.
API and data model
GET /v1/search/nearby?lat=37.7800&lng=-122.4100&radius=2000&limit=20&cursor=...
GET /v1/businesses/{id}
POST /v1/businesses
PUT /v1/businesses/{id}
DELETE /v1/businesses/{id}
The search response stays small: business IDs, names, distances in meters and a cursor for the next page.
Two kinds of data sit behind it:
- The business table is the source of truth: name, address, category, hours, latitude and longitude.
- The geo index maps a location cell to business IDs. It is derived data that can always be rebuilt from the business table.
Why an ordinary index is not enough
A B-tree index on (lat, lng) narrows one range at a time. lat BETWEEN a AND b selects a band that circles the globe: for a 2 km radius, every business in a 4 km strip of latitude, worldwide. The longitude condition then filters that band row by row. Two separate indexes give two such bands, and intersecting them is slow at 100 million rows.
Spatial indexes solve this in one of two ways:
- Grids divide the world into cells with IDs that sort well, then index the cell ID like any other column: geohash, S2 and H3.
- Trees split space where the data is dense: quadtrees and R-trees, including PostGIS's GiST index.
Geohash: a grid you can index as text
Geohash, published by Gustavo Niemeyer in 2008, halves the longitude range, then the latitude range, and repeats, writing one bit per split. Every 5 bits become one character from a 32-character alphabet (digits and lowercase letters without a, i, l and o). Each extra character divides a cell into 32 smaller ones, so businesses that share a prefix share a cell. Sizes from the Elasticsearch geohash grid documentation:
| Geohash length | Cell at the equator |
|---|---|
| 4 | 39.1 km × 19.5 km |
| 5 | 4.9 km × 4.9 km |
| 6 | 1.2 km × 609.4 m |
| 7 | 152.9 m × 152.4 m |
Store each business's geohash, for example as a 6-character column with a B-tree index, or as a Redis set per cell. To search, compute the user's geohash at the length that fits the radius, then read that cell and its eight neighbors.
The neighbors are not optional: a user near a cell's edge can be meters from businesses in the next cell, and points on either side of the equator, the prime meridian or the 180° meridian can share no prefix at all.
Pick the longest geohash whose cell's shorter side is at least the radius. The user sits inside the center cell, so the block of nine cells extends at least one full cell in every direction and contains the whole circle. Cells get narrower toward the poles, so check the rule at the highest latitude you serve. If the nine cells hold too few results, drop one character: the cells grow 32-fold.
Redis builds on the same idea: GEOADD stores a 52-bit interleaved geohash as a sorted-set score, and GEOSEARCH checks the "1+8 areas" around the shape. Distances use the Haversine formula on a spherical Earth, which the docs say can be off by up to 0.5%.
Quadtrees: cells that follow density
A fixed grid treats a city center like the open ocean: one cell can hold thousands of businesses while another holds none. Quadtrees, which go back to Finkel and Bentley in 1974, adapt instead. In the variant used for nearby search, the root covers the whole map, and any cell with more than a set number of businesses, say 100, splits into four equal quadrants. Dense areas end up with deep, small cells; empty areas stay as one large leaf.
To search, walk from the root to the leaf that contains the user, collect businesses from that leaf and the leaves around it until you have enough, then sort them by exact distance.
With 100 million businesses and at most 100 per leaf, the tree has at least a million leaves holding about 2.4 GB of IDs and coordinates, so one server can keep it in memory.
The cost is operational: each server builds the tree in memory before it takes traffic, so gate it behind a readiness check, rebuild nightly and roll new trees out a few servers at a time.
S2 and H3: cells on a sphere
S2, from Google, projects the six faces of a cube onto the sphere and subdivides each face like a quadtree, in 31 levels. Each cell has a 64-bit ID that is its position along a Hilbert curve, so nearby IDs usually mean nearby cells. A circle is covered by a handful of cells at mixed levels, which become a few ID ranges to scan in any sorted store. A level-13 cell averages 1.27 km².
H3, from Uber, uses hexagons at 16 resolutions. Every neighbor of a hexagon sits at the same distance, and gridDisk returns all cells within k steps of a cell. Hexagons do not nest exactly, so H3 suits aggregation, such as demand per cell, more than exact containment. The ride-sharing system design applies these cells to moving drivers.
Choosing an index
| Index | Cell shape | Adapts to density | Stored as | Good fit |
|---|---|---|---|---|
| Geohash | Rectangles on a fixed grid | No | Text or integer column, Redis keys | Simple services, Redis GEO |
| Quadtree | Rectangles that split when full | Yes | In-memory tree | Read-heavy services with uneven density |
| S2 | Cells on cube faces, Hilbert order | Through mixed-level coverings | 64-bit integer | Range scans in key-value stores |
| H3 | Hexagons | No, one resolution at a time | 64-bit integer | Rings, aggregation and analytics |
| R-tree (PostGIS GiST) | Bounding boxes | Yes | Database index | Teams already running Postgres |
Using PostGIS instead of a custom index
For many products, the database is enough. PostGIS indexes geography columns with GiST, an R-tree built on PostgreSQL's generalized search tree. ST_DWithin takes a distance in meters and uses the index for its bounding-box check, and the <-> operator returns nearest neighbors from the index when it appears in ORDER BY:
CREATE TABLE business (
id bigint PRIMARY KEY,
name text NOT NULL,
location geography(Point, 4326) NOT NULL
);
CREATE INDEX business_location_gix ON business USING GIST (location);
-- The 20 nearest businesses within 2 km of the user
SELECT id, name,
ST_Distance(location, 'SRID=4326;POINT(-122.4100 37.7800)'::geography) AS meters
FROM business
WHERE ST_DWithin(location, 'SRID=4326;POINT(-122.4100 37.7800)'::geography, 2000)
ORDER BY location <-> 'SRID=4326;POINT(-122.4100 37.7800)'::geography
LIMIT 20;
Points are written longitude first, as in GEOADD; swapping them is a common bug. Run the query on read replicas and measure it with EXPLAIN ANALYZE on production-sized data before you build a separate index service.
Scaling the read path
- Keep the location-based service stateless, so it scales by adding instances behind the load balancer.
- Replicate the geo index, do not shard it. At about 1.6 GB per geohash length, or 6.4 GB for all four, every replica can hold all of it and answer each search on its own, without fanning out to every shard the way a sharded Elasticsearch index does. Build each nightly version under a new key prefix and switch readers over in one step, so no search sees half an index.
- Cache details by business ID. Cache-aside with invalidation on every edit keeps names and hours current; the caching strategies post compares the patterns.
- Cache results by cell, not by coordinates. A key such as cell, radius and category is shared by everyone nearby; exact coordinates almost never repeat.
- Scale the business table separately. Read replicas absorb detail lookups; shard by business ID only when one primary can no longer hold the data.
- Rank after filtering. Fetch more candidates than the page size, apply filters such as "open now", then sort by distance and rating.
Location data falls under privacy law in many places; the GDPR data mapping diagram shows how to trace where it goes.
The proximity service diagram
Diagram contents
- User app
- Business owner app
- Load balancer
- Location-based service
- Business service
- Geo index: geohash cell → IDs
- Business cache
- Business DB (primary)
- Read replicas
- Geo index builder
- GET /nearby
- PUT /businesses
- search
- CRUD
- 1. 9 cells → IDs
- 2. details by ID
- writes
- invalidate
- async replication
- nightly scan
- rebuild cells
- 3. on miss
How to read it:
- Blue, top: the user app calls
GET /nearby. The location-based service reads the IDs in nine geohash cells (1), then their details from the business cache (2), loading any misses from a read replica (3), filters by exact distance and sorts. - Green, bottom: owners edit businesses through the business service, which writes to the Postgres primary and invalidates the cached details.
- Orange, right: a nightly job scans a read replica and rebuilds the geo index, so new and moved businesses appear in search the next day.
- Load balancer: one entry point sends searches and edits to separate services that scale on their own.
- Notes at the bottom: the capacity estimate and the radius-to-geohash-length table.
Drawing proximity service diagrams clearly
- Separate the read and write paths and color each; the 250-to-1 ratio drives the design.
- Number the lookups on the read path: cells first, then details.
- Show the index as derived data, with the rebuild edge and its schedule: reviewers will ask how fresh results are.
- Put the numbers in a note: the capacity estimate and the cell size per radius decide whether nine cells are enough.
- Mark replicated and sharded stores, because they fail and grow differently.
Common mistakes are a single box called "Database" with no index, a sharded index that would fit in memory, coordinates in the wrong order and search without neighbor cells. For a general approach, see the system design diagram example.
Build it in Archboard
- Sign in with Google or GitHub and create a diagram.
- From the Network pack, add two Device nodes on the left: User app and Business owner app.
- Add a Cloud LB node from the Cloud pack, tall enough to span both rows, and name it Load balancer.
- Add two Compute nodes from the Cloud pack: Location-based service with a blue accent in the top row and Business service in green in the bottom row.
- From the Data pack, add two Redis nodes, Geo index and Business cache, and two Postgres nodes, Business DB (primary) and Read replicas.
- Add a third Compute node, Geo index builder, in orange above the replicas. Connect the replicas to it with a dashed "nightly scan" edge, and connect it to the geo index with "rebuild cells".
- Draw the blue read edges with numbered labels, including a dashed "3. on miss" edge to the read replicas, the green write edges and a dashed green "invalidate" edge to the cache.
- Add two Markdown blocks from the Core pack for the capacity and geohash tables, and two Core Text notes for the paths.
If you sketch systems in Mermaid first, the Mermaid converter turns a flowchart into a first draft. The example uses 12 diagram nodes; the Free plan allows 15 per diagram.
FAQ
What is a proximity service? A service that returns the places within a given distance of a point, usually nearest first. Maps, review and delivery apps use one for "near me" searches.
Should I use geohash or a quadtree? Geohash is simpler: a column or a Redis key per cell, rebuilt with one query. A quadtree adapts to density, so busy downtown cells stay small, but you build and serve it in memory. Start with geohash or PostGIS, and move from geohash to a quadtree when dense cells get too large.
Why search the eight neighboring cells? A user near the edge of a cell can be meters away from businesses in the next cell, which may have a different prefix. When the cell is at least as large as the radius, the cell and its eight neighbors always contain the whole search circle.
Do I need to shard the geo index? Usually not. With 100 million businesses, it takes about 1.6 GB raw per geohash length, which fits in memory, so replicate it to serve more reads. Shard the business table by ID when it outgrows one primary.
How fresh are nearby search results? As fresh as the index. With a nightly rebuild, new and moved businesses appear the next day, while detail edits show at once through cache invalidation. For instant updates with geohash, move the business ID between cell sets in the same request that writes the database.