Skip to content

Design Post Search (Facebook Search)

Advanced 77 min read Part 17 of 18

Design Facebook post search: an inverted index fed by a post stream, sharding by document vs term, recency and like ranking, hot-query caching and freshness.

The Problem#

On Facebook you can type a few words, such as "taylor swift concert", into the search box and get back posts that contain those words, newest first or most liked first. Behind the box sit trillions of posts written over many years, thousands of new posts every second, and a hundred thousand likes every second that keep changing which posts are "most liked".

This problem is popular in infrastructure-style interviews because it tests whether you understand how data is laid out to answer a query fast. Interviewers often add a twist: you may not use Elasticsearch, Solr, or a database's built-in full-text search. You have to build the index yourself from simpler parts (a key-value store, a log, blob storage). That rule exists to see whether you know what a search engine does inside, not whether you can name one. It happens in real interviews, so be ready for it.

The four hard parts are:

  • Finding matches fast. Scanning petabytes of text for a word at query time is hopeless. We need an inverted index: a map from each word to the list of posts that contain it.
  • Keeping the index up to date. Every new post must become searchable within about a minute, and every like changes the like ranking. At 10,000 posts and 100,000 likes per second, the index is under heavy, continuous write load. This system is actually write-heavy, which surprises many candidates.
  • Ranking. Users want results sorted by recency or by like count, without the system sorting tens of millions of matches at request time.
  • Size. Trillions of posts and petabytes of raw text cannot all live in memory, yet old and unpopular posts must still be findable.

A real-world analogy. Think of the index at the back of a big textbook. To find every page that mentions "photosynthesis", you do not read the whole book; you look up the word in the index, which lists page numbers. A search engine builds that index for every word in every post. Now imagine the book gains thousands of new pages every second, readers want the page list sorted by "most recently written" or "most popular", and the "popularity" of every page changes constantly as readers applaud. The index must be updated continuously, kept in two sort orders, and split across many volumes because no single binder can hold it. That is post search.

This case study builds the index from first principles, then shows how it is sharded, how ingestion works through streams and change data capture, how ranking by recency and likes is kept cheap, how hot queries are cached, and how freshness is guaranteed. It builds on Elasticsearch and Search Systems, Database Indexing and Partitioning and Sharding.

Clarifying Questions#

QuestionTypical answerWhy it matters
Can we use Elasticsearch or a built-in full-text index?No, build the index from basic components.Forces us to design the inverted index, sharding and ranking ourselves.
What do users search?Keywords and short phrases in post text.Phrases need either intersection plus filtering or phrase-aware indexing.
What sort orders?By recency or by like count.Two different orders over the same matches suggest two indexes.
Personalised results, such as friends' posts first?Out of scope initially.Without personalisation, identical queries get identical results, so caching works very well.
Privacy rules, such as friends-only posts?Out of scope initially; mention it.Privacy filtering per viewer is a large problem of its own (covered in a deep dive below).
How fresh must results be?New posts searchable within one minute.Allows batching, short cache TTLs and asynchronous indexing.
Must old posts be searchable?Yes, all posts, but old ones may be slower to find.Hints at hot and cold tiers.
Fuzzy matching, synonyms ("bird" matching "ostrich")?Out of scope.Keeps tokenisation simple; mention as an extension.
Media, images, video?Out of scope; text only.No visual search pipeline.
Live-updating search results?Not required.No push channel to the search page.
Scale?About 1 billion daily users, each posting about once a day and liking about 10 posts.Gives the write rates that dominate the design.
Latency target?Median under 500 ms.Rules out request-time scanning and large request-time sorts.

Requirements#

Functional Requirements#

  1. Users can create posts and like posts (the write path that feeds search; post and like services already exist).
  2. Users can search posts by keyword, including multi-word queries and phrases.
  3. Users can sort results by recency or by like count.

Below the line (out of scope at first): fuzzy matching and synonyms, personalisation, privacy filtering, sophisticated relevance ranking, images and media, real-time updates on the results page. Stating these explicitly prevents surprises later. Note in particular that dropping personalisation makes caching dramatically more effective, so it is worth confirming that it really is out of scope.

Non-Functional Requirements#

  1. Fast: median query under 500 ms, p99 under about 1 to 2 seconds.
  2. High volume: about 10,000 searches per second on average, with bursts of 10 times or more during big events.
  3. Fresh: new posts searchable within 1 minute; like counts reflected in ranking within minutes.
  4. Complete: every post is discoverable, including old and unpopular ones, though these may be slower to retrieve.
  5. Highly available: search should keep working, perhaps slightly stale, when parts of the system fail. Availability matters more than strict consistency here, since a result that is a few seconds out of date harms nobody.
  6. Durable index: losing an index node must not lose data permanently; the index can always be rebuilt from the source of truth (the post database or the post log).

The phrase "old posts may be slower" foreshadows a design decision. When data is huge but access is skewed, split it into hot data (accessed often, kept in memory) and cold data (rarely accessed, kept on cheaper disk or blob storage). We return to this in the storage deep dive.

Capacity Estimation#

A common mistake is to fixate on "search" and assume reads dominate. Estimate first; the numbers say otherwise. We use 100,000 seconds per day (rounding 86,400 up) to keep the arithmetic easy. See Back-of-the-Envelope Estimation.

Writes.

  • Posts: 1 billion users × 1 post per day ÷ 100,000 s = 10,000 posts per second. (In reality perhaps 20% of users post five times and 80% not at all; the average is what matters for throughput.)
  • Likes: 1 billion × 10 likes per day ÷ 100,000 s = 100,000 likes per second, ten times the post rate.

Reads.

  • Searches: 1 billion × 1 search per day ÷ 100,000 s = 10,000 searches per second on average, bursting to 100,000 or more during a major event, when millions of people search for the same thing at once.

So writes (110,000 per second) outnumber reads (10,000 per second) by about ten to one. This is a write-heavy system that happens to serve search. Say that out loud in the interview; it shapes everything that follows.

Index write amplification. One post is not one write. Tokenising a post (splitting it into words) produces, say, 50 distinct terms on average (short posts have 10, long ones 1,000). Each term's posting list gets the post id appended, once in a recency index and once in a likes index:

  • 10,000 posts/s × 50 terms × 2 indexes = 1 million index writes per second from post creation alone.
  • If every like updated the post's score in every term's likes index: 100,000 likes/s × 50 terms = 5 million index updates per second. This is the single largest load in the system and the reason the like path gets its own deep dive.

Storage. Assume 10 years of history and 1 KB of metadata per post (probably generous).

  • Posts: 1 billion per day × 365 × 10 ≈ 3.6 trillion posts.
  • Raw post data: 3.6 trillion × 1 KB ≈ 3.6 PB.
  • Postings (one entry per term per post): 3.6 trillion × 50 ≈ 180 trillion postings. At 8 bytes per uncompressed post id, that is about 1.4 PB per index, 2.9 PB for two indexes. With delta encoding and compression (about 1 to 2 bytes per posting, explained later), about 200 to 400 TB per index.
  • Holding even the compressed index in memory, at 256 GB of usable RAM per machine, would take 800 to 1,600 machines per copy, before replication. We cannot keep everything hot. We need caps on posting-list length, hot and cold tiers, or both.

What a cap buys. Most searches look only at the first page or two of results. If each term's in-memory list keeps only the newest (or top-liked) 10,000 posts, the hot index is bounded by vocabulary rather than history. Suppose 10 million terms are worth keeping hot and each holds at most 10,000 ids at 8 bytes: that is at most 10 million × 10,000 × 8 B = 800 GB per index, and in practice much less because most terms have far fewer matches. A few dozen memory nodes hold it. The full history moves to a cheaper tier that is slower but complete.

Query fan-out and bandwidth. A results page shows about 25 posts. Hydrating them (fetching text, author and counts) at about 1 KB each is 25 KB per query, or 250 MB/s at 10,000 queries per second: easy. The expensive part is reading posting lists, which is why their size and placement matter.

