InterviewDryRun
Lesson 17 · 22 min video · free

Design a Proximity Service

Open a maps app, type coffee, and see the best places near you in a fraction of a second. This lesson designs that nearby search: a read-heavy service over a few hundred million mostly static places, a geospatial index built from geohashes or cells, searching rings of neighbouring cells, ranking by distance, rating and relevance, and keeping the index fresh as businesses change.

What you will learn

  • Businesses rarely move: this is a read-heavy problem, very different from tracking moving drivers.
  • Separate the business service (writes, details) from the location service (search).
  • Geohash or hierarchical cells turn 2D search into lookups of a few cell keys.
  • Pick the cell size from the search radius, and always include neighbouring cells.
  • Quadtrees adapt to density, so a dense city and an empty desert get sensible cells.
  • The index is small enough to replicate everywhere; rebuild it nightly and apply changes incrementally.

In this lesson

  1. The question
  2. Step 1: Clarify the requirements
  3. Step 2: Back-of-the-envelope estimates
  4. Step 3: The API and the split
  5. Step 4: The data model
  6. Step 5: Why two-dimensional search is hard
  7. Step 6: Geohash
  8. Step 7: Quadtrees and hierarchical cells
  9. Step 8: The search itself
  10. Step 9: Ranking results
  11. Step 10: Keeping the index fresh
  12. Step 11: One search, end to end
  13. Step 12: Scaling and failures
  14. Step 13: Privacy and abuse
  15. Step 14: The follow-up questions
  16. Recap
Practice this question with Max

The question

Welcome to lesson seventeen of the InterviewDryRun system design course. Today we design a proximity service: the search that answers what is near me. Restaurants within a kilometre, petrol stations along my route, pharmacies open now.

In the previous lesson, we indexed drivers who move every few seconds. Today's data barely moves at all: a restaurant stays where it is for years. That one difference changes the design completely, and a good answer says so early. With static data, we can precompute, replicate and cache aggressively, and the challenge becomes answering a huge number of searches quickly and ranking the results well.

Max asks

“Design a service that returns nearby businesses for a location, like the search in a maps app.”

That is how Max, our AI interviewer, asks it. The core is a two-dimensional search: given a point and a radius, find the places inside. Databases are built for one-dimensional lookups, so the real question is how to turn a two-dimensional search into something an ordinary index can answer quickly. That is the idea at the centre of today's lesson.

The plan: requirements and numbers, the API, and a split into a business service and a location service. Then the geospatial index in depth: geohashes, quadtrees and hierarchical cells. Then the search algorithm, ranking, caching, updates, scaling and failures, and the follow-up questions.

Step 1: Clarify the requirements

Functional requirements
  1. 01
    Search nearbyA point, a radius, optional category and keyword
  2. 02
    Ranked resultsDistance, rating, relevance, open now
  3. 03
    Business detailsName, address, hours, photos, reviews
  4. 04
    Owners editAdd or update a business
  5. 05
    PaginationShow more results

Start with questions.

Users search with their location, a radius, which might be chosen automatically, and optionally a category like coffee or a keyword. Results come back ranked. Ask how: by distance alone, or by a mix of distance, rating and relevance? A mix is realistic, and we will design for it.

Users open a business to see details, and owners can add or update their business. Ask how quickly an update must be visible. A typical answer is: details like hours within minutes, and new businesses appearing in search by the next day is acceptable. That answer is very important, because it lets the search index be rebuilt in batches.

Non-functional requirements
  1. 01
    Low latencyResults in under 200 ms
  2. 02
    Read heavySearches vastly outnumber edits
  3. 03
    Highly availableStale results beat no results
  4. 04
    ScalablePeaks at lunchtime and evenings
  5. 05
    PrivateDo not keep users' precise locations longer than needed

The qualities. Fast results, a couple of hundred milliseconds. And extremely read heavy: millions of searches for every business edit. That ratio tells us to optimise the read path at the cost of a slower, more complex write path.

High availability: showing a restaurant that closed yesterday is a small problem; showing nothing is a big one. So we will accept eventual consistency for search.

And privacy: search requests contain users' precise locations, which are sensitive. Use them to answer the query, and do not log them at full precision longer than necessary. Interviewers increasingly appreciate this being mentioned.

