System designDeep dives8 min read

Search and Geospatial Indexes in Depth

This lesson is for software engineers facing designs with a search box or a "near me" feature: product search, restaurant discovery, ride matching, local listings. A regular database index cannot answer "dishes matching spicy ramen" or "drivers within 3 km" efficiently, and interviewers know it. By the end you will be able to explain how an inverted index and a geospatial index work, keep a search index in sync with your database, and size a "find nearby" feature with numbers.

Choosing and Scaling a Database introduces the search index as a secondary store. This lesson opens it up.

How this comes up in the interview

Search and location usually arrive as a deep dive after the high-level design:

  • "How does search actually find matching items? How are results ranked?"

  • "A seller updates a listing. How long until search shows it?"

  • "How do you find the closest drivers without scanning all of them?"

  • "What happens in a dense city versus the countryside?"

They score on deep dive and scalability and trade-offs. Naming a tool is not enough; the interviewer wants the mechanism and its costs.

Full-text search: the inverted index

A B-tree index on a title column helps with exact matches and prefixes (LIKE 'ramen%'), but not with "find titles that contain ramen anywhere". That would scan every row.

An inverted index flips the relationship: for every term, it stores the list of documents that contain it (the posting list), often with the positions and counts of the term in each.

"spicy"  -> [doc 4, doc 17, doc 230]
"ramen"  -> [doc 17, doc 52, doc 230, doc 901]

A query for "spicy ramen" reads two posting lists and intersects them: documents 17 and 230. Posting lists are kept sorted by document id, so intersection is a linear merge, and the cost depends on the lengths of the lists, not the size of the whole collection.

Tokenization decides what matches

Before indexing, text goes through an analyzer: split into tokens, lowercase, often remove very common words, and reduce words to a stem so "noodles" matches "noodle". The same analyzer must run on the query, or the terms will not line up. Analyzers are also where language support lives: splitting words in Japanese or Thai, or handling accents, is an analyzer choice. If the interviewer asks about typos, the answer is fuzzy matching (terms within a small edit distance) or indexing character n-grams, both of which make the index larger.

Ranking basics

Matching finds candidates; ranking orders them. The standard text score, BM25, rewards three things:

  • Term frequency: a document that mentions "ramen" more often scores higher, with diminishing returns so repetition cannot game it.

  • Inverse document frequency: rare terms count more than common ones. Matching "tonkotsu" says more than matching "noodles".

  • Length normalization: a match in a short title counts more than the same match buried in a long description.

Real products blend the text score with business signals: rating, distance, popularity, freshness, whether the restaurant is open now. Say that ranking is usually two stages: retrieve a few hundred candidates cheaply by text match and filters, then re-rank those with the richer, more expensive signals.

Scaling the index

A search index is split into shards by document. A query goes to every shard, each returns its top results, and a coordinator merges them (scatter-gather). That means the query is only as fast as the slowest shard, so keep shards evenly sized and add replicas to serve more queries per second. Shard to fit data; replicate to fit traffic.

Keeping the index in sync

The primary database is the source of truth; the search index is a copy built for reading. How it stays current is a favorite follow-up.

Dual writes (the service writes to the database, then to the index) look simple and fail quietly. If the index write fails or the service crashes in between, the two disagree and nothing repairs it. If two updates race, the index can end up with the older one.

Change data capture (CDC) reads the database's own change log (the write-ahead log or binlog) and streams every committed change to an indexer, usually through an event stream. Every committed change is captured in commit order, nothing depends on the application remembering a second write, and the indexer can be replayed. The cost is lag: search is typically seconds behind the database. The queues and streams lesson covers the stream side.

Two details that score:

  • Seconds of lag is usually acceptable for search, but not for the person who just made the edit. Read their own listing from the database on their own pages, so they never see the stale copy.

  • Full reindex without downtime: build a new index in the background from a snapshot plus the change stream, then switch an alias from the old index to the new one. You will need this whenever the analyzer or mapping changes.

Typeahead

Suggestions while typing look like search but are a design problem of their own, with a request on almost every keystroke and a latency budget measured in tens of milliseconds. From the search side, two tools matter: index edge n-grams (r, ra, ram, rame, ramen) so the engine can match partial words when the user is searching the catalog itself, and have the client wait for a short pause in typing and cancel requests that are out of date. How to build a dedicated suggestion service at scale is worth practicing as its own interview rather than as a footnote to search.

Geospatial: finding things nearby

"Drivers within 3 km" is a two-dimensional range query, and a normal index sorts by one value at a time. An index on latitude finds a horizontal band of the whole world, which does not help. Geospatial indexes turn two dimensions into something you can search efficiently.

Geohash

A geohash divides the world into a grid and gives each cell a string. Each extra character splits the cell into 32 smaller ones, and nearby points usually share a prefix. Approximate cell sizes at the equator (cells get narrower east to west toward the poles):

  • 5 characters: about 4.9 km by 4.9 km

  • 6 characters: about 1.2 km by 0.61 km

  • 7 characters: about 153 m by 153 m