Cacheability. Query popularity follows a heavy-tailed (Zipf-like) distribution: a small set of queries ("world cup", a celebrity's name during breaking news) accounts for a large share of traffic. With no personalisation, every user asking "world cup" sorted by likes gets the same answer, so a results cache with a TTL under a minute can absorb a large fraction of reads, especially during the bursts that would otherwise hurt most.

QuantityValue
Post writes10,000 per second
Like writes100,000 per second
Searches10,000 per second average, 100,000+ in bursts
Index writes from postsabout 1 million per second
Naive like-driven index updatesabout 5 million per second
Total postsabout 3.6 trillion
Raw post dataabout 3.6 PB
Postingsabout 180 trillion
Compressed postings per indexabout 200 to 400 TB
Capped hot index per sort orderunder 1 TB

Core Entities#

  • User: creates posts and likes; issues searches.
  • Post: the document being searched. It has an id, author, text, creation time and (implicitly) a like count.
  • Like: a user liking a post. For search we mainly care about the resulting like count.
  • Term (also called a token or keyword): a normalised word or phrase extracted from post text, such as taylor or taylor swift.
  • Posting list: for one term, the ordered list of post ids containing it. There is one per term per sort order (a recency list and a likes list).
  • Index shard: a partition of the index held by one group of servers.
  • Query result (cached): the ranked list of post ids for a normalised query and sort order.

The entities are deliberately simple. The interesting design lives in how posting lists are stored, partitioned and updated, not in the entity model.

API Design#

The search system sits inside a larger social product. Post and like creation are owned by existing services; search consumes their events. For clarity we show both the external API and the internal events. See API Design Best Practices.

Write path (owned by existing services; search consumes their events):

POST /v1/posts
{ "content": "Saw Taylor Swift at the concert tonight!" }
-> 201 { "postId": "7362917461", "createdAt": "2026-12-03T19:04:11Z" }
 
POST /v1/posts/7362917461/likes
-> 204
 
Internal events (on a log such as Kafka, keyed by postId):
  post.created  { postId, authorId, text, createdAt }
  post.updated  { postId, text, updatedAt }
  post.deleted  { postId, deletedAt }
  like.added    { postId, userId, at }
  like.removed  { postId, userId, at }

Query path:

GET /v1/search?q=taylor+swift&sort=likes&limit=25&cursor=eyJzIjoxMjM0fQ
-> 200
{
  "results": [
    { "postId": "7362917461", "authorId": "...", "snippet": "Saw Taylor Swift at ...",
      "createdAt": "2026-12-03T19:04:11Z", "likeCount": 18342 }
  ],
  "nextCursor": "eyJzIjo5ODc2fQ"
}

Design notes:

  • sort is recency or likes. Each maps to a different index, not to a sort performed at request time.
  • Cursor pagination, not page numbers. For recency, the cursor encodes the last returned post id (ids are time-sortable), so the next page is "older than this id". For likes, it encodes the last score and post id. An offset like page=400 would force the server to skip thousands of entries, and results shift as new posts arrive.
  • The response is identical for every user who sends the same normalised query, sort and cursor. That makes it safe to cache in a shared cache and even at the CDN with Cache-Control: public, max-age=30. Once personalisation or privacy enters, this changes.
  • In a real deployment the write endpoints would not exist on the search service at all; search would consume the event stream. Showing them makes the two paths explicit.

High-Level Design#

We satisfy each functional requirement with the simplest design that works, then fix its problems in the deep dives. Say out loud which parts are over-simplified; interviewers are looking for flaws, and an acknowledged flaw counts in your favour.

1. Users can create and like posts#

Posts and likes are created by the existing Post Service and Like Service, which store them in their own databases. Search needs to observe those writes. The simplest version: both services call an Ingestion Service, which tokenises each new post and updates the index, and adjusts like counts when likes arrive.

Even at this stage, note the asymmetry from the estimates: likes arrive ten times as often as posts, and each like may touch many index entries. One ingestion service handles both for now; we split and scale it later.

Tokenisation is the process of turning text into index terms. A typical pipeline:

  1. Normalise Unicode (so composed and decomposed forms of "é" are the same) and lowercase.
  2. Strip markup and URLs, or index URLs as special terms.
  3. Split into words on whitespace and punctuation. For languages without spaces (Chinese, Japanese, Thai) use a dictionary or statistical segmenter.
  4. Handle hashtags and mentions as their own terms (#worldcup, @taylorswift), because people search for them exactly.
  5. Optionally stem (reduce "running" and "runs" to "run") and remove very common stop words ("the", "a"). For a recency-sorted social search, many systems keep stop words, because phrase queries like "to be or not to be" need them; posting-list caps keep their size under control.

The query string goes through the same pipeline, so a query for "Running" matches a post containing "runs" if stemming is on.

2. Users can search posts by keyword#

The read path starts with an API gateway (authentication, rate limiting; see API Gateway and Backend-for-Frontend) and a horizontally scaled, stateless Search Service that parses the query and asks the index for matches.

The heart of the problem is the index. How do we find every post containing "taylor" among trillions?

Bad: scan an un-indexed database

Store posts in a relational table and run SELECT * FROM posts WHERE content LIKE '%taylor%'. It returns correct results, but a leading wildcard cannot use a B-tree index, so the database reads every row. At 3.6 PB, a full scan at even 10 GB/s per node takes days.

Sharding or replicating does not save it. With N posts on M nodes, each node scans N/M posts. Even with 1,000 nodes, each scans 3.6 TB per query: minutes, not milliseconds, and every query occupies every node. Scanning is a dead end; we must organise data to match the query.

Great: an inverted index

An inverted index is a dictionary from each term to the list of documents containing it. "Inverted" because a normal (forward) view maps a document to its words; this maps a word to its documents.

post 101: "Saw Taylor Swift tonight"
post 102: "Taylor made a swift exit"
post 103: "Swift river crossing"
 
taylor -> [101, 102]
swift  -> [101, 102, 103]
saw    -> [101]
tonight-> [101]
made   -> [102]
exit   -> [102]
river  -> [103]
crossing->[103]

A query for "taylor" is now one key lookup returning a ready-made list, regardless of how many posts exist in total. The cost depends on the size of the answer, not the size of the corpus.

For the first version, store the index in Redis: one key per term, holding a list of post ids. Redis keeps it in memory, so a lookup takes well under a millisecond. On each new post, the Ingestion Service tokenises the text and appends the post id to the list of every term it contains. Durability is a concern for an in-memory store, but solvable: use Redis replication with append-only files, a durable Redis-compatible store such as Amazon MemoryDB, or simply treat the index as rebuildable from the post database. See Redis in Practice.

Two problems are already visible and will be addressed in the deep dives:

  • Posting lists for common words are huge. "the" or "love" appears in billions of posts.
  • Each post causes many writes, one per distinct term: 10 to 1,000 per post.

3. Users can sort results by recency or like count#

Bad: sort at request time

Fetch all post ids for "taylor", look up each post's timestamp or like count, sort in the Search Service, return the top 25. For a term with tens of millions of matches, the index returns hundreds of megabytes of ids, the service makes tens of millions of lookups, and the sort alone takes seconds. It fails the 500 ms target by orders of magnitude, and it does the same enormous work for every request.

Great: one index per sort order

Keep two indexes, each already in the order users want:

  • Creation (recency) index. For each term, a Redis list of post ids in creation order. New posts are always newer than old ones, so we only ever append. Queries read from the newest end (LRANGE key -25 -1). Time-sortable ids (such as Snowflake-style ids with a timestamp prefix) make "newer than" and "older than" comparisons cheap; see Unique ID Generation.
  • Likes index. For each term, a Redis sorted set, scored by like count. A sorted set keeps members ordered by score, like a priority queue that also supports range reads. Insertion and score updates cost O(log N); reading the top K costs O(log N + K). Queries call ZREVRANGE key 0 24.

On a new post, the ingestion service adds the id to both indexes for every term (score 0 in the likes index). On a like, it increments the post's score in the likes index of every term the post contains.

The trade-offs: storage doubles, which is a reasonable price for sub-millisecond ranked reads. And the likes index creates the 5-million-updates-per-second problem from the estimates, which the write-path deep dive solves.

# new post 7362917461 containing "taylor" and "swift"
RPUSH  idx:recency:taylor 7362917461
RPUSH  idx:recency:swift  7362917461
ZADD   idx:likes:taylor 0 7362917461
ZADD   idx:likes:swift  0 7362917461
 
# query "taylor", newest 25 and most-liked 25
LRANGE    idx:recency:taylor -25 -1
ZREVRANGE idx:likes:taylor 0 24 WITHSCORES

The full high-level design#

After the deep dives, the design looks like this. Writes flow from the source-of-truth databases through a log into partitioned indexers. Likes pass through an aggregator that turns a flood of events into a trickle of index updates. Queries pass through a CDN and a results cache before reaching a scatter-gather layer over sharded in-memory indexes, with cold tiers behind them.

The design has two halves that meet only at the index shards and the like count store. The query side serves reads through layers of caches; the ingestion side turns database changes into index updates.

Components:

  • CDN: caches popular search responses at the edge for tens of seconds. A hit returns in tens of milliseconds and never reaches our servers. See Content Delivery Networks (CDN).
  • API gateway: authentication, rate limiting, request routing.
  • Search Service: stateless. It normalises and tokenises the query, chooses a plan (single term, intersection, phrase lookup), checks the results cache, calls the broker, re-ranks, hydrates and paginates.
  • Results cache: Redis keyed by normalised query, sort order and cursor; TTL under one minute to respect the freshness requirement.
  • Broker (aggregator): sends sub-queries to the relevant shards in parallel, waits with a deadline, and merges partial results. This is the scatter-gather layer.
  • Hot index shards: in-memory posting lists (recency and approximate-likes orders), capped in length, replicated for availability and read throughput.
  • Cold index: immutable, compressed index segments for older posts and rarely searched terms, stored in blob storage (S3 or similar) and loaded on demand. See Object Storage and Blob Storage.
  • Re-ranker: fetches up-to-date like counts for the candidate set and sorts precisely.
  • Like count store: the current like count per post (a sharded key-value store or Redis), maintained by the aggregator.
  • Event log: Kafka topics for post and like events, fed by change data capture (CDC) from the source databases or by an outbox. It buffers bursts, lets indexers replay history, and decouples search from the product services. See Change Data Capture and the Outbox Pattern and Apache Kafka in Practice.
  • Indexers: consume post events, tokenise, and write postings to the right shards.
  • Like aggregator: consumes like events, keeps running counts, and emits index updates only when a post crosses a milestone.

Key Flows#

Flow 1: A new post becomes searchable#

  1. The Post Service writes the post to its database as usual. It does not call search.
  2. CDC (for example Debezium reading the database's replication log) publishes post.created to Kafka, partitioned by post id. Alternatively the Post Service writes an outbox row in the same transaction and a relay publishes it.
  3. An indexer consumes the event, tokenises the text, and produces the set of terms (and phrase terms, covered later).
  4. It writes the id to each term's posting lists on the appropriate shards, batching writes per shard (one pipelined request per shard rather than one per term).
  5. Only after every shard acknowledges does it commit the Kafka offset. If it crashes midway, the event is redelivered and the writes are repeated. Appends must therefore be idempotent: a sorted-set ZADD is naturally idempotent, and recency lists de-duplicate on read or use sets keyed by id. See Delivery Guarantees: At-Most, At-Least and Exactly-Once.
  6. The post appears in fresh queries immediately and in cached ones when their TTL (under a minute) expires. End to end, freshness is typically a few seconds, well inside the one-minute budget.

Flow 2: Searching "taylor swift" sorted by likes#

  1. The CDN checks its cache; on a miss it forwards to the origin.
  2. The Search Service normalises the query ("Taylor Swift!" becomes taylor swift) and decides on a plan: if a phrase term taylor swift exists in the index, use it directly; otherwise intersect taylor and swift.
  3. It checks the results cache. On a miss it asks the broker for the top 2K candidates (here 50 for a page of 25) by approximate like score.
  4. The broker queries the shards (one shard, or all, depending on the sharding scheme), merges the partial top-K lists, and returns candidates.
  5. The re-ranker fetches current like counts, sorts exactly, and keeps the top 25. The service hydrates post data (text, author), stores the response in the cache, and returns it with cache headers.

Typical latency: CDN hit 10 to 50 ms; results-cache hit 20 to 60 ms; full miss 80 to 300 ms (shard fan-out 10 to 50 ms, re-rank and hydration 20 to 80 ms, plus network).

Flow 3: A like changes the ranking#

  1. The Like Service records the like; CDC publishes like.added keyed by post id.
  2. The like aggregator, which owns that post id's partition, increments the post's running count in the like count store (always current).
  3. If the new count crosses a milestone (for example 1, 2, 4, 8, ...), the aggregator emits an index update: "post 7362917461 now has approximate score 16".
  4. Indexers apply the new score to the likes index entries for each of the post's terms.
  5. Queries sorted by likes see the new approximate order in the index and the exact count from the re-ranker.

Most likes therefore update one key-value counter, not 50 sorted sets, which is the difference between 5 million and a few hundred thousand index writes per second.

Data Model#

The source of truth for posts and likes lives in the product's own databases. Everything in the search system is derived data: it can be rebuilt from the post and like logs. That single fact drives many choices, such as using in-memory stores and tolerating eventual consistency. See Choosing a Database: A Decision Guide.

Logical tables and their physical form:

DataLogical keyPhysical storeNotes
PostpostIdPost DB (sharded MySQL or similar)Source of truth; used to hydrate results and to verify phrases.
Recency posting listtermRedis list or a sorted set scored by postIdAppend-only; capped at, say, 10,000 newest ids in the hot tier.
Likes posting listtermRedis sorted set scored by approximate likesScore updated only on milestones; capped at top 10,000.
Like countpostIdSharded key-value store or RedisExact, current count for re-ranking.
Term statisticstermAnalytics storeDocument frequency and query frequency; drive tiering and phrase-index decisions.
Cold segmentssegmentIdBlob storage (S3, GCS)Immutable compressed posting lists for older or rarely queried data.
Results cachenormalised query + sort + cursorRedis, CDNTTL under 1 minute.
Shard mapterm or post range to shardCoordination service (ZooKeeper or etcd)Read by brokers and indexers.

Posting entry layout. In the recency index, a posting is just a post id, because ids are time-sortable: the 64-bit id's high bits are a millisecond timestamp, so ordering by id is ordering by creation time. In the likes index, a posting is (score, postId), where the score is the approximate like count (or its logarithm, see the write deep dive) and the post id breaks ties so that the order is total and stable for pagination.

Why Redis sorted sets for both orders? A Redis list supports append and range reads from either end but not removal by value in O(1) or de-duplication. A sorted set scored by post id gives the same ordering, plus idempotent inserts (re-adding an id is a no-op) and cheap removal for deletions. It costs more memory per entry (a skiplist node plus a hash entry, roughly 50 to 100 bytes per member in practice, compared with about 8 bytes in a compact array), which is why the hot tier is capped and why the cold tier uses compact compressed arrays instead.

Capped lists. After each insert, the indexer trims the list (ZREMRANGEBYRANK key 0 -10001 keeps the newest or highest 10,000). Trimmed postings are not lost: they live in the cold segments built from the same event log.

Deletions and edits. Deleting a post removes its id from every term's lists (the indexer re-tokenises the stored text to know which terms) and adds it to a small tombstone set checked at query time, because cold segments are immutable and cannot be edited in place. Editing a post is a delete of the old terms plus an insert of the new ones, computed as a diff of the old and new term sets.

Deep Dives#

1. Building the inverted index: from Redis keys to segments#

The Redis design is easy to explain and works for the hot tier. But real search engines build indexes differently, and an advanced interviewer may ask how you would store hundreds of terabytes of postings efficiently. There are three broad approaches.

Basic: one mutable key per term

Each term is a key in a key-value store; each new post appends to many keys. This is what we built in the high-level design.

  • Good: simple, immediately consistent, sub-millisecond lookups.
  • Bad: each post causes 50 or more random writes to different keys (often on different machines). Memory per posting is high in general-purpose structures (tens of bytes per entry in a sorted set). Very common terms create giant keys that are slow to read, replicate and move.

Better: batch postings in memory, flush to sorted runs

Collect a few seconds of new posts in an in-memory buffer on each index node, building a small inverted index for just those posts (term to list of new ids). Periodically freeze the buffer and write it as an immutable segment: a file with a sorted term dictionary and, for each term, its posting list. Queries consult the live buffer plus all segments and merge the results.

This is the design of Lucene (the library inside Elasticsearch and Solr) and of most search engines. It is structurally the same idea as an LSM tree (log-structured merge tree) in databases: absorb writes in memory, write sorted immutable files, merge them in the background. See Storage Engines: B-Trees vs LSM Trees.

  • Good: writes become sequential and batched. One segment flush writes thousands of posts' postings in one pass. Immutable segments can be compressed aggressively, cached by the operating system, copied to replicas and uploaded to blob storage as plain files.
  • Bad: a query must check many segments, so a background merge process combines small segments into larger ones, like LSM compaction. Deletions cannot edit an immutable segment; they are recorded in a per-segment deletion bitmap and physically removed at the next merge.

Best: tiered segments with specialised in-memory structures for the newest data

Combine both. The newest few minutes of posts live in an in-memory, append-optimised index designed for concurrent reads during writes. Older data lives in compressed immutable segments, merged into progressively larger tiers (minutes, hours, days, months). The oldest and coldest segments live in blob storage and are fetched on demand.

Twitter's real-time search engine took this approach. Its design is described in "Earlybird: Real-Time Search at Twitter" (Busch, Gade, Larson, Lok, Luckenbill and Lin, ICDE 2012). Earlybird kept recent tweets in in-memory index segments with posting lists stored newest-first, used a single writer thread per segment with many concurrent reader threads (so no locks on the read path), and made tweets searchable within seconds of posting. Once a segment filled, it became read-only and was optimised. The reverse-chronological layout matters: queries sorted by recency read the beginning of each posting list and stop early once they have enough results.

Inside a segment. A segment contains:

  • A term dictionary: all terms in the segment, sorted, with pointers to their posting lists. Lucene stores this as a finite state transducer (FST), a compact automaton that shares prefixes and suffixes, so millions of terms fit in a few megabytes and a lookup costs a handful of memory accesses.
  • Posting lists: for each term, the sorted list of document numbers. Inside a segment, documents get small local numbers (0, 1, 2, ...), which compress far better than 64-bit global post ids.
  • Optionally positions (where in the post the term occurs, for phrase queries) and per-document values (such as creation time or like score, stored column-wise for fast sorting).
  • A deletion bitmap marking documents deleted since the segment was written.

Compressing posting lists. Sorted integer lists compress extremely well by storing gaps (deltas) instead of values. For a list [1000, 1003, 1004, 1010], store [1000, 3, 1, 6]. Small gaps need few bits:

  • Variable-byte encoding uses 7 bits per byte plus a continuation bit; gaps under 128 cost one byte.
  • Block encodings such as PForDelta (from "Super-Scalar RAM-CPU Cache Compression", Zukowski, Héman, Nes and Boncz, ICDE 2006) pack 128 gaps at a fixed bit width chosen for the block, with exceptions stored separately. Decoding is branch-free and very fast. Lucene uses a related fixed-width block scheme.
  • Elias-Fano encoding stores monotone sequences in close to the information-theoretic minimum while supporting fast skipping, and is used in several modern engines.
  • Roaring bitmaps (Chambi, Lemire, Kaser and Godin, "Better bitmap performance with Roaring bitmaps", Software: Practice and Experience, 2016) split the id space into chunks of 65,536 and choose per chunk between a sorted array, a bitmap or run-length encoding. They are excellent for very dense lists (stop words, filters) and for fast intersections.

A worked example: a term that appears in 1 of every 100 posts has an average gap of 100 within a segment, which needs about 7 bits. A typical posting costs 1 byte instead of 8, which is the 8x saving used in the capacity estimate. Rarer terms have larger gaps but also far fewer postings. The classic survey "Inverted Files for Text Search Engines" (Zobel and Moffat, ACM Computing Surveys, 2006) covers these encodings and their trade-offs in depth.

Skip pointers. Long lists store a skip entry every 128 or so postings ("the 128th posting is document 51,200, at byte offset 140"). An intersection that needs to jump to document 1,000,000 can skip whole blocks without decoding them, which turns intersections from linear in the longer list into roughly proportional to the shorter one.

In an interview without Elasticsearch, the natural answer is: Redis sorted sets for a capped hot tier (fast to explain), plus immutable compressed segments in blob storage for the full history, built by a batch or streaming job from the event log. Mention that this two-tier structure is how real engines (Lucene, Earlybird) organise data, which shows you know why the simple version eventually breaks.

2. Ingestion via change data capture and streams#

How does a new post get from the Post Service into the index, reliably, at 10,000 posts per second with bursts?

Bad: the Post Service calls the indexer synchronously

The Post Service writes to its database and then calls the Ingestion Service. If the call fails or times out, the post is saved but never indexed, or it is retried and indexed twice. A slow index slows down posting itself. And a burst of posts overloads the indexer with no buffer, so events can be lost. This is the dual-write problem: two systems updated without a shared transaction will eventually disagree.

Good: publish events to a durable log

The Post Service publishes post.created to Kafka after writing to its database. Indexers consume at their own pace. Kafka buffers bursts (a backlog of minutes is fine within the freshness budget, and it is far better than dropping posts). Partitioning the topic by post id spreads load over many indexer instances, and each partition is processed in order, so a post's create, edit and delete events cannot be reordered.

The remaining gap: the database write and the publish are still two separate actions. A crash between them loses the event.

Great: change data capture or the transactional outbox

Make the database itself the source of events:

  • Change data capture (CDC). A connector such as Debezium reads the database's replication log (the MySQL binlog or PostgreSQL write-ahead log) and publishes every committed insert, update and delete to Kafka. If it is in the database, it will be published, in commit order. Nothing in the Post Service changes.
  • Transactional outbox. The Post Service writes the post row and an outbox row in the same transaction; a relay process publishes outbox rows to Kafka and marks them sent. This gives the same guarantee with more control over the event's shape.

Either way, delivery is at least once: after a crash, some events are delivered again. Indexers must be idempotent (inserting an id that is already present is a no-op; applying "score = 16" twice is harmless, whereas "score += 1" twice is not, which is one reason the aggregator emits absolute values). See Change Data Capture and the Outbox Pattern.

Scaling ingestion. The indexer group scales by adding partitions and consumers. Each indexer batches by destination shard: it collects, say, 100 ms of events, groups the resulting postings by shard, and sends one pipelined request per shard. Batching turns 1 million individual index writes per second into perhaps tens of thousands of bulk requests per second, and the shards apply them in bulk too. See Pattern: Scaling Writes.

Backpressure. If shards slow down, indexers slow their consumption; the Kafka backlog grows; freshness degrades gracefully from seconds towards the one-minute budget. Alert on consumer lag measured in time (age of the oldest unprocessed event), not just message count, because time is what the freshness requirement is stated in.

Replay as a feature. Because Kafka retains the log (days or weeks, or forever with tiered storage), a new index format can be built by replaying the topic from the beginning into a fresh cluster, and a corrupted shard can be rebuilt from the log plus the latest snapshot. Kafka's log compaction, which keeps the latest event per key, can retain a full "current state of every post" stream without keeping every intermediate edit.

Two pipelines, one log. The same posts topic feeds both a streaming path (indexers updating the hot tier within seconds) and a batch path (a job that builds large, optimally compressed segments for the cold tier every hour or day). This mirrors the lambda architecture idea: a fast, approximate path for freshness and a slow, efficient path for completeness, both derived from one log. See Batch vs Stream Processing.

3. Sharding the index: by document or by term#

A capped hot index may fit on a few dozen machines; the full history needs hundreds or thousands. How do we split it? There are two fundamentally different answers, and knowing the difference is one of the main things this question tests. See Partitioning and Sharding.

Option A: partition by term (global index)

Each shard owns a subset of terms and holds the complete posting list for each of them. hash("taylor") mod N decides that shard 17 holds every post containing "taylor".

  • Single-term queries touch one shard. Cheap and fast.
  • Multi-term queries touch one shard per term. For "taylor swift", we fetch both lists from two shards and intersect in the search service, which means shipping potentially large lists across the network.
  • Writes are scattered: one post with 50 terms writes to up to 50 shards. Every post touches many machines.
  • Hot terms create hot shards. During a breaking story, one term's shard receives a large share of all queries and writes. Splitting a single term across machines is awkward because the term is the unit of partitioning.
  • Load imbalance. Term frequencies follow Zipf's law, so a few terms have enormous lists. Even with good hashing, the shard that drew "the" or "love" is much bigger than average.

Option B: partition by document (local index)

Each shard owns a subset of posts and builds a complete, small inverted index over just those posts. hash(postId) mod N, or ranges of time, decides which shard indexes a post.

  • Writes are local. All 50 terms of a post go to one shard, in one batch. Ingestion is much simpler and cheaper.
  • Every query goes to every shard (scatter-gather). Each shard returns its local top K; the broker merges them into a global top K. Work per query grows with the number of shards.
  • Multi-term queries are local. Each shard intersects "taylor" and "swift" over its own posts, never shipping lists across the network.
  • Load is naturally balanced. Each shard holds a random sample of posts, so every term is spread evenly. A hot term heats every shard a little rather than one shard a lot.
  • Tail latency. A query is as slow as the slowest of N shards. With 1,000 shards, a 1-in-1,000 slow response happens on most queries. This is the main cost (see the tail latency deep dive).

Web search engines have long used document partitioning. "Web Search for a Planet: The Google Cluster Architecture" (Barroso, Dean and Hölzle, IEEE Micro, 2003) describes index servers each holding a random subset of documents (an "index shard"), with every query sent to one replica of every shard and the results merged. Elasticsearch and Solr also partition by document by default.

AspectPartition by termPartition by document
Shards touched per single-term query1All
Shards touched per post writeUp to one per term1
Multi-term intersectionAcross the networkLocal on each shard
Hot-term behaviourOne hot shardSpread evenly
Adding capacityMove termsMove posts or add time ranges
Main riskHot spots, huge listsTail latency of fan-out
Typical useSmall, simple key-value indexesMost production search engines

Option C, often best: time-partitioned document shards

Post search has a property web search lacks: recency matters, and posts arrive in time order. So partition by document, using time as the primary dimension:

  • Each time tier (the last hour, the last day, the last week, older months) is a separate set of shards, each document-partitioned within the tier.
  • New posts go only to the newest tier, so writes hit a small, hot set of machines whose indexes are small and fit in memory.
  • A recency query searches the newest tier first. If it finds enough results (25 for page one), it stops without touching older tiers. Most recency queries for popular terms are answered by the newest tier alone.
  • A likes query searches a dedicated top-likes index (posts that have crossed a meaningful like threshold), which is far smaller than the full corpus.
  • Old tiers are immutable, so they can be heavily compressed, stored on SSD or in blob storage, and replicated less.

Hybrid: term partitioning for the hottest terms. Some systems combine both: document partitioning for general queries, plus a small term-partitioned cache of precomputed top results for the most popular queries or terms. The results cache in the next deep dives plays exactly that role.

Replication. Every shard has several replicas (say three). Replicas serve reads in parallel, so replica count scales query throughput, and shard count scales data size. These are two independent knobs: if the index grows, add shards; if queries grow, add replicas. Indexers write to a primary per shard which replicates to the others, or they write to all replicas from the log, since each replica can consume the same Kafka partition independently. See Database Replication.

Rebalancing. Hash-mod-N placement moves almost every key when N changes. Use many more logical shards than machines (for example 4,096 logical shards on 256 machines) and move logical shards between machines as the cluster grows, or use consistent hashing. With time tiers, rebalancing is rarely needed: new tiers are simply created at the right size. See Consistent Hashing.

Facebook's own design. Facebook described its search infrastructure in "Unicorn: A System for Searching the Social Graph" (Curtiss et al., VLDB 2013). Unicorn is an in-memory inverted index over the social graph, partitioned by document (here, by entity), with racks of index servers queried through aggregators that fan out and merge. It supports set operations (and, or, difference) and graph-aware operators such as "friends of" applied over posting lists. It was built for typeahead and graph search, but it illustrates the same document-partitioned, aggregator-based architecture used here.

4. Taming the like flood#

Likes arrive at 100,000 per second. If each like updates the post's score in every term's likes index, that is about 5 million sorted-set updates per second, spread over many shards. How do we cut it down without breaking "sort by likes"?

Bad: update every index entry on every like

Correct and simple, but it creates the largest load in the system, much larger than post creation, purely to keep an ordering perfectly up to date. Viral posts make it worse: a post receiving 10,000 likes per minute generates 500,000 sorted-set updates per minute, all on the same keys.

Good: batch likes per post

A like batcher consumes like events and aggregates them per post over a window (say 30 seconds), then emits one update: "post 7362917461: +500". A viral post's 500 likes per window become 1 update. Flink or Kafka Streams does this naturally with keyed tumbling windows. See Apache Flink and Stream Processing.

The weakness: most posts are not viral. A post receiving one like per minute receives 1,440 likes per day, and with a 30-second window it still needs about 1,440 updates per day: no saving at all, plus extra infrastructure. Batching helps the head of the distribution, not the long tail where most of the volume lives.

Great: milestones plus two-stage ranking

Observe that ranking does not need exact counts. A post with 10,000 likes belongs ahead of a post with 3 likes; whether it has 10,000 or 10,017 changes little. So:

  1. Stage one, approximate index. Update a post's score in the likes index only when its count crosses a milestone, such as a power of two (1, 2, 4, 8, ..., 1,024, ...) or a power of ten. A post with 1,000 likes has caused about 10 index updates (log2 of 1,000 ≈ 10) instead of 1,000. The index score is effectively the logarithm of the like count, so name it approxLikes or logLikes to make its meaning clear to other engineers.
  2. Stage two, exact re-rank. At query time, fetch the top 2N candidates (50 for a page of 25) from the approximate index, then fetch their exact current counts from the like count store (one batched key-value read) and sort precisely.

Storage holds an approximation; the user sees exact, fresh results. Why fetch 2N? Posts near a milestone boundary may be slightly misordered. A post with 1,023 likes has score 512 while one with 1,024 has score 1,024, so within a factor of two the order is fuzzy. Over-fetching ensures that the true top N is almost always inside the candidate set. The over-fetch factor is a tunable knob: measure how often the exact top 25 differs from the top 25 of a 4N fetch, and choose the smallest factor that keeps the error rate acceptable.

How much does it save? Suppose half of posts get no likes and the other half average 20. A post with 20 likes crosses milestones 1, 2, 4, 8, 16, which is 5 updates instead of 20. Over a day that is about 500 million posts × 5 = 2.5 billion milestone events, or about 25,000 per second, each touching about 50 term entries: about 1.25 million index updates per second instead of 5 million. With powers of ten instead of two (1, 10, 100, ...), it drops to about 2 milestones per liked post, roughly 500,000 index updates per second, at the cost of fuzzier ordering and a larger over-fetch factor. Combining milestones with the batcher (so a viral post crossing several milestones in one window emits one update) trims it further.

This two-stage pattern, a cheap approximate retrieval stage followed by an accurate, more expensive re-ranking of a small candidate set, is everywhere in information retrieval and recommendation systems. Web search engines retrieve thousands of candidates with simple scoring and re-rank the top few hundred with expensive models; recommendation systems retrieve from a vector index and re-rank with a heavy model. It is worth naming explicitly in the interview.

Unlikes and decreasing counts. If a count falls back below a milestone, the aggregator can either emit a downward update or simply let the index stay slightly high, since re-ranking uses exact counts anyway. Most systems ignore downward crossings except for large drops (such as removal of fraudulent likes), which are handled by a periodic reconciliation job that recomputes scores from the like count store.

Where the exact counts live. The like count store is a simple key-value map from post id to count, updated 100,000 times per second. Shard it by post id; for very hot posts, use sharded counters (split a counter into several sub-keys and sum on read) or accept the aggregator's batching, which already turns a viral post's thousands of likes per second into one write per window. See Pattern: Dealing with Contention.

5. Ranking by recency and likes across shards#

With a document-partitioned, time-tiered index, how is one ranked page actually produced? And how do we paginate consistently?

Recency queries: early termination by tier. Each shard's recency list is already sorted newest first. For "taylor" sorted by recency, page one:

  1. The broker sends "top 25 newest ids for taylor" to every shard of the newest tier.
  2. Each shard returns up to 25 ids from the head of its list: one memory read, microseconds.
  3. The broker performs a k-way merge of the sorted lists using a heap (O(K log S) for K results from S shards) and keeps the 25 newest.
  4. If the merge has fewer than 25, the broker continues to the next tier with a cursor of "older than the oldest id seen".

The cursor for the next page is simply the smallest id returned. Page two asks every shard for "the newest 25 ids older than cursor", which each shard answers with a binary search or a skip within its sorted list. Because ids are time-sortable and immutable, recency pagination is stable: new posts arriving between pages do not shift page two.

Likes queries: top-K merge with a stable snapshot. Each shard returns its local top 2K by approximate score; the broker merges by score and re-ranks with exact counts. Pagination is harder, because scores change between page requests: a post on page one may rise or fall and appear again on page two, or be skipped entirely. Options:

  • Cursor by (score, postId): page two asks for entries with score less than the last score, or equal score and smaller id. Simple, but moving scores can cause occasional duplicates or gaps. De-duplicate on the client using ids already shown.
  • Snapshot the candidate list: on the first page, compute the top 500 candidates, store them in the results cache under a query session id with a TTL of minutes, and serve subsequent pages from that frozen list. Consistent pagination at the cost of a little staleness, and most users never go past page two or three.

Blending recency and popularity. Pure "most liked" favours old posts: a 2019 post with 2 million likes beats yesterday's 50,000-like post forever. Pure recency surfaces spam and trivia. Real products often blend them with a score that decays with age, for example:

score = log2(1 + likes) - age_hours / half_life_hours

With a half-life of 24 hours, a post loses one "doubling" of likes per day of age: yesterday's post with 2,000 likes ties with today's post with 1,000. Hacker News and Reddit popularised variants of this gravity-style decay for ranking stories. Because the score depends on query time, it cannot be stored precisely in the index; the two-stage pattern helps again: retrieve candidates from both the recency index and the likes index, then compute the blended score for the union in the re-ranker.

Text relevance. Sophisticated relevance ranking is out of scope here, but name it. Classic scoring uses BM25, which rewards terms that appear often in a document (with diminishing returns) and terms that are rare across the corpus, normalised by document length. The framework is summarised in "The Probabilistic Relevance Framework: BM25 and Beyond" (Robertson and Zaragoza, Foundations and Trends in Information Retrieval, 2009). For short social posts, term frequency matters little (most words appear once), so recency, engagement and social signals dominate. Personalised ranking, such as boosting posts from friends, uses learning-to-rank models in the re-ranking stage.

Dynamic pruning. When ranking combines many terms over long lists, engines avoid scoring every matching document. WAND (from "Efficient Query Evaluation using a Two-Level Retrieval Process", Broder, Carmel, Herscovici, Soffer and Zien, CIKM 2003) keeps, for each term, an upper bound on the score it can contribute, and skips documents whose best possible total cannot beat the current K-th best result. Block-Max WAND (Ding and Suel, SIGIR 2011) stores the bound per block of postings, so whole blocks are skipped. For our recency and likes orders, sorted lists already give a simpler form of early termination: read from the head and stop after K.

6. Handling high read volume: caching hot queries#

Search traffic is 10,000 queries per second on average, but it bursts. When news breaks, millions of people search for the same few words within minutes. Two requirements make caching especially effective here:

  • No personalisation: identical queries have identical answers, so one cached result serves everyone.
  • One-minute freshness: results may be up to a minute stale, so a TTL under a minute is acceptable.

Whenever duplicate requests meet tolerable staleness, think caching. See Pattern: Scaling Reads and Caching Strategies: Cache-Aside, Read-Through, Write-Through, Write-Behind.

Good: a distributed results cache next to the search service

Before running a query, the Search Service looks up results:{normalisedQuery}:{sort}:{cursor} in Redis or Memcached. On a hit, return it; on a miss, run the query and store the result with a TTL. This is the cache-aside pattern.

  • Choose the TTL from the freshness budget. The requirement is that a new post appears within one minute. If indexing takes up to 20 seconds, the cache TTL must be at most about 40 seconds; 30 seconds is a sensible default. TTL plus indexing delay must stay under the budget.
  • Normalise keys aggressively. "Taylor Swift", "taylor swift" and "taylor swift!" must map to one key, or the hit rate collapses. Apply the same tokenisation used for the query plan, sort the terms for commutative queries if word order does not matter, and include every parameter that changes the answer (sort, page cursor, language filter).
  • Hit rates. Query popularity is heavy-tailed. Even modest caches holding the top few million queries typically capture a large share of traffic, and the share rises exactly during the bursts when it matters most, because burst traffic is concentrated on a few queries.

Great: add a CDN in front

Mark search responses cacheable with Cache-Control: public, max-age=30 (and a cache key that includes the full query string). A CDN such as Cloudflare, Akamai, Fastly or Amazon CloudFront caches them at hundreds of edge locations close to users. A hit returns in tens of milliseconds instead of the hundreds needed to cross the internet, the gateway, the search service and the cache. During a burst, each edge location sends at most one request per query per TTL to the origin, so a million users searching "world cup final" in one minute produce at most a few hundred origin requests.

Things to get right:

  • Authentication. If the API requires a login token, the CDN must not vary the cache by token, or every user gets a separate entry. Keep the search response user-independent and authenticate at the edge, or serve search for public content without user-specific data in the response.
  • Stampedes. When a hot entry expires, thousands of simultaneous misses can hit the origin together. Use request coalescing at the CDN (one fetch per key per edge) and at the results cache (a short lock or a "single flight" in the search service), and serve slightly stale content while revalidating (stale-while-revalidate). See Cache Failure Modes: Stampedes, Hot Keys and Penetration.
  • Hot keys in Redis. A single key for "world cup" read 50,000 times per second can overload one Redis node. Keep a small in-process cache in each search server (a few seconds' TTL) for the very hottest keys, or replicate hot keys under several suffixes and pick one at random.
  • Negative caching. Cache empty results too (briefly), so that repeated searches for nonsense strings or attacks do not reach the index.
  • Abuse. Rate-limit per user and IP at the gateway; scrapers paging deep into results bypass caches. Limit maximum page depth. See Rate Limiting and Throttling.

Layered latency. In-process hit: under 1 ms. Results cache hit: 1 to 5 ms plus service overhead. CDN hit: 10 to 50 ms end to end for the user (no trip to the origin at all). Full miss: 80 to 300 ms. Each layer cuts the load on the next by its hit rate, so the index sees only a fraction of raw traffic.

7. Multi-keyword and phrase queries#

Users search "dog", but also "taylor swift" and "all your base are belong to us". Some engines offer a boolean language ("+taylor +swift -red"). Assume the requirement is multi-word phrases. How do we answer them?

Good: intersect, then filter

For "taylor swift" sorted by likes:

  1. Fetch the candidate lists for taylor and swift.
  2. Intersect them: keep ids present in both.
  3. Fetch the text of each surviving post and check that the words really appear adjacent and in order, which rejects "my friend Taylor made a swift exit".
  4. Return the survivors in order.

On a document-partitioned index, each shard does steps 1 to 3 locally and returns only verified matches, which removes the network cost. Intersection of two sorted lists is a merge (linear in their combined length) or, with skip pointers, close to linear in the shorter list: walk the shorter list and skip ahead in the longer one. A useful rule is to process terms from rarest to most common, so the running candidate set shrinks quickly.

The costs: on a term-partitioned index, both lists cross the network, and for two common words they may hold millions of ids (megabytes to intersect within 500 ms). And when two words co-occur often but rarely as a phrase, the filter discards most candidates after expensive text fetches.

Positional index. Step 3 can avoid fetching post text if the index stores positions: for each posting, the word offsets where the term occurs. "taylor" at position 2 and "swift" at position 3 of the same post means adjacency. Positions add perhaps 30 to 50% to index size (more for long documents), but make every phrase query verifiable inside the index. This is what Lucene does for phrase queries.

Great: index bigrams (shingles)

Index word pairs as terms in their own right. The sentence "I saw Taylor Swift at the concert" produces the bigrams i saw, saw taylor, taylor swift, swift at, at the, the concert, in addition to single words. A query for "taylor swift" becomes a single lookup of the taylor swift posting list: no intersection, no filtering. Lucene calls these shingles; the general case of n consecutive words is an n-gram. Longer phrases can be answered by intersecting bigrams ("all your", "your base", "base are") which is far more selective than intersecting single words.

The problem is size. A sentence of n words has n − 1 bigrams, so posting count roughly doubles. Worse, bigrams are far more diverse than words: "swift at" or "the concert" rarely recur, so the vocabulary explodes from perhaps 10 million useful words to hundreds of millions of bigram keys, most of them with tiny lists that are never queried.

Remedy: index only bigrams worth indexing.

  • Use query logs: index bigrams that people actually search for ("taylor swift", "world cup", "new york"). This set is small and changes slowly.
  • Use corpus frequency: index bigrams that occur often enough to make intersection expensive. Rare bigrams are cheap to answer by intersection anyway, because at least one of the words is rare or the positional filter is cheap.
  • Count bigram frequencies cheaply with a count-min sketch (Cormode and Muthukrishnan, "An Improved Data Stream Summary: The Count-Min Sketch and its Applications", Journal of Algorithms, 2005), a small fixed-size table of counters that estimates the frequency of any item with bounded overcount, so we can track hundreds of millions of distinct bigrams in a few hundred megabytes. See Probabilistic Data Structures for Big Data.
  • Fall back to intersection plus filtering when a bigram has no list.

This gives a common pattern: precompute for the expensive, popular cases; compute on demand for the long tail.

Other query features, briefly:

  • Boolean operators. "+taylor -red" is intersection with one list and difference with another. Sorted lists support AND, OR and NOT as merges.
  • Prefix and typeahead. Search-as-you-type needs prefix lookup over the term dictionary (a trie or FST) and a separate, heavily cached index of popular completions. The search autocomplete case study covers this.
  • Fuzzy matching. Out of scope, but mentionable: Levenshtein automata over the term dictionary find terms within edit distance 1 or 2; synonym expansion ("bird" to "ostrich") rewrites the query into an OR of terms.
  • Hashtags and mentions. Indexed as exact terms, often with dedicated, heavily cached lists because they are queried like topics.

8. Freshness: making new posts searchable within a minute#

The requirement is that a new post shows up in search within one minute. Where does the time go, and how do we guarantee it?

The freshness budget. End-to-end delay is the sum of:

StageTypical delayNotes
CDC capture from the database log100 ms to 1 sDepends on connector polling and replication lag.
Kafka produce and consume10 to 100 msPlus any backlog when consumers fall behind.
Indexer batching window100 ms to 1 sLarger batches are more efficient but add delay.
Index visibility0 to 1 sImmediate for Redis; a "refresh" interval for segment-based engines.
Results cache TTLup to 30 sA cached result may predate the post.
CDN TTLup to 30 sOverlaps with the results cache if both are used.

In steady state that is a few seconds plus the cache TTL. To guarantee one minute with two layers of caching, make sure the sum of CDN TTL and results-cache TTL plus indexing delay stays under 60 seconds, or align them so that the CDN fetches from the origin, which itself bypasses the results cache when it is refreshing (for example CDN 20 s, results cache 20 s, indexing budget 15 s).

Near-real-time segment engines. In Lucene-based systems, newly indexed documents become visible only when the in-memory buffer is turned into a searchable segment, an operation Elasticsearch calls a refresh and performs every second by default. Durability is separate: a transaction log (translog) records operations so that a crash does not lose unflushed documents, and a periodic flush (Lucene commit) writes segments to disk durably. That separation, visibility every second and durability on a slower cycle, is how such engines get both freshness and efficient writes. Refreshing more often makes tinier segments and more merge work; less often increases visibility delay. For our budget, a refresh of 1 to 5 seconds is plenty. See Elasticsearch and Search Systems.

Read-your-own-writes for the author. An author who posts and immediately searches for their own words expects to see the post. The global system cannot promise that in milliseconds, but the client can: after posting, the app inserts the new post locally into matching search results for that session, or the search service merges a small "recent posts by this user" lookup into the author's own results. This is a common pattern for hiding eventual consistency from the person most likely to notice it. See Consistency Models.

Monitoring freshness directly. Do not infer freshness from component metrics. Run a canary: a synthetic account posts a unique random token every few seconds, and a prober searches for each token and records how long until it appears. Alert when the p99 time-to-searchable exceeds, say, 45 seconds, which leaves margin before the 60-second objective is breached. See Observability: Logs, Metrics and Traces.

When the pipeline falls behind. During a major event, posting rates may spike tenfold. Kafka absorbs the backlog; indexers autoscale on consumer lag; shards accept bulk writes. If lag still exceeds the budget, prioritise: index the text of new posts first (freshness) and defer like-score updates and cold-tier segment building (which nobody notices for a few minutes). Shedding the less time-critical work protects the guarantee users actually see.

9. Optimising storage: caps, tiers and compression#

We estimated 3.6 PB of raw posts and hundreds of terabytes of compressed postings. Users, however, look at a vanishingly small fraction: page one of popular queries over recent posts. How do we stop paying memory prices for data nobody reads?

Cap posting lists in the hot tier. No one needs all 10 million posts containing "mark" in memory. Keep the newest 10,000 in the recency index and the top 10,000 in the likes index. That bounds hot memory by vocabulary, not history: from hundreds of terabytes to under a terabyte per index (see the capacity section). Postings beyond the cap still exist in colder tiers, so the "every post is discoverable" requirement holds.

Tier by query frequency. Most terms are almost never searched: misspellings, rare names, random strings. Use search analytics to decide:

  1. A daily or weekly batch job computes, per term, how often it was queried in the last 30 days.
  2. Terms queried rarely or never have their posting lists moved out of memory into blob storage (Amazon S3, Cloudflare R2, Google Cloud Storage), as compressed objects keyed by term or grouped into segment files.
  3. At query time, the search service first looks in the hot in-memory index. On a miss for a term, it fetches the term's list from blob storage, with a small latency penalty (tens of milliseconds for an object read in the same region), and optionally promotes it back into memory if it becomes popular.

The requirement "old or unpopular posts may take longer" is exactly the permission this design needs.

Cost arithmetic. Approximate list prices: memory costs of the order of $3 to $5 per GB-month in cloud instances, SSD perhaps $0.08 to $0.20 per GB-month, standard object storage about $0.02 per GB-month, and archive tiers a fraction of a cent. Keeping 300 TB in memory with three replicas would cost several million dollars a month; keeping 1 TB hot plus 300 TB in object storage costs a small fraction of that. Tiering is not an optimisation at this scale; it is what makes the design affordable. See Data Lifecycle, Tiering and Retention.

Compress everything that is immutable. Cold segments use delta plus block encodings (about 1 byte per posting), and the posts themselves use general compression such as Zstandard. Hot structures trade memory for speed; cold ones trade a little CPU for large savings.

Drop what the product does not need. Do we need positions for posts older than a year? Do we need stop words in the cold tier? Do we need the likes order for posts that never received a like? Each "no" removes a large slice of storage. For example, posts with zero likes (perhaps half of all posts) need not appear in the likes index at all: they can never rank above a liked post, and "sort by likes" pages deep enough to reach them are vanishingly rare.

Segment caching on index nodes. Even the SSD tier benefits from the operating system's page cache: frequently accessed segment blocks stay in RAM automatically. Size the machines so that the working set of hot blocks fits in memory, and let the rest sit on disk.

10. Scatter-gather, tail latency and availability#

Document partitioning means every query fans out to many shards. A query's latency is the maximum of its shards' latencies, so rare slow responses dominate.

The arithmetic of fan-out. If each shard answers within 10 ms 99% of the time, and a query touches 100 shards, the probability that all 100 are fast is 0.99^100 ≈ 37%. So 63% of queries see at least one slow shard. This is the central point of "The Tail at Scale" (Dean and Barroso, Communications of the ACM, 2013). Fan-out turns a per-shard p99 into a typical-case problem.

Techniques:

  • Fewer, bigger shards for the hot tier. Fan-out to 32 shards is easier to control than fan-out to 1,000. Time tiering helps: most queries touch only the small newest tier.
  • Hedged requests. If a shard has not answered within, say, its p95 latency, send the same request to another replica and use whichever answers first. This adds only a few percent of extra load but cuts tail latency sharply.
  • Tied requests. Send to two replicas at once, each told about the other, so the second cancels when the first starts executing.
  • Deadlines and partial results. The broker waits up to a deadline (such as 150 ms) and returns whatever it has, marking the result as possibly incomplete. For a top-25 query over a random document partition, missing 1 of 64 shards loses about 1.5% of candidates, which rarely changes page one. Search engines routinely trade a sliver of completeness for predictable latency.
  • Two-level aggregation. For very many shards, use rack-level aggregators that merge their rack's results before a top-level broker merges the racks. This keeps per-node fan-in bounded and limits cross-rack traffic. Unicorn and web search engines use this tree structure.
  • Replica health and load balancing. Route to the least-loaded replica (for example "power of two random choices": pick two at random and send to the less busy). Pull slow replicas out automatically. See Load Balancing.
  • Isolate expensive queries. A query that intersects two huge lists, or pages very deep, can slow a shard for everyone. Cap work per query (maximum postings scanned), give expensive queries a separate pool, and cache their results.

Availability. With three replicas per shard, losing a machine reduces capacity but not coverage. Losing all replicas of a shard (a rack failure if replicas were not spread across racks and zones) makes a slice of posts temporarily invisible, so place replicas in different failure domains. Because the index is derived data, a lost shard is rebuilt from the latest snapshot plus a Kafka replay. For a cold-tier shard, recovery is just re-downloading segments from blob storage. See Resilience Patterns: Timeouts, Retries and Circuit Breakers.

Graceful degradation, in order: serve stale cached results; drop the cold tiers (search only recent posts); return partial results from the shards that answered; disable the likes sort and offer only recency, which is cheaper; and finally serve a friendly error. Each step keeps the product usable while protecting the core.

11. Deletions, privacy and personalisation#

These were declared out of scope, but a strong candidate explains what would change, because in a real social network they are not optional.

Deletions must be fast and complete. When a user deletes a post, it must vanish from search quickly, for privacy and often for legal reasons.

  • Hot tier: the indexer consumes post.deleted, re-derives the post's terms from the last known text (kept in a small "indexed terms" record per post, so it does not depend on the deleted row), and removes the id from each list.
  • Immutable segments: add the id to the segment's deletion bitmap, or to a global tombstone set consulted on every query. Physical removal happens at the next merge or segment rebuild.
  • Caches: cached results containing the post may live for up to the TTL. Either accept that window (seconds), or filter every result page against the tombstone set during hydration, which is cheap because hydration fetches posts anyway and a deleted post simply fails to hydrate.
  • Defence in depth: hydration from the Post Service is the final check. A post that no longer exists, or that the viewer may not see, is dropped before the response is built.

Privacy: who may see what. On Facebook, a post may be public, friends-only, friends-of-friends, or visible to a custom list. Search must never reveal a post the viewer cannot see, not even by its snippet or its presence in a count.

  • Post-filtering retrieves candidates and drops those the viewer cannot see. It is simple, but if the viewer can see only a small fraction of matches (most posts are not public), the engine may scan thousands of candidates to fill one page.
  • Pre-filtering in the index adds visibility terms to postings: public posts carry a vis:public term; friends-only posts carry vis:friends_of:{authorId}. A query for viewer V becomes taylor AND (vis:public OR author IN friends(V)). Facebook's Unicorn paper describes exactly this kind of set algebra over posting lists, including operators that expand "friends of V" into a list of author ids that is then used to constrain the result set.
  • Partition by audience: a separate index for public posts (small, cacheable, globally shared) and per-user or per-friend-cluster indexes for restricted posts (searched with the viewer's friend list as a filter). Results from both are merged.
  • Never cache personalised results in shared caches or the CDN. Cache the public portion globally and the private portion per user, if at all.

Personalisation changes the caching story. Once results depend on the viewer (friends' posts first, language, location, interests), identical queries no longer have identical answers, and the CDN and shared results cache lose most of their value. A common design keeps the shared, cacheable layer for candidate retrieval (public posts for "taylor swift", top 500 by approximate likes) and personalises only in the re-ranking stage, which runs per request on a small candidate set. That preserves most of the caching benefit.

Abuse and integrity. Search results are a target for spam ("taylor swift free tickets" posted by bots). Integrity classifiers score posts at ingestion; low-quality or spam posts are indexed with a penalty or excluded from popular-query results. Like counts can be inflated by fake accounts, which is another reason the likes index tolerates approximate, periodically reconciled scores.

12. Reindexing, schema changes and multiple regions#

Changing the tokenizer is a reindex. If you add stemming, change how hashtags are split, or add bigrams, every existing posting list is wrong for the new query pipeline. Because the index is derived, the procedure is:

  1. Build a new index (version 2) alongside the old one, by replaying the post log or scanning the post database in bulk, with the new tokenizer.
  2. While it builds, the live stream writes to both indexes (dual writing from the indexers), so version 2 is current when the backfill finishes.
  3. Shadow traffic: send a copy of real queries to version 2, compare results and latency, and fix surprises.
  4. Cut over queries gradually (1%, 10%, 100%) behind a flag, then retire version 1.

Rebuilding hundreds of terabytes takes days, so the backfill is a large batch job (Spark or a MapReduce-style pipeline: map each post to (term, postId) pairs, shuffle by term or by shard, write sorted, compressed segments). This is exactly how indexes were built in the original MapReduce paper (Dean and Ghemawat, "MapReduce: Simplified Data Processing on Large Clusters", OSDI 2004), which used inverted index construction as a motivating example. See Online Data Migrations and Schema Evolution.

Index aliases. Queries address a logical alias (posts-search) that points to a physical index version, so cut-over and rollback are a pointer swap. Elasticsearch has aliases for exactly this; a home-grown system keeps the mapping in the coordination service.

Multiple regions. Users are worldwide; searching across an ocean adds 100 to 200 ms. Options:

  • Full index in every region. Each region consumes the global post log (replicated with Kafka MirrorMaker or a similar tool) and builds its own complete index. Queries are local and fast; freshness for posts written in another region includes the cross-region replication delay (typically under a few seconds). Cost: every region stores everything, but the hot tier is small and the cold tier can be shared in a multi-region bucket.
  • Hot tier everywhere, cold tier in one or two regions. Recent and popular data is local; rare deep queries cross regions with a latency penalty, which the requirements allow.
  • Regional affinity for content: index each region's posts locally and query other regions only for global queries. This is more complex and rarely worth it for a global social network where content crosses borders constantly.

Because the index is derived and eventually consistent, multi-region search is much easier than multi-region writes to the source of truth: each region simply follows the same log. See Multi-Region and Global Data.

Bottlenecks and Failure Modes#

Failure / hotspotImpactMitigation
Full-text scan instead of an indexQueries take minutes; sharding barely helpsInverted index: term to posting list, cost proportional to the answer size
Request-time sorting of huge match setsHundreds of MB per query, seconds of sortingOne pre-sorted index per order (recency list, likes sorted set), top-K reads
Like updates to every term's indexAbout 5 million index writes per secondMilestone updates of approximate scores, per-post batching, exact re-rank of 2N candidates
Dual writes from the Post ServicePosts saved but never indexed, or indexed twiceCDC or transactional outbox into Kafka, idempotent indexers, offsets committed after writes
Ingestion burst during a major eventIndex lag grows past the freshness budgetKafka buffering, autoscaling on time lag, bulk writes per shard, defer like and cold-tier work
Hot term on a term-partitioned shardOne shard overloaded for reads and writesDocument partitioning, replicas, results cache, in-process cache for the hottest keys
Fan-out tail latencyp99 dominated by the slowest of many shardsTime-tiered shards, hedged requests, deadlines with partial results, two-level aggregation
Cache stampede on a hot queryOrigin and index flooded when an entry expiresCDN and service-level request coalescing, stale-while-revalidate, jittered TTLs
Unbounded posting lists for common wordsHuge keys, slow reads and replication, memory blow-upCaps in the hot tier, compressed immutable segments, tiering by query frequency
Phrase queries over common wordsLarge intersections and expensive filteringRarest-first intersection with skips, positional index, selective bigram index guided by logs and sketches
Deleted or private posts appearingPrivacy breach, legal exposureTombstones checked at query time, removal from hot lists, hydration as the final visibility check
Index node or shard lossSlice of posts temporarily invisible, reduced capacityReplicas across zones, rebuild from snapshot plus log replay, degrade to partial results

What Interviewers Expect#

Mid-level#

  • Clear requirements, including what is out of scope, and a working design with both sides: ingestion and query.
  • Recognise that LIKE '%word%' scanning cannot work and propose an inverted index, explaining what it is.
  • Clear API endpoints and data model; cursor pagination.
  • Some answer for sorting by recency and likes, ideally separate indexes, possibly reached with guidance.
  • With prompting, add a cache and explain its eviction policy and TTL.

Senior#

  • Notice from the estimates that the system is write-heavy and that likes, not posts, dominate the index writes.
  • Move quickly through the high-level design to the critical paths: a proper inverted index, two sort orders, and a caching strategy tied to the freshness requirement (TTL plus indexing delay under one minute), with a CDN for hot queries.
  • Scale ingestion with a log (Kafka) partitioned for parallelism, and remove the dual-write problem with CDC or an outbox.
  • Solve the like flood with batching and, better, milestone updates plus exact re-ranking, and explain why batching alone does not help the long tail.
  • Handle multi-word queries with intersection and filtering, then bigrams, and articulate the storage trade-off.

Staff+#

  • Get through several deep dives in depth and bring real insight: document versus term partitioning with clear reasoning about writes, hot terms and tail latency; time-tiered shards with early termination.
  • Explain how real engines store postings: immutable segments, merges, delta and block compression, skip lists, deletion bitmaps, near-real-time refresh separate from durability.
  • Treat cost as a design input: caps, hot and cold tiers in memory, SSD and blob storage, with numbers.
  • Quantify fan-out tail latency and mitigate it with hedging, deadlines and partial results.
  • Cover what changes with privacy and personalisation (pre-filtering versus post-filtering, keeping the cacheable layer for candidate retrieval), reindexing without downtime, freshness canaries, and multi-region replicas from the log.
  • Ideally the interviewer learns something new from the discussion; there are many valid ways to solve this problem, and the strongest candidates explain why they chose theirs.
Deep Dive: The maths of post searchShow

Zipf's law and posting-list sizes. In natural-language text, the frequency of the r-th most common word is roughly proportional to 1/r. The most common word appears about twice as often as the second, three times as often as the third, and so on. Two consequences matter for design:

  • A handful of terms have enormous posting lists (stop words appear in a large fraction of posts), while most of a vocabulary of tens or hundreds of millions of distinct terms appear only a few times.
  • The total number of postings is dominated by common terms, but the number of keys is dominated by rare ones. Caps attack the first; tiering by query frequency attacks the second.

Heaps' law and vocabulary growth. Vocabulary size grows sublinearly with corpus size, roughly V = K × N^β with β between about 0.4 and 0.6 for English text. Doubling the corpus does not double the number of distinct terms, but it never stops growing either: new names, hashtags, typos and slang keep appearing. Social text, with its misspellings and invented words, sits at the high end. This is why the term dictionary must be compact (an FST or a sorted, prefix-compressed array) and why rarely used terms should not occupy expensive memory.

Index size estimate, revisited. With 3.6 trillion posts and 50 distinct terms each, there are 180 trillion postings. Delta encoding inside segments gives average gaps that depend on term frequency. For a term in a fraction f of posts, the average gap is about 1/f, which needs about log2(1/f) bits. Averaged over all postings (weighted towards common terms with small gaps), real engines achieve roughly 4 to 10 bits per posting for document ids alone, before positions. At 8 bits, 180 trillion postings are 180 TB per sort order. Positions might add 50 to 100%.

Intersection cost. Intersecting sorted lists of sizes m ≤ n by a linear merge costs O(m + n). With skips or galloping search (exponentially growing jumps, then binary search), the cost is about O(m log(n/m)), which is much smaller when one list is short. For "taylor" (10 million postings) and "swift" (2 million) on one shard holding 1/64 of the corpus, the lists are about 156,000 and 31,000 entries. A merge touches about 190,000 entries, a few hundred microseconds of CPU; galloping touches far fewer. Across 64 shards in parallel, intersection is fast. Over the network on a term-partitioned index, the same query would move 12 million ids (about 96 MB) to one place, which is why document partitioning wins for multi-term queries.

Milestone savings. Updating at powers of two means a post with L likes causes about log2(L) + 1 index updates instead of L. Summed over posts with a heavy-tailed like distribution, the saving is enormous at the top (a post with 1 million likes causes 21 updates instead of 1 million) and modest at the bottom (a post with 3 likes causes 2 instead of 3). Powers of ten reduce it further at the cost of ranking precision: within a decade, posts are unordered in the index, so the re-ranker must over-fetch more.

How much to over-fetch. If the index score is the like count rounded down to a power of two, any post whose true count is within a factor of two of the N-th result could be misordered relative to it. The re-ranker needs every post whose true count exceeds the N-th true count. A post in the true top N has an index score of at least half the N-th true count. So fetching all candidates with an index score of at least half the N-th score from the first fetch guarantees correctness; in practice, a fixed 2N to 4N fetch covers it for all but pathological distributions, and the error can be measured offline.

Cache hit rate under Zipf. If query popularity follows Zipf with exponent near 1 over Q distinct queries, caching the top C queries captures about ln(C) / ln(Q) of the traffic. With 1 billion distinct queries a day and a cache of 10 million, that is about ln(10^7) / ln(10^9) ≈ 16.1 / 20.7 ≈ 78%. Real query logs deviate from a pure Zipf, and a TTL under a minute means only queries repeated within the TTL hit. But during bursts, when traffic concentrates on a few queries, hit rates rise towards 95% or more. (Breslau, Cao, Fan, Phillips and Shenker analysed this kind of Zipf-like popularity for web caching in "Web Caching and Zipf-like Distributions: Evidence and Implications", INFOCOM 1999.)

Fan-out probabilities. With per-shard probability p of being slow and S shards, the probability a query is slow is 1 − (1 − p)^S. With p = 1% and S = 64, that is 47%. With hedging after the p95 latency, the per-shard slow probability falls to about p × (chance the hedge is also slow), roughly 0.01 × 0.05 = 0.05% if replicas fail independently, and the query-level slow probability falls to about 3%.

Freshness budget as a sum of percentiles. Delays add, but percentiles do not add linearly; the p99 of a sum is less than the sum of p99s when stages are independent. Measure end to end with the canary rather than summing component p99s, which is pessimistic, or component medians, which is optimistic.

Deep Dive: How real systems search postsShow

Facebook. "Unicorn: A System for Searching the Social Graph" (Curtiss et al., VLDB 2013) describes Facebook's in-memory, document-partitioned inverted index over the social graph. Index servers hold posting lists for terms and for graph edges (such as "friends of user X"), and aggregators fan out queries and merge results. Its query language composes set operations over posting lists, and it supports operators that apply one query's results as input to another (for example, "people who like pages liked by my friends"). The paper also discusses privacy: results carry enough information for visibility checks to be applied before anything is shown to the searcher.

Twitter. "Earlybird: Real-Time Search at Twitter" (Busch et al., ICDE 2012) describes the in-memory real-time index: tweets partitioned across clusters, posting lists organised so that newest tweets are found first, a single-writer and many-readers concurrency model that avoids locks on the read path, and searchability within seconds of posting. Twitter later wrote about extending search to the full archive of tweets with a separate, SSD-based index tier, which is the hot-and-cold tiering idea applied in practice.

LinkedIn. LinkedIn has described its search architecture, Galene, built on Lucene with offline index building in Hadoop, live updates layered on top of offline-built base indexes, and a federated layer that combines verticals (people, jobs, posts). Again: a batch-built base index for efficiency plus a real-time layer for freshness.

Lucene, Elasticsearch, OpenSearch and Solr. Most companies that do not build their own engine run one of these. They implement every mechanism in this case study: immutable segments with merges, compressed posting lists with skips, positions for phrases, shingle filters for bigrams, near-real-time refresh with a translog for durability, document-partitioned shards with replicas, scatter-gather query execution, index aliases for zero-downtime reindexing, and hot, warm and cold tiers. When an interviewer allows them, use one; when they do not, describe the same ideas in your own components. See Elasticsearch and Search Systems.

Web search engines. Google's early cluster architecture (Barroso, Dean and Hölzle, 2003) partitioned the index by document across many index servers, with each query sent to all shards and a separate tier of document servers producing snippets. Jeff Dean's WSDM 2009 keynote, "Challenges in Building Large-Scale Information Retrieval Systems", traced how Google's index moved from disk to memory, how encodings evolved for faster decoding, and how update latency shrank from monthly to minutes. The web search engine case study goes further into crawling, link-based ranking and serving tiers.

Lessons that recur across all of them. Partition by document. Keep the newest data in a write-optimised in-memory structure. Build large, compressed, immutable segments for the rest, often in batch. Separate visibility from durability. Use a cheap first-stage retrieval and an expensive second-stage ranker. Treat the index as rebuildable derived data.

Deep Dive: Following a query through the engineShow

Take the query Taylor Swift concert sorted by recency, issued during a tour announcement.

  1. Edge. The CDN normalises the cache key (query string lowercased by a rule at the edge) and misses, because the announcement made this a new query.
  2. Gateway. The token is validated; the user's rate-limit bucket has room.
  3. Parse and plan. The search service tokenises to taylor, swift, concert. It looks up the bigram dictionary: taylor swift is indexed (it is a popular query), swift concert is not. The plan is list(taylor swift) AND list(concert), with adjacency verification only for the second pair if the user quoted the phrase. Since they did not, plain intersection is fine.
  4. Results cache. Miss.
  5. Broker. Sends the plan to the 64 shards of tier 0 (last 24 hours) with a deadline of 120 ms, asking each for its 25 newest matches.
  6. Shard execution. Each shard has taylor swift (about 40,000 local postings today, it is a big day) and concert (about 15,000). It walks the shorter list from the newest end, galloping in the longer list. It finds 25 matches after examining a few hundred entries, because both terms are hot today, and returns ids with timestamps. About 1 to 3 ms of work.
  7. Merge. The broker merges 64 lists of up to 25 into the newest 25. One shard is slow; a hedged request to its replica answers in 18 ms.
  8. Hydrate. The service fetches 25 posts from the Post Service cache (a multi-get), drops one that was deleted a few seconds ago, and pulls one extra from the merge buffer to fill the page.
  9. Respond and cache. The response, with a cursor equal to the oldest returned id, is stored in the results cache for 30 seconds and sent with Cache-Control: public, max-age=20. Total: about 70 ms at the origin.
  10. The next million users searching the same phrase in the next minute are served from CDN edges and the results cache. The index sees a few hundred requests for this query instead of a million.
Deep Dive: Walking through failuresShow
  1. An indexer crashes after writing to half the shards. It had not committed its Kafka offset, so the event is redelivered to the replacement consumer, which repeats all writes. Inserts are idempotent, so the shards that already had the posting are unchanged.
  2. CDC connector stalls (database failover changed the log position). Kafka stops receiving post events; freshness canaries alert within a minute. The connector resumes from its stored log position after the failover, and the backlog drains. No posts are lost because the database log is the source.
  3. Like aggregator restarts and loses in-memory window state. On restart it rebuilds counts from the like count store (which holds exact totals) and resumes from its committed offset. Milestones might be re-emitted, which is harmless because they carry absolute scores.
  4. A hot query stampedes when its cache entry expires. Request coalescing at the CDN and single-flight in the search service ensure one recomputation; stale-while-revalidate serves the old entry meanwhile.
  5. A shard's replicas all fail in one zone. Replicas in other zones serve; if all replicas of one shard are lost, queries return partial results (missing about 1/64 of candidates) while the shard is rebuilt from a snapshot and log replay.
  6. The blob store for cold segments is degraded. Queries that need old posts time out on that tier; the broker returns recent results with a flag, and deep pagination is temporarily disabled. Hot-tier traffic is unaffected.
  7. A bad tokenizer release stops splitting hashtags. Queries for #worldcup return almost nothing. Shadow testing should catch this before cut-over; if not, the index alias is flipped back to the previous version, and posts indexed during the bad window are replayed from the log.
  8. A spam wave floods a trending query with junk posts. Integrity scoring at ingestion demotes them; a per-query blocklist in the search service filters them immediately while classifiers catch up.
  9. A massive deletion (an account removed for abuse with millions of posts). The tombstone set absorbs the ids instantly; background jobs remove postings from hot lists and mark segment deletion bitmaps over the following hours.
  10. Cross-region replication lags. Posts from another region appear later in local results; freshness canaries per region show the delay, and queries for very fresh content can be routed to the writing region if the lag exceeds the budget.
Deep Dive: Variants, evolution and operating the systemShow

Variants of the problem.

  • Twitter or Threads search. Nearly identical: short public posts, recency-first, real-time freshness in seconds. Public by default, so caching is even more effective.
  • Slack or Discord message search. Strictly scoped by workspace or server and channel membership. Partition the index by tenant (each workspace is a natural shard), which also makes deletion and data residency easier. Freshness and permissions dominate; global popularity does not exist.
  • E-commerce product search. Small corpus (millions of products), rich structured filters (price, size, brand), relevance and conversion-based ranking, and faceted counts. Freshness of inventory and price matters more than freshness of new documents.
  • Log search. Append-only, time-partitioned, rarely queried per byte, very high ingest. Index by time first, often with minimal text indexing and brute-force scanning of compressed blocks within a time range.
  • Semantic search. Users describe meaning rather than keywords. Embeddings and approximate nearest-neighbour indexes replace or complement posting lists, with the same two-stage structure: vector retrieval, then re-ranking. See Vector Databases and Similarity Search.

Evolving the system.

  • Stage 1: a managed search engine (Elasticsearch or OpenSearch) fed by CDC from the post database. Default shards, replicas and a short refresh interval. This serves a product with millions of posts per day.
  • Stage 2: results cache and CDN for hot queries; time-based indexes (one per day or week) with aliases; a like aggregator with milestones; hot and cold node tiers.
  • Stage 3: custom serving for the newest data (an Earlybird-style in-memory tier), batch-built compressed segments for history, selective bigram indexing from query logs, privacy pre-filtering, and multi-region replicas of the index.

Service level objectives. Examples: p50 query latency under 200 ms and p99 under 1 s at the origin; 99.9% of new posts searchable within 60 seconds (measured by canaries); 99.95% availability of the search endpoint; partial-result rate under 0.5% of queries.

Load testing. Replay real query logs at multiples of peak, including a synthetic "breaking news" burst where 30% of traffic targets one new query, and verify coalescing and cache behaviour. Measure index write throughput with realistic term distributions, not uniform random words, because Zipf skew is what creates hot keys. See Capacity Planning and Load Testing.

Dashboards. Query latency by tier and by plan type (single term, intersection, bigram); cache hit rate per layer; shard p99 and hedge rate; Kafka consumer lag in seconds for posts and likes; milestone events per second; freshness canary p99; tombstone set size; cold-tier fetch rate and latency.

Deep Dive: Inside an in-memory index shardShow

If the interviewer forbids search libraries and pushes further ("what does one index server actually look like?"), here is a concrete design for the newest-tier shard, in the spirit of real-time engines.

Data layout. A shard holds a fixed time slice (say the last few hours) for its share of posts. Inside it:

  • A term dictionary: a hash map from term string to term id (a small integer), plus per-term metadata (document frequency, pointer to the posting pool).
  • Posting pools: large pre-allocated arrays of 32-bit integers. Each term's postings are a chain of slices inside the pools. A term starts with a tiny slice (say 2 entries); when it fills, the next slice is twice as large and the old one stores a pointer to it. Common terms quickly reach big contiguous slices; rare terms waste little space. This avoids per-posting objects and garbage-collection pressure, which matters greatly in managed runtimes such as the JVM.
  • Local document ids: each post gets the next integer in the shard (0, 1, 2, ...). Because posts arrive in time order, local id order equals time order, so recency ranking is "read from the highest id downwards". A side array maps local id to global post id and creation time.
  • Per-document columns: arrays indexed by local id holding approximate like score, author id and flags (deleted, low quality). Like-score updates write one array cell, not a posting list, so the likes order is produced at query time by a top-K pass over candidate local ids, which is cheap inside a single shard's small time slice.

Concurrency: one writer, many readers. A single indexing thread appends postings; many query threads read concurrently. Readers must never see a half-written posting. The trick is a published high-water mark: the writer fills in all postings for document d, then updates a shared, volatile "max visible document id" to d with a memory barrier. Readers read the mark first and ignore anything above it. No locks on the read path, and writes are visible as soon as the mark moves, which gives sub-second freshness. Earlybird described this kind of design, relying on the Java memory model's guarantees for volatile variables.

Deletes and updates. Set a bit in the deleted-flags column; readers skip flagged documents. Edits are a delete plus a new document. Like-score updates overwrite a 32-bit cell atomically.

Sealing. When the shard's slice is full (by count or time), it becomes read-only. A background step then optimises it: postings for each term are copied into a single contiguous, delta-compressed block with skip entries, the dictionary is rewritten as a sorted array or FST, and the result is written out as an immutable segment file (and uploaded to blob storage for the warmer tiers). A new empty slice takes over writes.

Memory arithmetic. Suppose the shard indexes 50 million posts (about 1.4 hours of global posts if spread over 1 shard, or about 3.7 days for one of 64 shards) with 50 postings each: 2.5 billion postings × 4 bytes = 10 GB uncompressed for document ids, plus dictionary and columns (a few GB). That fits comfortably on a 64 to 128 GB machine, with room for two or three slices (active plus recently sealed) and replication buffers.

Recovery. On restart, a shard loads its latest sealed segments from local disk or blob storage and replays the Kafka partitions from the offset recorded at the last snapshot. Because the active slice is rebuilt from the log in minutes (a few hours of events at hundreds of thousands per second per consumer), there is no need for a separate write-ahead log on the shard: Kafka is the write-ahead log.

Query execution inside the shard. For a single term sorted by recency: read the term's chain from the newest slice backwards, skip flagged documents, stop after K. For two terms: walk the shorter chain from newest, probe the longer one with a skip search. For the likes order: gather candidates (capped at, say, 10,000 per term), read their like-score column, keep a min-heap of size K. Each operation touches contiguous arrays, so it is fast and cache-friendly, typically well under a millisecond for common queries.

Why not just Redis? Redis sorted sets are general-purpose: each member costs tens of bytes, every update goes through a network round trip, and multi-term intersections either move lists to the client or run as scripts that block the server's single thread. A purpose-built shard stores 4 bytes per posting, executes the whole query locally, and handles writes in bulk. Redis is the right answer for a 45-minute interview's first version; the purpose-built shard is the answer to "how would you make it ten times cheaper?"

Key Takeaways#

  • Estimate first: post search is write-heavy (10,000 posts and 100,000 likes per second against 10,000 searches), and likes dominate index updates. See Back-of-the-Envelope Estimation.
  • Scanning cannot work at petabyte scale, and sharding a scan does not fix it. Build an inverted index from terms to posting lists, with the same tokenisation for posts and queries. See Database Indexing.
  • Keep one pre-sorted index per sort order (a recency list and a likes sorted set) instead of sorting at request time, and read only the top K.
  • Feed the index from the source of truth through CDC or an outbox into Kafka, with idempotent, batching indexers and replay for rebuilds. See Change Data Capture and the Outbox Pattern.
  • Partition by document, ideally in time tiers, so writes stay local, hot terms spread evenly and recency queries stop at the newest tier; manage the fan-out tail with hedging, deadlines and partial results. See Partitioning and Sharding.
  • Tame likes with milestone updates of approximate scores plus an exact re-rank of 2N candidates: the classic two-stage retrieval pattern. See Pattern: Scaling Writes.
  • Without personalisation, identical queries share answers: put a results cache and a CDN in front with TTLs chosen so that TTL plus indexing delay stays under the freshness budget, and coalesce requests to stop stampedes. See Pattern: Scaling Reads.
  • Answer phrases with rarest-first intersection and positions, and add a selective bigram index for popular phrases, chosen from query logs and count-min sketches. See Probabilistic Data Structures for Big Data.
  • Control cost with caps, compression and hot, warm and cold tiers, moving rarely queried lists to blob storage. See Data Lifecycle, Tiering and Retention.
  • Real engines (Lucene, Earlybird, Unicorn) share the same shape: in-memory newest data, immutable compressed segments, document partitioning, and rebuildable derived indexes. See Elasticsearch and Search Systems.