Step 2: Back-of-the-envelope estimates

Sizing it
Businesses200 millionworldwide
Daily users100 million5 searches each
Searches500 million / dayabout 6,000 / s, 30,000 at peak
Location indexabout 10 GBid + lat + lng + cell per business
Business detailsabout 1 TB+text; photos in object storage
Editsabout 100 / stiny next to searches

Let us size it.

Say two hundred million businesses, and a hundred million daily users doing five searches each: five hundred million searches a day, around six thousand a second on average, and say thirty thousand at the peak. Business edits are tiny by comparison, perhaps a hundred a second.

Now the key number. The location index only needs, for each business, its id, latitude, longitude and maybe a cell id and a few ranking fields: about forty to fifty bytes. Two hundred million of those is around ten gigabytes. That fits in the memory of one server. So we can give every search server a full copy of the index, and scale reads simply by adding replicas.

The business details, names, descriptions, hours, reviews, are larger, perhaps a terabyte or more of text, plus photos in object storage. They live in an ordinary database with a cache, and are fetched only for the results we actually show.

Notice also that searches are very unevenly spread. A city centre at lunchtime gets thousands of searches a minute, a rural area almost none. Because every location server holds the whole index, uneven demand is not a problem for the index itself; it only affects which regional data centres need more replicas, which autoscaling handles.

Step 3: The API and the split

API
GET /v1/search/nearby?lat=12.9716&lng=77.5946
                     &radius=1000&category=coffee&open_now=true
                     &limit=20&cursor=...
→ { results: [ { id, name, distance, rating, open } ], nextCursor }

GET    /v1/businesses/{id}          → full details
POST   /v1/businesses               (owners)
PUT    /v1/businesses/{id}          (owners)

The API has two parts. A nearby search with a point, a radius in metres, filters like category and open now, and a page size. It returns a short summary for each result: id, name, distance, rating, open or closed. And business endpoints to read full details, and for owners to create or update their business.

Two services
searchdetailsrebuildCLIENTAppEDGEAPI gatewaySERVICELocation servicesearch, read onlyCACHEGeo indexin memory, replicatedSERVICEBusiness servicedetails, editsSTOREBusiness DBprimary + replicas

That API suggests a clean split into two services with very different workloads.

The location service does search. It is read only, stateless apart from its in-memory copy of the geo index, and handles thirty thousand searches a second by running many replicas.

The business service owns business data: details for display, and edits from owners. It uses a normal relational database with a primary for writes and read replicas, plus a cache for popular businesses.

And changes flow from the business database into the geo index asynchronously, by a nightly rebuild plus incremental updates. Search never waits on the business database. This separation lets each side scale on its own terms.

Step 4: The data model

Two stores, two shapes
StoreKeyHolds
business (relational)business_idname, address, lat, lng, category, hours, owner
reviewsbusiness_id, review_idrating, text, author
geo index entry (memory)cell idbusiness_id, lat, lng, category, hours bits, score
result cachecell, category, filtersranked ids, a few minutes

Let us make the data concrete. The business table is the source of truth: one row per business with its name, address, coordinates, category, opening hours and owner. It is relational, because owners edit it through forms with validation, and reviews and photos relate to it.

Reviews are a separate, much larger table, keyed by business. The average rating and review count are computed from it and copied onto the business row, updated asynchronously, because recomputing an average on every search would be wasteful.

The geo index holds a slimmed-down entry per business, grouped by cell: the business id, exact coordinates, category, a compact encoding of opening hours, and a precomputed quality score. Everything search needs to filter and rank is in this entry, so search never has to touch the business table until it shows the final page.

And a result cache for popular searches. Notice how the read path is designed backwards from the query: we decided what search needs, then built a structure that holds exactly that, in memory, in the order search wants it. That is the general technique for read-heavy systems, and it is worth naming.

Step 5: Why two-dimensional search is hard

The naive query
SELECT id FROM businesses
WHERE lat BETWEEN :lat - d AND :lat + d
  AND lng BETWEEN :lng - d AND :lng + d

index on lat finds a whole horizontal stripe of the planet
index on lng finds a whole vertical stripe
the database must intersect two huge sets