Because a cell is a string prefix, an ordinary sorted index or key-value store can answer "everything in this cell" as a prefix range scan. That is the main appeal: no special database needed.

The catch is edges. Two points a few meters apart can sit on opposite sides of a cell boundary with different prefixes. The fix is standard: query the target cell and its 8 neighbors, then compute the exact distance for each candidate and drop those outside the radius.

Quadtrees

A quadtree starts with one square covering the map and splits any square holding more than a set number of points (say 100) into four, recursively. Dense downtown areas end up with many small cells and rural areas with a few large ones, so each cell holds a similar number of points. It is usually kept in memory, and it suits data that changes slowly, such as restaurants or stores. For points that move every few seconds, constantly moving entries between cells and splitting or merging them makes a geohash grid simpler.

Other options worth naming: R-tree indexes in databases such as PostGIS, and hierarchical cell systems like S2 or H3. They solve the same problem with better-shaped cells.

Worked example: nearby drivers

Prompt: "In a ride-hailing app, find the closest available drivers to a rider. There are 500,000 active drivers, and each sends its location every 4 seconds."

A weak answer: "Store driver locations in the database and query by latitude and longitude ranges." That writes 125,000 updates per second (500,000 / 4) to the primary database and the range query still scans a band of the world.

A strong answer:

  1. Separate the fast-changing data. Driver locations are high-volume, short-lived and only useful for seconds. Keep them in an in-memory geospatial index (for example Redis geo commands, which store geohash-encoded positions in a sorted set), not in the primary database. Persist trips, not pings.

  2. Shard by city or region. A rider in Lisbon never needs drivers in Seoul, so each region's index is independent and the 125,000 updates per second spread across them.

  3. Query. For a 3 km radius, take the rider's 5-character geohash cell plus its 8 neighbors. Each cell is about 4.9 km tall, and about 4.9 km wide at the equator, so the nine cells extend well past 3 km from the rider in every direction. East-west width shrinks with latitude (about 3.8 km at Lisbon, about 2.4 km at Helsinki), and once it drops below 3 km, at about 52 degrees latitude, add the next ring of cells or use a finer grid with more cells. Redis GEOSEARCH handles this cell selection for you. Fetch candidates, compute exact distances, filter by availability, sort, return the top few.

  4. Freshness. A location older than, say, 15 seconds is treated as stale and the driver dropped from results, so a phone that lost signal does not get matched.

  5. Trade-off to name. Straight-line distance is not driving time. Rank the top candidates by an ETA from a routing service, which is too expensive to call for every driver but fine for the closest ten.

Worked example: restaurant search

Prompt: "Users search restaurants and dishes by text, filtered to those delivering to them, ranked by relevance and distance. 1 million restaurants."

At about 2 KB per restaurant document (name, cuisine, dish names, location, rating, hours), the index is about 2 GB: one shard holds it, and you add replicas for query volume rather than more shards. Each document carries a geo field, so one query combines text match on "spicy ramen", a filter "within 5 km and open now", and a ranking that blends BM25 with distance and rating. Restaurant and menu edits flow from the primary database through CDC, so a price change appears in search within seconds, while the restaurant owner sees their own edits from the database immediately.

Mistakes that cost points

  • Using LIKE '%term%' on the primary database. It scans every row; propose a search index and say why.

  • Dual writes to keep the index in sync. Name CDC or the outbox pattern, and the lag it implies.

  • Forgetting cell edges. Always query the neighbors and filter by exact distance.

  • Writing every location ping to the main database. Keep moving positions in memory, sharded by region.

  • One ranking signal. Text relevance alone rarely matches what users want; say how you blend in distance, rating or freshness.

Practice it

Spend ten minutes sketching "find coffee shops within 1 km" twice: once with a geohash grid and once with a quadtree, and write down when you would pick each. Then practice deep dives where search and indexing come up:

Practise this in a mock interview

Try what this lesson covers out loud: the AI interviewer asks one of these questions, follows up, and scores your answer.

Read next

  • How to Run a Deep Dive in a System Design Interview

    Pick the riskiest part of your design and work through it in five steps (numbers, options, trade-off, decision, failure mode), with a chat message fan-out as the worked example.

    9 min read

  • Choosing and Scaling a Database

    Choose a database from the data's access patterns, explain how indexes, replicas and shards change performance and what each costs, and walk through two storage decisions with numbers.

    8 min read

  • Caching in Depth

    Place a cache, choose its read and write pattern, TTL and eviction, handle stampedes, hot keys and lookups for missing keys, and calculate how much load it takes off the database.

    8 min read

  • Load Balancing in Depth

    Choose between Layer 4 and Layer 7, match the algorithm to the traffic, design health checks, drain long-lived connections, remove the load balancer as a single point of failure, and route users across regions.

    8 min read