Search, feeds and geo building blocks
Foundations F16. The parts inside Twitter, Swiggy search, typeahead and "find nearby": the inverted index and text analysis, BM25 and two-stage ranking, vector and hybrid search with HNSW and reciprocal rank fusion, scaling a search cluster with shards, replicas and refresh, typeahead with precomputed top-k per prefix, feed fan-out on write vs read, assembling and paging a feed with cursors, and geo indexes (geohash, S2, H3, quadtrees). Each idea is told as a story you'll remember, with a lab that shows when push, pull or hybrid fan-out breaks.
Start here
Three building blocks turn up inside half the classic problems: search (find the documents that match these words, best first), feeds (show each user the newest or best posts from the accounts they follow) and geo (what is near this point). Interviewers rarely ask "explain an inverted index" on its own. They ask you to design Twitter, Swiggy search, typeahead or "find nearby drivers", and listen for whether you know the data structure underneath and its cost.
This page covers eight ideas: the inverted index; ranking with BM25 and the two-stage candidates-then-ranker pattern; vector and hybrid search; scaling a search cluster; typeahead; feed fan-out on write vs read; assembling and paging a feed; and geo indexes (geohash, S2, H3, quadtrees). They belong together because they share one trick: do work ahead of time so a query touches a tiny slice of the data, and one trade-off: the more you precompute, the more each write costs and the staler the answer can be.
Deep dives into one product (news feed, typeahead, proximity service) come in the Classics track; this page gives you the parts they are built from.
Shaadi-season shopping in Chandni Chowk
A family from Lucknow has one Saturday in Old Delhi to buy everything for a wedding: lehengas, bangles, silver payals, dry fruits, a sherwani, puja items. Chandni Chowk is a maze of specialised lanes, and the family has a cousin, Imran, who grew up there. Everything on this page happens on that one day:
- Imran's notebook: for every item, which lanes sell it. (inverted index)
- Which payal shop first, and how he shortlists before Bua ji judges. (ranking: BM25 and two stages)
- Dadi asking for "that red thread they tie at the puja" without knowing its name. (vector and hybrid search)
- The market association's register, copied at every gate and split by lane. (scaling search)
- The paan-wala who has your order ready after two words. (typeahead)
- The wedding card sent to every guest, and the notice on the temple board. (feed fan-out)
- Scrolling back through the family WhatsApp group for the lehenga photos. (assembling and paging a feed)
- PIN codes, and the parking lot across the road that's in a different one. (geo indexes)
The market and the family are a teaching story; the companies, papers, docs and numbers cited on this page are real.
The inverted index: word → documents
An inverted index maps each word to the list of documents that contain it, so a search reads a few short lists instead of every document; the text is normalised the same way when indexing and when searching, or nothing matches.
Imran's notebook
Chandni Chowk has hundreds of lanes and thousands of shops. Walking every lane asking "do you sell silver payals?" would take a week.
Imran's notebook is organised the other way round. One page per item: "payal → Dariba Kalan shops 12, 18, 40", "bangles → Kinari Bazaar 3, 7, 22", "dry fruits → Khari Baoli 5, 9". To find shops that sell both bangles and bindis, he lays the two pages side by side and picks the shop numbers on both.
He also writes "chudi", "choodi" and "bangles" on the same page, because the family will use all three words. If he filed them separately, Mausi's "choodi" would find nothing.
- Forward index: document → its words (what a database row is). Inverted index: word (term) → a sorted postings list of document IDs, often with positions and counts.
- Analysis turns text into terms, the same way at index time and query time: split into words (tokenise), lowercase, drop accents, maybe stem ("running" → "run"), add synonyms. Mismatched analysis is the classic "why doesn't it match" bug.
- Queries become list operations: AND = intersect postings lists, OR = union, phrase = check positions. Lists are sorted, so intersection is a fast merge, and the rarest term's list is walked first.
- Why a normal index doesn't do this: a B-tree on a text column helps "starts with", but `LIKE '%payal%'` can't use it and scans every row.
- Write path: search engines like Lucene (inside Elasticsearch and OpenSearch) buffer new documents, write small immutable segments (each its own little inverted index), and merge segments in the background. Deletes are marks, cleaned up at merge time.
Elasticsearch's docs (8.19, checked Oct 2026) describe a Lucene segment as "similar to an inverted index": new documents are written into a new segment in the filesystem cache, and only then become searchable (the refresh, covered in "Scaling search" below).
PostgreSQL ships a full-text type and a GIN (inverted) index, so a small product with "search the help articles" can stay on its database; a dedicated engine earns its place when you need relevance tuning, typo tolerance, facets and many millions of documents at high query rates.
- Richer analysis (stemming, synonyms, n-grams for typos) finds more matches but makes the index bigger and can match things users didn't mean; tune per field (exact for SKUs and IDs, analysed for titles and descriptions).
- Immutable segments make writes and caching simple but mean updates are delete + re-add, and many small segments slow searches until merges catch up.
Search runs on an inverted index: each term maps to a sorted list of document IDs. The query is analysed the same way as the documents (lowercase, stemming, synonyms), then we intersect the postings lists, rarest term first. I'd put that in Elasticsearch or OpenSearch, not a LIKE query on the database.
"We'll run a LIKE '%term%' query on the products table." That scans every row on every keystroke, and it can't rank, handle plurals or typos.
Ranking: BM25, then two stages
Matching finds candidates; ranking orders them: BM25 scores a document higher when it contains the query's rarer words, more often, in a shorter text, and large systems rank in two stages: a cheap step picks a few hundred or thousand candidates, then an expensive model orders only those.
Which payal shop first, and the two-step shortlist
In Dariba Kalan, forty shops mention silver. Imran's rule of thumb for "silver payal":
- "Payal" matters more than "silver", because almost every shop in this lane says silver; few say payal. Rare words tell you more.
- A shop whose board says "payal" three times is more likely a payal specialist than one that says it once, but the tenth mention doesn't add much.
- A small shop with "SILVER PAYAL" on its board beats a big store that lists payal once among two hundred items.
Then the shortlist. Imran can walk past forty shops in ten minutes and pick eight that look right. Bua ji then spends half an hour in each of those eight: weight, polish, the price per gram. She never inspects all forty; she couldn't. A cheap, wide first pass, then a slow, careful second one.
BM25 is the standard text-relevance score (Lucene's and Elasticsearch's default). Per query term it multiplies:
- IDF: how rare the term is across all documents (rare terms count more).
- Term frequency with saturation: more occurrences help, with diminishing returns (parameter k1).
- Length normalisation: the same count in a shorter document counts more (parameter b).
Two-stage (or multi-stage) ranking is how search, feeds and recommendations all work at scale:
- Candidate generation (retrieval): cheap and wide. Inverted index + BM25, "posts from people you follow", nearest neighbours in an embedding space. Millions → hundreds or thousands.
- Ranking: an expensive model (gradient-boosted trees, a neural net) scores only those candidates with many features: your history, freshness, popularity, price.
- Re-ranking and rules: diversity, de-duplication, business rules, ads, filters for blocked or unsafe content.
Ranking quality is measured offline (NDCG, recall@k on labelled queries) and confirmed online with A/B tests on clicks, purchases or watch time.
Elasticsearch's similarity docs (7.17) list BM25 as the default with k1 = 1.2 and b = 0.75.
YouTube's 2016 RecSys paper (Covington, Adams, Sargin) describes "a deep candidate generation model" followed by "a separate deep ranking model". Twitter's 2023 write-up of its open-sourced home timeline says each request draws about 1,500 candidates from a pool of hundreds of millions of posts, about half from accounts you follow; a ~48M-parameter neural network ranks them; and the pipeline runs about 5 billion times a day, finishing in about 1.5 seconds on average.
- More candidates improve recall but cost ranking time linearly; the first stage must be good enough that the best items are in the shortlist at all.
- A learned ranker beats BM25 on engagement but needs labelled data, features served at query time, and monitoring for drift; BM25 needs none of that and is a strong baseline.
Ranking is two stages. Retrieval pulls about a thousand candidates cheaply: BM25 from the inverted index plus nearest neighbours from embeddings. A learned model then scores just those with user and item features, and a last pass applies filters, diversity and business rules. We judge it offline with NDCG and online with A/B tests.
Sorting by a single "popularity" column, or running the heavy model over the whole catalogue per query. Say how many candidates each stage sees and why that fits the latency budget.
Vector and hybrid search
Vector search turns text, images or users into embeddings and finds the nearest ones, so it matches meaning rather than words; real systems use approximate indexes (HNSW) that trade a little recall for speed, and combine vector results with keyword results (hybrid search) because each misses what the other finds.
Dadi and the red thread
Dadi wants "that red-and-yellow thread they tie on your wrist at the puja". No board in the market says that. Imran's notebook, organised by words, finds nothing.
The old shopkeeper at the puja-items stall understands at once: she means kalava (mauli). He matches what she means, not the words she used.
An hour later, Phupha ji asks for "Raymond suiting, shade 4471". Here the shopkeeper's "something similar" is useless: he wants that exact code. Imran's word notebook finds it instantly.
The family needs both: one helper who understands meaning, one who matches exact words, and someone who merges their suggestions.
- Embeddings: a model maps each item (and each query) to a vector of a few hundred numbers, so that similar meanings land close together. Search = find the k vectors nearest to the query vector (cosine or dot-product similarity).
- Exact vs approximate: comparing against every vector is exact but linear in the data. ANN indexes answer much faster with slightly imperfect recall:
- HNSW: a layered graph; search starts in a sparse top layer and greedily walks closer. Fast, high recall, memory-hungry, slower to build.
- IVF: cluster the vectors, search only the nearest few clusters. Cheaper memory, often paired with quantisation (compressing vectors).
- Knobs: a bigger search list (ef_search in HNSW) means higher recall and more latency; measure recall against exact search on a sample.
- Hybrid search: run keyword (BM25) and vector retrieval side by side and merge. Reciprocal rank fusion (RRF) adds 1 ÷ (k + rank) from each list, so it needs no score calibration between the two.
- Operational facts: query and documents must be embedded by the same model; changing the model means re-embedding everything; filters (category, in-stock, tenant) must be applied inside the ANN search or results come back empty.
The HNSW paper (Malkov and Yashunin, arXiv 2016, later IEEE TPAMI) shows that starting from the top layer "allows a logarithmic complexity scaling".
pgvector's docs (v0.8.7, checked Oct 2026) say that "by default, pgvector performs exact nearest neighbor search, which provides perfect recall", that approximate indexes trade "some recall for speed", that HNSW has a better speed-recall trade-off than IVFFlat at the cost of build time and memory, and that hnsw.ef_search defaults to 40.
Elasticsearch's RRF docs give the score as 1 ÷ (k + rank) summed over result lists, with rank_constant k defaulting to 60.
- Vector search finds paraphrases and works across languages and images, but misses exact tokens (SKUs, error codes, names) and is hard to explain; keyword search is the opposite. Hybrid costs two retrievals per query.
- ANN indexes hold vectors in RAM: 100M vectors × 768 dimensions × 4 bytes ≈ 300 GB before graph links, so quantisation, sharding or disk-based indexes come up at scale.
For meaning-based queries I'd embed documents and queries with the same model and use an HNSW index, tuned until recall against exact search is about 95% at our latency budget. Product codes and names still need keyword search, so retrieval is hybrid: BM25 and vectors in parallel, merged with reciprocal rank fusion, then the usual ranker.
"Replace Elasticsearch with a vector database." Pure vector search fails on exact identifiers and filters; and calling ANN results "the nearest neighbours" without mentioning recall hides the trade-off.
Scaling search: shards, replicas and refresh
A search cluster splits the index into shards (each query asks every shard and merges the top results: scatter-gather) and copies each shard to replicas for read throughput and failover; the index is derived data fed from the database, and new documents become searchable after a refresh, not instantly.
The register at every gate
The market association keeps the official register of every shop. One copy at one gate means a queue of a thousand shoppers, so:
- Split by lane group: one clerk keeps the register for Kinari Bazaar and Dariba, another for Khari Baoli and Nai Sarak. Each register is thin enough to search quickly.
- Copies at every gate: each section's register is copied to three gates, so more people can ask at once, and a closed gate doesn't lose a section.
- Ask everyone, merge the best: "who sells silver payals?" goes to every section's clerk; each sends back their best five; the head clerk merges them into one top five.
The register isn't where shops are licensed: that's the municipal office, the source of truth. The association copies new licences into the register every evening, so a shop that opened this morning isn't in it until tonight.
- Shards (partitions of the index): usually split by document (each shard holds all terms for its documents). Every query goes to every shard (scatter), each returns its top k, and a coordinator merges them (gather). Latency is set by the slowest shard, so tail latency matters (see the scaling page).
- Replicas: copies of each shard on other nodes. They add read throughput and survive node loss; they don't make the index bigger per node.
- Shard count is a trade-off: too few and shards are huge and slow to recover; too many and every query pays per-shard overhead. Route by tenant or region when queries naturally stay inside one.
- Near real-time: new documents become searchable after a refresh opens a new segment, typically about a second later. Read-your-own-write in search needs a refresh or reading the database directly.
- The index is derived data: write to the database first, then feed the search index from a change stream (CDC or an outbox + queue). If the index is lost or the mapping changes, rebuild it from the source into a new index and switch an alias.
Elasticsearch's sizing guide (checked Oct 2026) says "aim for shards of up to 200M documents, or with sizes between 10GB and 50GB", that each shard's search runs on one thread, and that "searching a thousand 50MB shards will be substantially more expensive" than one 50 GB shard.
Its near-real-time docs say it "periodically refreshes indices every second, but only on indices that have received one search request or more in the last 30 seconds".
A 2013 summary of Twitter's QCon talk (third party, High Scalability) describes its search as scatter-gather across the cluster with reads "on the order of 100 msecs".
- A shorter refresh interval makes new documents visible sooner but creates more small segments and more merge work; bulk loads often turn refresh off and back on.
- Feeding the index asynchronously keeps writes fast and the database the source of truth, at the price of a short window where search is stale; dual-writing from the app is simpler but drifts out of sync on partial failures.
The product database is the source of truth; changes flow through CDC into Kafka and an indexer writes to Elasticsearch, so search lags by a second or two. The index is split into shards of a few tens of GB, two replicas each; queries scatter to all shards and merge top-k. If the mapping changes, we reindex into a new index from the source and flip an alias.
Treating the search index as the primary store, or promising that a product appears in search "immediately" after it's saved. Say it's derived, eventually consistent, and rebuildable.
Typeahead: answers before you finish typing
Typeahead must answer each keystroke in tens of milliseconds, so it doesn't search at query time: it precomputes the top suggestions for every prefix in an in-memory structure (a trie or FST), refreshes them from query logs offline, and layers a little personalisation and caching on top.
The paan-wala who finishes your order
At the corner paan shop, Chacha hears "meetha..." and his hands are already folding a meetha paan. "Banarasi..." and the Banarasi tin is open.
He isn't thinking through all two hundred paans he could make. Years of orders have taught him the few most likely endings for each opening, and those sit in his head, ready. If he paused to consider everything, the queue behind you would leave.
He also knows the regulars: for Sharma ji, "meetha" means meetha with no supari. And on a wedding day, when everyone suddenly wants "fire paan", it takes him a day or two to start offering it first.
- Budget: users type a key every 100–200 ms, so a suggestion must arrive within tens of milliseconds or it shows up stale. Debounce on the client (wait ~50–100 ms after typing stops) and cancel outdated requests.
- Data structure: a trie (or a compact FST) keyed by prefix, where each node stores its top-k completions precomputed. A lookup is just a walk down the prefix: no sorting at query time.
- Building it: aggregate query logs (and catalogue titles) offline, score by frequency with time decay, filter offensive or zero-result queries, and rebuild periodically (hourly or daily); a small fast path can add trending queries sooner.
- Serving: the structure fits in memory; replicate it widely, shard by prefix if huge, and cache popular short prefixes at the edge or in the client.
- Personalisation: blend the global top-k with the user's recent searches and context, in a light re-rank on top.
- Typos and Indian languages: fuzzy matching (edit distance 1–2) and transliteration ("chudi" vs "चूड़ी") add recall at a cost in latency.
Facebook's 2010 post "The life of a typeahead query" (Keith Adams) says "spending more than 100 msec to retrieve a result will cause the typeahead to 'stutter'", and describes prefetching each user's friends, pages and groups into the browser cache when the search box is focused, so many queries are answered locally.
Flipkart's Fifth Elephant 2020 talk on context-aware autocomplete describes ranking over 5 million documents at 10K QPS with a latency requirement under 20 ms, and notes users mainly see the top 3–4 suggestions.
Elastic's 2013 post on its completion suggester stores suggestions in an in-memory FST; on 2.1 million Wikipedia titles a completion took about 0.5–0.7 ms on a laptop.
- Precomputed top-k is fast but stale between rebuilds; a streaming path for trending terms adds freshness at the cost of a second pipeline and more abuse risk.
- Per-user personalisation helps relevance but multiplies cache keys; keep the global trie shared and personalise with a small re-rank.
Typeahead never runs a full search per keystroke. An offline job aggregates query logs into a trie where each prefix node holds its top 10 completions; it's rebuilt hourly and served from memory on replicated nodes, with popular prefixes cached at the edge. The client debounces and cancels stale calls, and we re-rank the top results with the user's recent searches. Target: under 50 ms server time.
Hitting the main search index with a prefix query on every keystroke, or forgetting to filter offensive and zero-result suggestions out of the logs before they're shown.
Feeds: fan-out on write vs fan-out on read
A home feed is built either when someone posts (push: copy the post ID into every follower's timeline, so reading is one lookup) or when someone opens the app (pull: read everyone you follow and merge); big networks push for normal accounts and pull for the few with millions of followers.
Wedding cards and the temple notice board
The family sends a printed card to each of its 300 guests. It's work up front (300 envelopes), but every guest has the news in their hand and doesn't need to go looking. That's push.
The temple doesn't post a card to every devotee when it changes the aarti time. It pins a notice on its board, and each devotee reads it when they visit. Nothing to send, but every visitor has to go and check every board they care about. That's pull.
Now imagine a film star's wedding with two crore fans. Printing two crore cards would take weeks, and the last fan would hear long after the wedding. So the star's family does what the temple does: one announcement, and fans check it themselves. Everyone else in town still sends cards.
Fan-out on write (push)
- When a user posts, a worker reads their follower list and inserts the post ID into each follower's timeline (a capped list in Redis or similar, newest first).
- Reading the feed = one read of your own timeline, then fetch the posts by ID.
- Cost: writes × followers. A celebrity post is millions of inserts, so it arrives late and delays everyone else's posts.
Fan-out on read (pull)
- Posts are stored once, per author. Opening the feed reads the recent posts of everyone you follow and merges them (a scatter-gather).
- Cost: reads × accounts followed, on every open; latency is set by the slowest of those reads. Writes are trivial and the feed is always fresh.
Hybrid, the usual answer at scale:
- Push for normal accounts; pull for accounts above a follower threshold, merged in at read time.
- Push only to followers active recently; rebuild an inactive user's timeline on their next login.
- Timelines hold IDs, not content, capped at a few hundred entries, so edits and deletes don't have to touch millions of timelines.
A 2013 write-up of Twitter's "Timelines at Scale" QCon talk by Raffi Krikorian (third party, High Scalability) gives 150 million active users, about 300K reads/s for timelines against about 6,000 writes/s, 30 billion timeline deliveries a day, home timelines capped at 800 entries and "replicated 3 times" in Redis, a target of delivering a tweet in under 5 seconds, and that a tweet to Lady Gaga's 31 million followers "can take up to 5 minutes", which is why very large accounts were to be merged in "at read time".
LinkedIn went the other way: its 2016 FollowFeed post says "the fan-out-on-read model is more efficient for our use case", because the push design was "62 times greater" in data size; it ranks tens of thousands of records per request with a p99 of about 140 ms.
- Push: fast, simple reads and easy caching; expensive, slow writes for big accounts and lots of memory for timelines of people who never log in.
- Pull: cheap writes, always-fresh feeds and easy re-ranking (LinkedIn's reason); every open becomes a wide, latency-sensitive fan-in.
Reads outnumber writes about 50 to 1, so I'd precompute: on post, fan-out workers push the post ID into each active follower's Redis timeline, capped at 800. Accounts above about a million followers aren't fanned out; their recent posts are fetched and merged at read time. The timeline holds IDs only, and we hydrate posts from a cache.
Picking push or pull without numbers, or forgetting the celebrity problem. The interviewer will ask "what happens when someone with 50 million followers posts?": have the arithmetic ready.
Try it: push, pull or hybrid?
Pick a network and a way to build feeds. The lab works out timeline inserts per second, reads per feed open, how long a celebrity post takes to reach everyone, and how much memory the timelines need, then says which limit you hit first.
A Twitter-sized network: 150 million daily users, about 5,000 posts a second, and 200 film stars and cricketers with 20 million followers each. Everything is pushed on write.
| What we're sizing | Number | How we got it | So we decide |
|---|---|---|---|
| 1 · The traffic | |||
| Posts and feed opens per second (peak)Feeds are read far more often than posts are written. That ratio, and the few accounts with millions of followers, decide where the work should go. | 10K posts · 35K opens | posts: 2 × 150M users × 3/day ÷ 86,400 s = 10K/s, plus 200 celebrities × 5/day = 0.02/s opens: 2 × 150M × 10/day ÷ 86,400 = 35K/s accounts a user follows: 60 + 200 × 20M ÷ 150M celebrities = 87 | Opens outnumber posts 3 to 1: doing work at write time so reads are cheap usually pays. |
| 2 · Work at write time | |||
| Timeline inserts per secondPush copies each post into every follower's timeline. Cheap for a post with 60 followers, enormous for one with 20 million. | 1.1M (73%) | normal: 10K posts/s × 60 followers = 625K/s celebrities: 0.023 posts/s × 20M followers = 463K/s ÷ capacity 1.5M/s = 73% | Close to the limit: a bigger peak will overflow it. |
| 3 · Work at read time | |||
| Timeline reads per feed openPull makes every open a scatter-gather across everyone you follow; the feed waits for the slowest of those reads. | 1 · 35K/s (2%) | push: read your own precomputed timeline = 1 read 35K opens/s × 1.0 = 35K reads/s ÷ capacity 2.0M/s = 2% | Cheap reads. |
| 4 · Freshness | |||
| A celebrity post reaches its last follower afterOne post from a star is millions of writes, and normal posts queue behind it. | 13 s | 20M inserts ÷ 1.5M/s, if the whole fan-out tier did nothing else = 13 s target: 5 s | Too slow: pull the biggest accounts at read time. |
| 5 · Memory | |||
| Precomputed timelines in cacheTimelines hold IDs, not posts; the text and media are fetched (and cached) once per post when the feed is shown. | 7.20 TB | 150M users × 800 entries × 20 B (post ID, author ID, flags) × 3 copies = 7.20 TB | Terabytes of RAM: keep timelines only for recently active users and rebuild the rest on demand. |
| 6 · Verdict for this setup | |||
| What you get | A celebrity post takes 13 s to reach everyoneLoad is within limits on average, but one post from a star with 20M followers is 20M inserts. Even with the whole fan-out tier on it (1.5M/s), the last follower sees it 13 s later, against a target of 5 s, and normal posts queue behind it. Don't fan out celebrities: store their posts once and merge them in when a follower opens the feed (hybrid). | ||
Try: on Big network, push, set followers per celebrity to 2 million. On Match night, switch to Hybrid: still behind, because six times the normal posting alone overflows fan-out, so known peaks need capacity, not just a smarter model. On Big network, pull, set followers of a normal account to 20. On Small app, raise a celebrity to 5 million followers. Model: rounded teaching values; every follower is active, posts spread evenly over the day apart from the peak factor, a celebrity post has the whole fan-out tier to itself, and a real feed also ranks, filters and hydrates posts.
Assembling and paging a feed
Serving a feed is a small pipeline: get candidate IDs (timeline, pulled accounts, recommendations), hydrate them from caches, filter (deleted, blocked, already seen), rank, and return one page with an opaque cursor, because offset pages skip and repeat items while new posts arrive and get slower the deeper you go.
Scrolling back through the family group
Everyone has been posting lehenga photos in the family WhatsApp group all morning. Mausi wants to go back to the ones from before lunch.
If she said "show me page 3", the answer would keep changing: every new photo pushes everything down, so she'd see some photos twice and miss others. What she actually does is scroll: "show me what came before the last photo I'm looking at". New messages at the top don't disturb that at all.
And the group doesn't send every photo to her phone at full size. It sends small previews first; the full image loads only when she taps. Photos someone deleted, she never sees.
The read path for one feed page
- Candidates: post IDs from the precomputed timeline, plus recent posts from pulled celebrities, plus ads or recommended posts.
- Hydrate: fetch post bodies, author names, counts and media URLs by ID in batches from a cache (multi-get), not one query per post.
- Filter: deleted or edited posts, blocked or muted authors, privacy rules, posts already seen.
- Rank: newest-first, or a model (two-stage, as above); then de-duplicate and diversify (not five posts in a row from one account).
- Page: return 20–50 items and a cursor.
Cursor (keyset) pagination
- The cursor encodes where the page ended, e.g. (created_at, post_id) of the last item; the next query is "WHERE (created_at, id) < cursor ORDER BY created_at DESC, id DESC LIMIT 20", served by an index.
- Stable while new items arrive, and as cheap on page 50 as on page 1. Offset pagination ("OFFSET 1000") reads and throws away 1,000 rows and shifts under inserts.
- Make the cursor opaque (base64 of the values, signed if needed) so the server can change the scheme.
- For a ranked feed, order isn't by time, so the server keeps the ranked list for the session (or the IDs already served) and the cursor points into it.
Pull to refresh asks for items newer than the first one shown (a "since" cursor).
Slack's 2017 post "Evolving API pagination at Slack" (Michael Hahn) explains the move to cursors: with offsets "the database still has to read up to offset + count rows from disk", and when new messages arrive between requests, offset pages end up "skipping or returning duplicate results". Its cursor-based design is opaque to clients, and gives up total counts and jumping to page N in exchange.
Twitter's 2023 description of its home timeline shows the same pipeline shape at scale: candidate sourcing, ranking, then "heuristics and filters to implement various product features" for a balanced, diverse feed, before mixing in ads and other content.
- Cursors are stable and fast but can't jump to page 37 or show a total count; offset pages are fine for small, rarely changing admin lists.
- Freezing a ranked list per session gives stable paging but holds memory and goes stale; re-ranking every page is fresher but can repeat or drop items.
GET /feed?cursor=… returns 20 items and a next cursor. The server reads IDs from the user's timeline and merges celebrity posts, multi-gets the posts from cache, drops deleted and blocked ones, ranks, and encodes the last item's (score or time, ID) into an opaque cursor. No offsets, so new posts never cause duplicates while you scroll.
Using LIMIT/OFFSET for an infinite feed, or hydrating each post with its own database query (an N+1 that turns one feed load into 50 round trips).
Geo indexes: geohash, S2, H3 and quadtrees
To find what's near a point, map the Earth onto cells with IDs (geohash, S2, H3) or split it adaptively (quadtree), index items by cell, and search the user's cell plus its neighbours, then compute exact distances on that small set; never compute distance to every item.
PIN codes and the parking lot across the road
India's PIN codes are a grid of cells with a hierarchy: the first digit is a region, the first three a sorting district, all six a post office's area. Two addresses that share more leading digits are usually closer together. That's how a geohash works: a longer shared prefix means a smaller shared cell.
But "usually" hides a trap. The family's car is parked in a lot just across the main road, which happens to be in a different PIN code. If Imran searched only "places in my PIN code", the nearest parking would be invisible. So he checks his own area and the areas around it, then measures real distances to the few places he found.
On a crowded day, one lane has fifty shops and a park has none. Imran's notebook splits busy lanes into smaller sections, so no single page grows too long.
Cell-based indexes turn 2-D points into 1-D keys a normal index can store:
- Geohash: interleave latitude and longitude bits and encode in base-32; each extra character is a smaller rectangle. Easy (a string prefix), but cells are rectangles that shrink in width away from the equator, and neighbours across a cell edge can have totally different prefixes.
- S2 (Google): projects the sphere onto a cube and numbers cells along a Hilbert curve, 31 levels; nearby cells mostly get nearby IDs, and any region can be covered by a few cell ranges.
- H3 (Uber): hexagons at 16 resolutions; every neighbour's centre is the same distance away, which suits movement, smoothing and per-area pricing.
Nearby search: pick a cell size close to the search radius, look up the user's cell and its neighbours (8 for squares, 6 for hexagons, or "k rings"), fetch candidates, compute exact distance (haversine), filter by radius, then rank (distance, rating, ETA).
Quadtrees and R-trees split space adaptively: a cell divides when it holds too many items, so dense city centres get small cells and empty areas big ones. PostGIS uses R-tree-like GiST indexes.
Moving objects (drivers, riders): keep the latest positions in memory, updated every few seconds, indexed by cell and sharded by cell or city; hot cells (a stadium after a match) need splitting or replicas.
Elasticsearch's geohash docs (7.17) give cell sizes at the equator: length 5 ≈ 4.9 km × 4.9 km, length 6 ≈ 1.2 km × 609 m, length 7 ≈ 153 m × 152 m. Redis stores GEO data in a sorted set: "latitude and longitude bits are interleaved to form a unique 52-bit integer" used as the score, and its distance maths has up to 0.5% error.
S2's docs describe 31 levels (0–30), cells numbered so "if the S2CellIds of two cells are close together, then the cells are also close together", with leaf cells "about 1cm across". Uber's 2018 H3 post (Isaac Brodsky) explains hexagons' equal-distance neighbours, 16 resolutions with seven children per parent, and that Uber calculates surge pricing by measuring supply and demand in each hexagon.
- Fixed grids (geohash, S2, H3) are simple to shard and cache but uneven: a cell in Connaught Place may hold thousands of places, one in the Thar none; adaptive quadtrees balance load but are harder to distribute and update.
- Small cells mean fewer false candidates but more cells to query for a given radius; pick the level whose cell is about the size of the radius.
I'd index restaurants by H3 cell at a resolution about the size of the delivery radius. A nearby query takes the user's cell plus one ring of neighbours, fetches candidates from those cells, computes exact distance and road ETA, and ranks. Driver locations are kept in memory by cell, updated every four seconds, and sharded by city.
"Compute the distance from the user to every restaurant", or using only the user's own geohash cell, which misses the place 50 metres away across a cell edge.
Remember it
One line per idea. Read this the night before.
- Inverted index: term → sorted list of document IDs; analyse queries exactly like documents; never LIKE '%term%'.
- Ranking: BM25 (rare terms, saturating counts, short documents) as the baseline; at scale, cheap retrieval of ~1,000 candidates, then an expensive ranker on just those.
- Vector search matches meaning with approximate indexes (HNSW) that trade recall for speed; hybrid = BM25 + vectors merged with RRF, because each misses what the other finds.
- Scaling search: shards of 10–50 GB, replicas for reads, scatter-gather top-k; the index is derived from the database via CDC, refreshed about every second, rebuilt behind an alias.
- Typeahead: precomputed top-k per prefix in an in-memory trie or FST, rebuilt from query logs; debounce, cache popular prefixes, personalise with a light re-rank; tens of milliseconds.
- Feeds: push copies IDs to followers' timelines (cheap reads, costly celebrity writes); pull merges at read time (cheap writes, wide reads); hybrid pushes normal accounts and pulls celebrities.
- Serving a feed: candidates → hydrate by multi-get → filter → rank → page with an opaque cursor, never OFFSET.
- Geo: cells (geohash, S2, H3) or adaptive trees (quadtree, R-tree); search your cell plus neighbours, then exact distance on the few candidates.
Check yourself
Answer out loud, then open.
Your e-commerce search uses a LIKE query on the products table and it's slow and misses "shoe" when users type "shoes". What do you change?
Move search to an inverted index (Elasticsearch or OpenSearch), fed from the database.
- Analyse titles and descriptions: lowercase, stem (shoes → shoe), synonyms (sneakers ~ trainers), maybe transliteration for Hindi queries. Keep SKUs and brand codes as exact keyword fields.
- Rank with BM25 plus boosts (in stock, rating, sales), later a learned ranker.
- Feed it with CDC from the products table so the database stays the source of truth; accept a second or two of lag.
Say it the database stores products; the search index is a derived, rebuildable view built for matching and ranking.
A celebrity with 50 million followers posts. Walk through what happens in a push-based feed, and what you'd change.
Pure push means 50 million timeline inserts for one post.
- At 1.5 million inserts a second for the whole fan-out tier, the last follower sees it after about 33 seconds, and every normal post queues behind it.
- Fix: don't fan out accounts above a threshold (say 1 million followers). Store their posts once; when a follower opens the feed, read the recent posts of the few celebrities they follow and merge them with their precomputed timeline.
- Also fan out only to followers active recently, and keep separate queues so one huge fan-out can't starve normal ones.
Say it hybrid fan-out, push for most accounts, pull for celebrities, merged at read time.
Why does LinkedIn build its feed on read when Twitter famously built it on write?
Because the numbers and goals differ.
- LinkedIn reported that the push design was 62 times larger in data, and that computing at read time made it easy to re-rank and A/B test relevance; it still met a p99 of about 140 ms.
- Twitter's timelines were strictly time-ordered with a huge read-to-write ratio, so precomputing made each of 300K reads a second a single lookup.
- Both ended up hybrid in practice: Twitter merged very large accounts at read time; ranked feeds add candidates from outside your network either way.
Say it choose by read/write ratio, follower distribution, freshness and how much the ranking changes; then handle the extremes with the other model.
Design "restaurants near me" for a food-delivery app. What index, and what does one query do?
Index restaurants by cell.
- Use H3 (or geohash) at a resolution roughly the size of the delivery radius, and store cell → restaurant IDs (or put the cell in the search index alongside cuisine, rating and open-now).
- A query computes the user's cell, adds one ring of neighbours, fetches candidates from those cells, filters by open-now and serviceability, computes exact distance or road ETA, and ranks.
- Cache results per cell for a minute; restaurants rarely move.
- Dense areas: use a finer resolution or cap candidates per cell, ranked by rating.
Say it never compute distance to every restaurant; search the cell and its neighbours, then do exact maths on a few hundred.
Typeahead p99 is 300 ms and users complain suggestions lag behind their typing. What do you look at?
Make the server do less per keystroke, and the client send less.
- Server: serve precomputed top-k per prefix from an in-memory trie or FST, not a search query; replicate it close to users; cache the most common short prefixes (one or two characters) at the edge.
- Client: debounce about 50–100 ms, cancel in-flight requests when a new key arrives, and reuse results (the suggestions for "biry" can filter those for "bir").
- Keep personalisation to a small re-rank of the global top-k.
Say it typeahead is a lookup, not a search; target tens of milliseconds server-side, because Facebook found 100 ms already makes it stutter.
Your feed API uses ?page=3&size=20 and users report duplicate posts while scrolling. Why, and what's the fix?
Offsets count from the top, and new posts keep arriving at the top.
- If 5 posts arrive between page 2 and page 3, page 3 starts 5 items earlier, so the user sees 5 posts again; deletes cause skips the other way. Deep offsets also read and discard every earlier row.
- Fix: cursor pagination. Return an opaque cursor encoding the last item's (time or score, ID); the next request asks for items after it, using an index.
- For a ranked feed, keep the ranked ID list for the session (or the set already served) and page through that.
When would you add vector search, and what would make you keep keyword search?
Add vectors when users describe what they want in their own words: support articles, "something like this" images, RAG over documents, queries in mixed languages.
Keep keyword search because:
- Exact tokens (SKUs, error codes, names, PIN codes) are where embeddings are weakest.
- Filters and facets, explainability and cost are simpler.
So run both and merge with reciprocal rank fusion, then the usual ranker; measure ANN recall against exact search, and plan for re-embedding when the model changes.
Where you'll use this in the series
- Uber: from tap to pickup · drivers in an in-memory geo index by H3 cell, ranked by road ETA
- Caching · timelines and typeahead prefixes as precomputed caches
- Replication and sharding · sharding timelines and search indexes, and hot cells
- Queues and event streams · fan-out workers and CDC into the search index
- News feed: fan-out and ranking · the full design built on this page's fan-out and paging
- Typeahead / autocomplete · the trie, the offline pipeline and personalisation in depth (coming)
- Proximity service (Yelp) · geohash vs quadtree for places that rarely move (coming)
- AI foundations: inference, RAG and agents · vector and hybrid retrieval for RAG
Sources
- Near real-time search, Elasticsearch reference 8.19 (checked Oct 2026)
- Similarity module (BM25 defaults), Elasticsearch reference 7.17
- Size your shards, Elastic docs (checked Oct 2026)
- Reciprocal rank fusion, Elasticsearch docs (checked Oct 2026)
- Deep Neural Networks for YouTube Recommendations, Covington, Adams and Sargin, RecSys (2016)
- Twitter's Recommendation Algorithm, Twitter Engineering (Mar 2023)
- Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs, Malkov and Yashunin (arXiv, Mar 2016)
- pgvector 0.8.7 documentation (checked Oct 2026)
- The life of a typeahead query, Keith Adams, Engineering at Meta (May 2010)
- Context-aware autocomplete at scale at Flipkart, The Fifth Elephant (2020)
- You complete me (completion suggester), Elastic blog (Aug 2013)
- The architecture Twitter uses to deal with 150M active users, High Scalability (third party, Jul 2013)
- Timelines at Scale, Raffi Krikorian, QCon SF 2012 (InfoQ, Apr 2013)
- FollowFeed: LinkedIn's feed made faster and smarter, LinkedIn Engineering (Mar 2016)
- Evolving API pagination at Slack, Slack Engineering (Aug 2017)
- Geohash grid aggregation (cell sizes), Elasticsearch reference 7.17
- GEOADD, Redis docs (checked Oct 2026)
- S2 cell hierarchy, S2 Geometry docs (checked Oct 2026)
- H3: Uber's Hexagonal Hierarchical Spatial Index, Isaac Brodsky, Uber Engineering (Jun 2018)
Checked October 2026. Mechanisms come from official docs (Elasticsearch near real-time search, similarity, shard sizing, geohash grid and RRF; Redis GEOADD; S2 Geometry; pgvector 0.8.7) and papers (HNSW 2016, YouTube RecSys 2016). Company figures are as published on the dates shown: Facebook (2010), Elastic (2013), LinkedIn (2016), Slack (2017), Uber (2018), Flipkart (2020) and Twitter (2023). Twitter's 2013 timeline numbers come from a third-party write-up of Raffi Krikorian's QCon talk and are labelled that way. The lab uses rounded teaching values.
System Design Mastermind · Foundations
Series homeAll of Foundations
18 publishedStart here: the concepts every design uses, each told as a story you'll remember.
How a request travels: DNS, load balancers, gateways and open connections
Name → address (DNS) → open a secure line once and reuse it (TCP, TLS) → nearby copies for static files (CDN) → spread and guard the work (load balancer, gateway) → find colleagues inside (discovery) → keep a line open for live updates.
The interview framework: requirements, numbers and scope before boxes
Agree what users must do (three core requirements) → put numbers on how well (p99 latency, availability, durability, staleness) → say what's out of scope → sketch the simple end-to-end design → go deep only where a number breaks it.
Back-of-envelope estimation: from users to servers in one minute
Users × actions ÷ 86,400 (≈10⁵) = average per second → × peak factor → split reads and writes → storage = count × size × time × copies → bandwidth × 8 bits → in flight = rate × latency → servers = peak ÷ (capacity × 60%) + 2 spares.
APIs and real-time communication: REST, gRPC, retries, webhooks and live updates
Nouns + HTTP verbs (user from the token) → REST outside, gRPC inside → cursor pagination → POST with an Idempotency-Key, retries with backoff and jitter → add, don't change → poll for rare updates, SSE for one-way live, WebSockets for both ways → webhooks are at-least-once → thin connection gateways with resume and push fallback.
Databases: data models, indexes and transactions
Relational by default (each fact once, keys, constraints) → key-value / document / wide-column / graph only for a named access pattern → B-tree for reads, LSM for heavy writes → composite index with equality columns first, then the sort → one transaction per local change, made durable by the write-ahead log → know your isolation level → win races with a conditional write and a unique constraint.
Replication and sharding: copying and splitting your data
Copies scale reads and survive failures (leader + followers); splits scale writes and size (shards). Replicate first; shard only when data size or write rate outgrows one leader → pick the shard key from the main query → hash it into many fixed slots so growth moves ~1/(N+1) → name your hot key and your one cross-shard query.
Caching: hit ratios, invalidation and stampedes
Cache what is read far more than it changes → say the expected hit ratio and size the database for the misses → cache-aside with a TTL; on writes, update the database then delete the key → coalesce misses on hot keys and jitter TTLs → plan for the cache failing or restarting empty, because by then the system depends on it.
Consistency, CAP and quorums: what replicas promise
Say what each operation needs, not what the system is: strong (linearizable) for money, stock, seats and uniqueness; read-your-writes for a user's own data; eventual for counts, feeds and pages → during a partition, strong operations fail on the minority side, the rest keep serving (CAP) → on a normal day, strong costs a round trip to a quorum (PACELC) → with N copies, W + R > N makes reads overlap the latest write, but it isn't linearizability.
Coordination: clocks, leaders, locks and consensus
Don't order events across machines by wall-clock time; let one leader assign the order → elect that leader by majority vote with increasing terms, so a split network can't elect two → give it a lease so a dead leader is replaced without anyone proving it died → and a fencing token the storage checks, so a paused old leader can't do harm → use consensus (Raft) for the few decisions that must be agreed, not for every request.
Queues and event streams
Put a queue between work that can wait and the caller, so a spike becomes lag instead of an outage → use a task queue for jobs and an event log (Kafka) when many consumers need every event, replay or per-key order → key by the entity whose order matters and size partitions for peak consumers → deliver at least once and make consumers idempotent → retry a few times with backoff, then dead-letter → scale on lag → publish through an outbox, never "save, then publish".
Idempotency, exactly-once and sagas
Treat a timeout as unknown, never as failed → make writes idempotent by design (set, don't add; client IDs; conditional writes) → for the rest, an idempotency key per intent, stored with the result in the same transaction as the effect → consumers deduplicate by message ID in the same transaction → exactly-once holds only inside one boundary → across services, use a saga of local steps with compensations, not 2PC → compensable steps first, the pivot (capture payment) next, retryable steps last, on a durable orchestrator.
Scaling and performance
State latency as a percentile at a stated load → size each tier to the utilisation where its p99 is still flat (pooled, least-request balancing lets you run hotter) → budget fan-out calls against the page deadline, hedge stragglers → scale up first, scale out stateless tiers → name the shared resource (database, lock, connections) that caps the speed-up → find the saturated resource and cut work per request → pre-scale known peaks, autoscale on the signal that saturates → under overload, shed the lowest-priority work fast and budget retries.
Reliability and disaster recovery
Turn the target into a downtime budget → cut hard dependencies, because chains multiply → spread copies across zones (cells for blast radius) → timeouts from the deadline, one layer of jittered retries under a budget → circuit breakers with fallbacks and a bulkhead per dependency → fast, non-flapping health checks (readiness checks dependencies, liveness doesn't) → statically stable: spare capacity already running, config cached → PITR plus tested restores, because replicas copy mistakes → the cheapest DR strategy that meets RTO and RPO, drilled.
Observability and safe deployments
Metrics to notice, traces to locate, logs to explain (joined by a trace ID) → watch latency percentiles, traffic, errors and saturation → set an SLO per user journey and treat 1 − SLO as an error budget → page on burn rate over two windows, not on CPU → canary every change on a slice with automated analysis against a baseline → keep every version compatible with its neighbours (expand, migrate, contract) so rollback is always possible → ship dark behind flags, and stage config like code → when it breaks: one commander, mitigate first, blameless postmortem.
Security essentials for system design
Prove who the caller is (slow salted hashes, MFA, passkeys, rate-limited login) → carry identity in short-lived signed tokens with revocable refresh tokens, or in sessions you look up → delegate with OAuth code flow + PKCE, sign in with OpenID Connect → check this user against this object on every request, least privilege for people and services, audit logs → TLS 1.3 at the edge, mTLS inside, no trust from network location → envelope encryption with a KMS, secrets in a vault, tokenise what you needn't keep → treat all input as data (parameterise, encode, CSRF tokens, no user-chosen fetches) → absorb floods and abuse at the edge.
Search, feeds and geo building blocks
Search: analyse text into terms → inverted index of sorted postings → BM25 or hybrid (BM25 + vectors via RRF) retrieval of ~1,000 candidates → learned ranker → shards with replicas, fed from the database by CDC, refreshed every second. Typeahead: precomputed top-k per prefix in memory. Feeds: push IDs into followers' timelines, pull celebrities at read time, hydrate, filter, rank, page with cursors. Geo: index by cell (geohash, S2, H3), search the cell plus neighbours, exact distance on the few candidates.
Data pipelines: batch and stream
Pick batch or stream by how fresh each output must be. Get data in with log-based CDC (snapshot, then the WAL) and schemas that evolve safely; land raw events as Parquet in lakehouse tables partitioned by date. Batch jobs map, shuffle and reduce one partition and overwrite it, so retries and backfills are safe. Stream jobs window by event time, fire on watermarks, decide whether late events wait, correct or drop, and checkpoint state with offsets for exactly-once effect, with transactional or idempotent sinks. Reprocess by replaying retained data (Kappa) rather than keeping two codebases (Lambda).
AI foundations: inference, RAG and agents
Latency is time to first token (prefill reads the prompt, compute-bound) plus output tokens × time per token (decode, memory-bound), so stream answers and limit by tokens. GPU memory is weights plus a KV cache per request; long prompts, not users, fill it. Continuous batching shares each weight read across many requests, cutting cost per token by 10× or more until time per token hits its target. Route easy requests to small models, cache shared prompt prefixes, quantize carefully. RAG retrieves, reranks and cites a few permission-filtered chunks; agents are tool-calling loops with budgets, idempotent tools and approval for irreversible steps. Evaluate every change on an eval set, and design so a model fooled by prompt injection still can't do damage.