Before choosing an index, explain why the obvious query is slow, because interviewers often ask. The naive approach puts latitude and longitude in a table and searches a box: latitude between two values, and longitude between two values.

An index on latitude helps find a stripe of the planet with the right latitude, all the way around the world. An index on longitude finds a stripe from pole to pole. Each stripe may contain millions of businesses, and the database must intersect them to find the small box where they cross. Even a composite index on both only uses the first column efficiently. That is the fundamental problem: ordinary indexes sort data in one dimension.

So every geospatial index answers one question: how can we map two-dimensional positions into one-dimensional keys, so that points that are close on the map are usually close in the index? There are two families of answers: divide the map into a fixed grid of cells with nested names, like geohash or hierarchical cells, or divide it adaptively into a tree, like a quadtree. Let us look at each.

Step 6: Geohash

Geohash precision
LengthCell size, roughlyGood for radius
439 km x 20 km20 km
54.9 km x 4.9 km2 km
61.2 km x 0.6 km500 m to 1 km
7153 m x 153 m100 m

Geohash first, because it is simple and works in any key-value store. Split the world into two halves by longitude, then each half by latitude, and keep alternating, writing a bit for each split. Group the bits into characters of base thirty-two. The result is a short string, where every extra character means a smaller cell inside the previous one.

The useful property: places in the same cell share the same geohash prefix. So a four-character geohash is a cell roughly forty by twenty kilometres; six characters, about a kilometre by half a kilometre. To search within about a kilometre, compute the user's six-character geohash and find businesses with that prefix. That is a simple index lookup on a string column, or a key in a hash map.

But there is a trap you must mention. A user standing near the edge of a cell may be ten metres from a café in the next cell, which has a completely different geohash. Searching only the user's cell would miss it. The fix is always to search the user's cell and its eight neighbours, which together cover a square three cells wide. Neighbours can be computed directly from the geohash.

A second, rarer trap: cells next to each other can have very different prefixes, especially across the major dividing lines of the grid, like the equator. Computing neighbours properly, rather than assuming similar strings are close, handles that too. And because geohash cells are rectangles that get narrower towards the poles, cell sizes vary with latitude, which is a reason some teams prefer other cell systems.

Step 7: Quadtrees and hierarchical cells

A quadtree adapts to density
  1. 01
    Start with the whole mapOne square
  2. 02
    Split when crowdedMore than about 100 businesses: four children
  3. 03
    Dense cityMany levels, tiny cells
  4. 04
    Empty desertOne huge cell
  5. 05
    SearchWalk down to the leaf, then neighbouring leaves

A fixed grid has a problem: density. A six-character cell in a busy city centre might hold two thousand businesses, while the same cell in a desert holds none. A quadtree adapts. Start with the whole map as one square; whenever a square holds more than, say, a hundred businesses, split it into four children. Repeat.

In dense cities, the tree goes many levels deep, with tiny cells. In empty areas, cells stay huge. Every leaf holds a manageable number of businesses. To search, walk down to the leaf containing the user, then collect nearby leaves until we have enough results within the radius.

The quadtree for two hundred million businesses has a couple of million leaves, and the whole structure fits in a few gigabytes of memory, built in a few minutes. So each location server can build or load it at start-up. Updates are possible but fiddly, which is fine for data that changes slowly.

A third option, which many large mapping systems use, is a hierarchical cell system: the sphere is divided into cells at many levels, squares projected onto a cube or hexagons, each with a numeric id, where a parent cell's id is a prefix of its children's. It combines the simple key lookups of geohash with even cell sizes and easy neighbour finding. For the interview, explain geohash or quadtree well, and mention that hierarchical cells are the production-grade version of the same idea.

Which would I pick? For static businesses with huge variation in density, a quadtree in memory, or hierarchical cells, both work well. If the index must live in a plain key-value store or a database, geohash is the simplest. Say your choice and why; there is no single right answer, and interviewers mostly want to see that you understand the trade-off.

Step 9: Ranking results

What makes a result good
  1. 01
    DistanceCloser is better, but not everything
  2. 02
    QualityRating, number of reviews
  3. 03
    RelevanceHow well it matches the keyword or category
  4. 04
    ContextOpen now, price, time of day
  5. 05
    PersonalPast visits, preferences, if allowed

Sorting by distance alone gives poor results: the closest café might have terrible reviews, and a famous one three hundred metres further is what people want. So rank by a score that combines several signals.

Distance, with a diminishing penalty. Quality, from ratings and how many reviews back them up, so a single five-star review does not beat a thousand four-and-a-half star ones. Relevance to the keyword, from a text match on name, category and description. And context: open now, price level, time of day.

Personal signals can be added if the user allows. The structure is the same two-stage ranking we have seen before: the geo index gathers candidates cheaply, then a scoring function, simple weights at first and a learned model later, orders a few hundred of them. Store the static parts of the score, like quality, in the index entry, so ranking needs no extra lookups.

Keyword search deserves a sentence. If users type free text, like vegan brunch, the location service needs a text index too. A common approach is a search engine with geospatial filtering built in, partitioned by region. The geo index we designed remains the core, and the text match becomes one more filter and one more ranking signal.

Step 10: Keeping the index fresh

Updates
  1. 01
    Edits go to the business DBWith validation and moderation
  2. 02
    Change eventsPublished from the database's change stream
  3. 03
    Incremental applyLocation servers update in memory within minutes
  4. 04
    Nightly rebuildFresh index from scratch, swapped in atomically

Owners' edits go to the business service, which validates them, often with moderation, because fake listings are a real problem, and writes them to the business database.

Every committed change is published as an event, from the database's change stream. Location servers consume these events and update their in-memory index: move a business to a new cell, change its hours, remove a closed business. Within minutes, search reflects the change.

Incremental updates can drift over time through bugs or missed events, so also rebuild the whole index from the database every night, write it as a snapshot file, and have servers load it and swap it in atomically, as in the autocomplete lesson. The combination, nightly full rebuild plus incremental updates, gives freshness and a guaranteed clean state every day.

Because the index is about ten gigabytes, every location server holds a full copy. No sharding is needed for search at this size; we scale by adding replicas in every region. If the index grew much bigger, for example with more data per business, we would shard by region, since nearly all searches stay within one region.

Step 11: One search, end to end

Coffee near me, step by step
StepWhereTime
Request arrivesgateway, nearest regiona few ms
Pick cells: 6-char cell + 8 neighbourslocation servermicroseconds
Collect 340 candidates, filter to 120in memoryabout 1 ms
Exact distance, drop 30 outside circlein memoryunder 1 ms
Rank, take 20, build cursorin memoryabout 1 ms
Fetch 20 summariesbusiness cachea few ms

Let us follow one search through the system: a user in a busy neighbourhood opens the app and searches for coffee, open now, within a kilometre.

The request reaches the nearest region's gateway and goes to any location server. The server converts the point into its cell at the level for a one kilometre radius and computes the eight neighbouring cells. It collects about three hundred and forty businesses from those nine cells and filters them by category and open now using the compact fields in each entry, leaving a hundred and twenty.

It computes exact distances and drops the thirty that sit in the corners of the squares, outside the circle. It scores the remaining ninety with the ranking formula, sorts them, takes the top twenty and builds a cursor for the next page. All of this has taken a couple of milliseconds, entirely in memory.

Finally, it fetches display summaries for those twenty businesses from the business service's cache in a single batch, and returns. The whole request takes a few tens of milliseconds, most of it network. The business database itself was never touched. If ten other users nearby make the same search in the next minute, they get the cached ranked list and the whole thing is cheaper still.

Step 12: Scaling and failures

What breaks
  1. 01
    Lunch peakAutoscale stateless location replicas
  2. 02
    Hot areaCache ranked results per cell and category
  3. 03
    Bad snapshotValidate counts; roll back to yesterday's
  4. 04
    Business DB downSearch still works; details from cache

Traffic follows meal times in each time zone, so the location service autoscales, which is easy because its replicas are interchangeable. A new replica loads the latest snapshot file, applies recent change events, and joins.

Hot areas, like a city centre at lunchtime, get many identical queries. Cache ranked results per cell, category and filter set for a minute or two. Users in the same few hundred metres share the cached work.

A bad snapshot, say one missing half the businesses because a job read a partial table, would empty search results everywhere. Validate each snapshot before publishing: count businesses per region and compare with yesterday, and refuse to publish a big unexplained drop. Keep the previous snapshots to roll back instantly.

And if the business database is down, search keeps working from the in-memory index, and details are served from cache; owners' edits are paused. That is a graceful degradation story, and the separation of the two services is what makes it possible.

Step 13: Privacy and abuse

Protecting users and the index
  1. 01
    Coarse loggingRound locations in logs; drop them after analysis
  2. 02
    No location history by defaultSearch does not need to remember where you were
  3. 03
    Fake listingsVerify owners; detect duplicates and spam
  4. 04
    Review fraudWeight reviews by account trust

Two topics round off a strong answer. First, user privacy. Every search carries the user's precise location. Search needs it for a moment, but logs do not: round coordinates to a coarse cell before logging, keep raw locations out of analytics, and delete search logs after a set period. Search does not need to remember where someone was yesterday, so by default it should not.

Second, abuse of the index itself. Fake listings appear to capture searches, competitors post fake reviews, and businesses register many duplicate entries. Verify owners before a listing is promoted, detect near duplicate listings by name and location, and weight reviews by how trustworthy the reviewer's account looks. Ranking quality depends on the data being honest, so these checks are part of search quality, not an afterthought.

Both points cost little to mention, and they show the interviewer you think about the system as a product used by real people, not only as an index to make fast.

Step 14: The follow-up questions

Max asks

“How would you show businesses along a route, not around a point?”

Turn the route into a corridor: the set of cells within a few hundred metres of the path, computed by walking the route's line segments and collecting cells at a suitable level. Search those cells, rank by detour time rather than distance, and favour businesses ahead of the user rather than behind. The index stays the same; only the set of cells changes.

Max asks

“What changes if the businesses were moving, like food trucks?”

A few thousand moving trucks can use the ride matching approach from the previous lesson: an in-memory grid updated as locations arrive, kept separate from the static index, and merged into results at query time. The static index stays simple, and only the small moving set pays the cost of frequent updates.

Max asks

“How do you handle a search at the boundary between two regional shards?”

The search knows which cells it needs. If some of them belong to another shard, it queries that shard too, in parallel, and merges the results before ranking. With hierarchical cell ids, mapping cells to shards is a simple lookup. Searches near borders are a small fraction of traffic, so the extra call is cheap.

Max asks

“How would you make sure new businesses show up in search within minutes instead of by tomorrow?”

The incremental path already makes that possible: when a new business passes moderation, its change event reaches every location server within a minute or two, and each server inserts it into the right cell of its in-memory index. The nightly rebuild then makes sure nothing was missed. The real delay is usually moderation, not the system, so the honest answer is to decide how much checking a new listing needs before it is shown.

Recap

Your 45 minutes
  1. 01
    0 to 5: requirementsNearby, ranked, fast; edits visible by tomorrow
  2. 02
    5 to 10: estimates30,000 searches a second; index about 10 GB
  3. 03
    10 to 15: API and splitLocation service for search, business service for data
  4. 04
    15 to 30: the indexWhy lat-lng indexes fail; geohash, quadtree, cells; neighbours
  5. 05
    30 to 45: search and opsRanking, caching, rebuild plus incremental, failures

On the clock: five minutes of requirements, including the key question of how fresh search must be. Five minutes of numbers, showing a read-heavy system whose index fits in one server's memory.

Five minutes on the API and the split into a search service and a business service.

Fifteen minutes on the index: why two-dimensional search defeats ordinary indexes, geohash with neighbouring cells, quadtrees for uneven density, and hierarchical cells. And fifteen on the search algorithm, ranking, caching, updates and failures. If you can explain the neighbour-cell trap and the density problem, you have shown real understanding of geospatial search.

Geohashes and quadtrees are easy to name and harder to explain clearly while drawing. Practicing out loud is how you make that explanation crisp. You can practice this exact question with Max, our AI interviewer, at interview dry run dot com. It is free to start, and you get a scored report with what to fix. The written lesson, with every diagram, is on the site too. See you in lesson eighteen.

Now say it out loud

Watching an answer is not the same as giving one. Max asks this exact question, pushes back when an answer is vague and keeps time, then scores you per skill.

Practice with Max

Free: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.