System Design · Interview breakdown · Free article
Design a Post Search System (Facebook, Twitter)
Find the 25 newest posts that contain two words among a trillion, make a post searchable a second after it is written, keep most liked exact while likes change 200,000 times a second, split the index so most searches ask 20 machines, absorb the search everyone makes at once, and never show a post its author hid. Built one step at a time, with experiments you can run.
A post search system lets people find posts by the words in them, newest first or most liked first, out of every post ever written. Posts are saved in a sharded posts database, and every change reaches the indexers as an outbox row committed with the post, so a crash cannot leave a saved post out of search. The indexers keep an inverted index: for each word, the list of posts that contain it, sorted by post ID, and the ID starts with the time. An AND search walks the rarest word’s list, jumps into the others with skip pointers, and stops at the 25th match. Likes are added up by a counter that reads the same stream, and the index holds only a bucket per post, the largest power of two at or below its likes from 64 up, so a most-liked search reads exact counts for a few candidates and stops early. The index is split by post into a recent tier in memory, a popular tier and yearly tiers on SSD, so most searches ask 20 partitions. Hot searches share one cached fetch, and every result is checked against the privacy service before it is shown.
Difficulty: Hard. Reported in interviews at Meta, LinkedIn. Also asked as Design Facebook post search, Design Twitter search, Design search without Elasticsearch, Design an inverted index for billions of documents.
How do you design a post search system?
A post search system lets people find posts by the words in them. You type “night train”, and it returns the posts that contain both words, newest first or most liked first, out of every post anyone has written. Facebook, Twitter, LinkedIn and every large forum have one. It looks like a database query. At a trillion posts, a query that reads the posts is millions of times too slow. So the system keeps a second structure built for the question, an index. It keeps the index up to date as people post, like and delete.
- Post: Stuck at Linz. Jonas posts at 23:10:00. Farah must be able to find it within seconds.
- Search: night train. Two words, each in millions of posts. Only posts with both count.
- Newest: 25 newest. The 25 newest matches out of a week of 2.1 billion posts, in under half a second.
- Most liked: Past day, by likes. Likes change 200,000 times a second, and the order must still be right.
- Allowed: Friends only. A post its author hid must never appear, even before the index hears.
Picture Farah on the platform in Salzburg at 23:10 on a Friday, waiting for the night train from Vienna. It is late, and the board says nothing. She opens the app and searches “night train”. Jonas is on that train. Ten seconds ago he posted: “Night train from Vienna stuck at Linz, engine fault. They say about 40 minutes, so Salzburg people stay warm inside.” Farah needs to see that post now, not tomorrow.
Interviewers like this problem because the obvious first answer, a database with a text search, works on a laptop. It then fails at scale in ways a candidate can reason about out loud. The version most often reported asks you to build the index yourself, without Elasticsearch, so the interviewer can see whether you know what is inside one.
Here is the design in brief. Posts are saved in a posts database. Every change to it flows, in order, through a change stream to indexers. The indexers keep an inverted index: for every word, the list of posts that contain it, sorted newest first. A search for two words walks their lists together and stops at the first 25 posts that appear in both. A second list per word, ordered by a coarse like count, answers most liked. The index is split by post across many machines, with the last seven days in memory and older years on SSD. A cache absorbs the search everyone makes at once, and a privacy check runs on every result before it is shown.
The rest of this page is about the moments that design has to survive.
The first is the post nobody can find. Jonas taps Post at 23:10:00. The Post API saves his post, and 10 milliseconds later a deploy kills it, before it has told the index. Farah searches at 23:10:10 and gets nothing. Nothing in the system knows the post is missing, so she gets nothing at 23:20 either.
The second is the word everybody uses. “Train” is in 2.1 million posts this week and “the” is in 700 million. A search for “the train” that walks both lists to the end reads 702 million entries to show 25 posts.
What is the interviewer testing?
Most candidates reach a working answer quickly: a posts table, an inverted index from words to post IDs, and a search service that intersects two lists. That answer is right, and a mid-level answer often stops there.
The interviewer then pushes on what that answer takes for granted. The lists have millions of entries each. A new post must be searchable in seconds. Most liked depends on counts that never stop changing. A trillion posts do not fit on one machine, and a news event sends everyone to the same search at once. A senior answer walks the lists newest first and stops at a page. It feeds the index from the database’s change stream, and keeps likes out of the index’s hot path. A staff answer also splits the index into tiers so a search asks as few machines as possible, and keeps privacy correct while the index lags.
Spend most of the deep-dive time on the list walk, likes and splitting the index. Freshness and hot searches are the usual follow-ups, and privacy is where a staff round goes. How to run a round has the time plan for a 45 to 60 minute round and a 15-minute screen.
What should you ask before drawing anything?
Four questions change the design. Ask them in the first two minutes. If the interviewer leaves one open, say your assumption out loud.
- Can we use Elasticsearch?
- Assume not. The version of this question most often reported asks you to design the index itself. If the interviewer allows it, say so, and spend the saved time on likes, freshness and privacy, which a search engine does not decide for you.
- What is a search, and in what order?
- Assume words joined by AND or OR, such as “night AND train” or “train OR tram”, matched after lowercasing. Results come newest first, or most liked over the past day, week or all time, 25 to a page, with a way to get the next page. Exact phrases are a short extension; typos and search by meaning are out of scope.
- How big, and how fresh?
- Assume 600 million daily users, 300 million new posts a day, 6 billion likes a day, and ten years of posts to search. A new post should be searchable within 10 seconds, and a search should answer in under half a second.
- Who may see a post?
- Posts are public or friends-only, and a search must never show a post its reader may not see. Some interviewers put privacy out of scope. Ask; if it is in, it becomes the last deep dive.
Functional requirements
1. Post short text posts; edit, delete 2. Like a post, once per person 3. Search by words: AND, OR 4. Newest, or most liked in a time range out: typos, meaning, images, per-user rank
Say it, don’t write it: The index answers one question fast: which posts contain this word. Everything else is built on that.
Two people use the system. Jonas writes posts and likes other people’s. Farah searches. It also answers to authors: a post they delete or hide must disappear from search.
- Post a short text post, and edit or delete it.
- Like a post, at most once per person.
- Search posts by words, joined by AND or OR.
- Sort results newest first, or most liked over the past day, week or all time, 25 to a page, with a next page.
Out of scope
- Typos and spelling suggestions
- Search by meaning rather than by words
- Images and video
- Ranking tailored to each reader
- Autocomplete and trending topics
Non-functional requirements
• 40k searches a second at peak, p99 < 500 ms • 10k posts, 200k likes a second at peak • A new post searchable within 10 s • Every post of 10 years findable • Never show a post its reader may not see
Say it, don’t write it: Likes outnumber posts 20 to 1, so whatever changes on a like must not be the index.
- About 40,000 searches a second at the peak, each answered in under 500 ms at the 99th percentile.
- About 10,000 new posts and 200,000 likes a second at the peak.
- A new post is searchable within 10 seconds, and a saved post is never missing from search.
- Every post of the last 10 years can be found.
- A search never shows a post its reader is not allowed to see, and never shows a deleted post.
Three numbers are worth working out now, because each decides a piece of the design.
Posts come first. One post for every two users each day is 300 million a day, which is 300,000,000 ÷ 86,400, about 3,472 a second, with a peak of 10,000. Each post adds its ID to the list of every word in it, and a short post has about 20 distinct words. At the peak that is 10,000 × 20 = 200,000 list appends a second. Adding to the end of a list is cheap, so the index keeps its lists append-only wherever it can.
Likes come second. Ten likes per user per day is 6 billion a day, about 69,444 a second, with a peak of 200,000. That is 20 likes for every post. If a like changed the index the way a post does, likes would be 20 times the index’s work. So likes are counted outside the index, and the likes deep dive decides how little of each count the index needs to know.
Searches come third. Two searches per user per day is 1.2 billion, about 13,889 a second, with a peak of 40,000. One search may ask many index machines. At 40,000 searches a second, asking 400 machines each would be 16,000,000 machine requests a second. So the deep dive on splitting the index is about asking as few machines as possible.
The other numbers appear in the deep dive that needs them. They are illustrative interview targets, not measurements of any real company.
Core entities
Post(id, author, text, audience) Like(user, post), one per pair Count(post) → likes, from the stream Word → post IDs, newest first Word → post IDs, by like bucket
Say it, don’t write it: A post ID starts with the time it was made, so a list sorted by ID is a list sorted newest first.
Follow Jonas’s post through the records. When he taps Post, the Post API gives it an ID, P7. The ID is a 64-bit number whose first 41 bits count milliseconds from a fixed start date, followed by a 10-bit machine number and a 12-bit sequence number. This is the layout Twitter published as Snowflake (Twitter). A larger ID means a newer post, to within about a second, so sorting by ID sorts by time.
The post’s row holds P7, Jonas’s user ID, the text and the audience, public or friends-only. The indexer lowercases the text and splits it into words: “night”, “train”, “from”, “vienna” and so on, 20 distinct words in all. For each one, it adds P7 to that word’s list. It also keeps P7’s own word set, so that an edit later knows which lists to take P7 out of. When Farah likes the post, one transaction writes a like row keyed by her user ID and P7, and an outbox row that says so. A counter reading the stream adds one to P7’s count.
| Record | What it holds | Why it is separate |
|---|---|---|
| Post | ID, author, text, audience | The truth. The index is a copy that can always be rebuilt from it |
| Like | The user and the post, unique together | A second tap on Like finds the row and changes nothing |
| Like count | One number per post, kept by a counter that reads the stream; this week’s and popular posts are also in Redis | It changes 200,000 times a second at the peak, so it lives outside the index |
| Word list | A word, and the IDs of the posts that contain it, newest first | What a search reads |
| Likes list | A word, and the IDs of its posts, ordered by like bucket | What a most-liked search reads |
The one distinction that matters: the posts database is the truth, and everything a search reads is a copy of it that can be a second behind. So a search that finds a post still checks the post before showing it.
API
POST /posts {text, audience} → {id}
POST, DELETE /posts/{id}/likes → 204
GET /search?q=night+AND+train
&sort=newest|liked&cursor=…
→ {posts[25], next_cursor}Say it, don’t write it: The cursor says where the last page ended, so page two continues from it instead of counting from the top again.
The app calls three endpoints to post and like, and one to search.
| Call | Returns | Why it looks like this |
|---|---|---|
POST /posts with {"text": "Night train from Vienna stuck at Linz…", "audience": "public"} | {"id": "P7"} | The server makes the ID, so it carries the server’s clock |
POST /posts/P7/likes | 204, and the same for a second tap | A like is a row keyed by user and post, so repeating it is harmless |
DELETE /posts/P7/likes | 204 | An unlike removes the row, and the count goes down |
DELETE /posts/P7 | 204 | The post leaves search as well as the feed |
GET /search?q=night+AND+train&sort=newest | {"posts": [25 posts], "next_cursor": "c_9f…"} | Words are lowercased; AND binds tighter than OR |
GET /search?q=night+AND+train&sort=newest&cursor=c_9f… | The next 25 | The cursor holds the last post shown, so new posts cannot shift page two |
Three details are there on purpose. The server makes the post ID, because only its clock can be trusted to order posts. The like is safe to repeat, because a phone on a train retries. And the search returns a cursor instead of taking a page number. Suppose Farah asks for page two by number after 40 new posts have arrived. Page two, positions 26 to 50, would now hold 15 of the new posts and then 10 posts she saw on page one. The cursor says “older than the last post you saw”, which new posts cannot move.
Step 1: post, and search for one word
Jonas taps Post. The Post API gives the post its ID, P7, and saves it in the posts database, a relational database such as MySQL, split into shards by post ID. The same transaction writes an outbox row that says P7 was created. A relay publishes outbox rows to a Kafka topic keyed by post ID, the change stream, so all changes to one post arrive in order. Stream workers read it, and the ones that build the index are the indexers. For each word in P7, an indexer adds P7 to that word’s list in the index, which lives in memory.
Farah searches “train”. The Search API asks the index for the list for “train”, takes the first 25 IDs, which are the newest, and fetches those posts from the posts database.
The interactive version of this example is available when JavaScript loads.
An inverted index turns the question around. The posts database can say which words post P7 contains. The index says which posts contain the word “train”. Stanford’s information retrieval book calls each word’s list a postings list. The whole design rests on one rule it states: “it is crucial that postings be sorted by a single global ordering” (Stanford IR book). Here that ordering is the post ID, which is time.
Step 2: two words, AND and OR
Farah searches “night train”, which means night AND train. Both lists are sorted by the same post IDs, newest first. The Search API walks them together. It looks at the current ID in each list. If the two are the same post, that post contains both words, so it goes in the results. If not, the walk moves forward in the list whose current ID is newer, because the older ID might still turn up there. When the results reach 25, the walk stops: those are the 25 newest posts that contain both words.
OR is the same walk with a different rule. “train OR tram” takes every ID it meets in either list, in order, and stops at 25.
The interactive version of this example is available when JavaScript loads.
The first deep dive shows why this walk is cheap for “night train” and ruinous for “the train”, and what fixes it.
Step 3: likes, and most liked first
Jonas’s post starts to collect likes. Each like is a row keyed by the user and the post, written in the same transaction as an outbox row. A second tap finds the row, so it changes nothing and sends nothing. A like counter, another stream worker, reads those events and adds them up per post. For now it sends each new count to the index, which moves P7 within a second list for each of its words, a list ordered by likes. A most-liked search walks those lists instead.
The interactive version of this example is available when JavaScript loads.
With steady traffic this already works. The deep dives take it through six moments: a search for a common word, a post nobody can find, a post everyone likes, a trillion posts, one search made by everyone at once, and a post its author hid.
Two words, each in millions of posts. How does a search read only a few thousand entries?
Start with the last week, because most searches want recent posts. Seven days at 300 million posts a day is 2.1 billion posts, and a post is about 300 bytes of text. The word “night” is in 10.5 million of them, one post in 200. “Train” is in 2.1 million, one in 1,000. About 105,000 posts contain both, one train post in 20. That is ten times what chance would give, because people who write about trains write about night trains.
The first answer many candidates give is to search the text: WHERE text LIKE '%night%' AND text LIKE '%train%', newest first. A normal database index sorts whole values, so it cannot find a word in the middle of a string. The database reads posts until 25 of them match. Newest first, a match comes along once in every 20,000 posts, because 2.1 billion ÷ 105,000 = 20,000. So 25 matches take about 500,000 posts, about 150 MB of text, for one search. At 40,000 searches a second that is 6 TB a second. A search whose words almost never meet, such as “night giraffe”, never finds 25 and reads the whole week: 630 GB. A database’s own full-text index, such as PostgreSQL’s, is already an inverted index and is the right first answer for a small site. This page builds the same structure at a size no single database holds. The database indexing guide explains why an ordinary index cannot help with a word in the middle.
The inverted index turns this around. Walk the two lists together from their newest end, always moving forward in whichever list holds the newer ID, and stop at the 25th match. Only the stretch of each list back to that match is read. A match turns up once in every 20 entries of “train”, because 2.1 million ÷ 105,000 = 20. So 25 matches take 500 entries of it. Over the same stretch of time, “night”, five times as common, has 2,500 entries. The walk reads 3,000 entries. At about 4 bytes an entry, that is 12 KB. Walking both lists to the end would read 12.6 million.
The early stop works only because both lists are sorted by the same post IDs, and the IDs are time. Newest first puts the answer at the front. A list sorted any other way could not stop early, because the next entry might belong on the first page.
Now Farah searches “the train”. Half of all train posts contain “the”, so 25 matches take only 50 entries of “train”. But “the” is in one post of every three, 700 million this week. Walking the two lists in step drags the second pointer through every entry of “the” between those 50 train posts. That is 50 × (700 million ÷ 2.1 million), about 16,667 entries. Stopping early helped. The common word still costs 333 times as much as the rare one.
The fix is to stop walking the long list. Walk the rarer list, “train”. For each of its entries, ask the longer list one question: do you contain this post ID? Skip pointers let the longer list answer in a few steps. Every so often, an entry also stores where the list continues much further on, so a search can jump past everything newer than the ID it wants. The Stanford book describes them as “effectively shortcuts that allow us to avoid processing parts of the postings list that will not figure in the search results” (skip pointers). Twitter’s real-time index goes further and keeps each list as a skip list. A skip list is several layers of such pointers, each layer holding a fifth as many entries as the one below (Twitter). Finding a post ID then takes a number of steps that grows with the logarithm of the list’s length.
Replay both searches. “the train” now costs 50 entries of “train” and 50 jumps into “the”. “night train” costs 500 entries and 500 jumps. Each jump is a handful of steps, so the cost is the rare list’s length times a small number, whatever the length of the long list.
One case is left, and it sets the worst case. Farah searches “night giraffe”. Only 2 posts this week contain both. The page never fills, so no walk can stop early. The walk that steps through both lists reads all 10.5 million entries of “night” as well. The walk that jumps reads all 2,100 entries of “giraffe” and makes 2,100 jumps. So the design keeps one rule: a search costs about as much as its rarest word, never its commonest. And when even the rare list runs out before the page fills, the search has to look further back than a week. The deep dive on splitting the index handles that.
The Search API plans longer searches the same way. The index keeps each list’s length beside its word. For “night AND train AND stuck”, the Search API walks the shortest list and jumps into the other two. For “(train OR tram) AND strike”, the OR merges two lists into one sorted stream. If “strike” is rarer, the AND walks it and jumps into each of the two lists behind the OR. An OR on its own cannot skip: every entry it passes is a result, so it reads both lists one entry at a time. The book notes that “the presence of skip pointers only helps for AND queries, not for OR queries”. Newest first, it still stops at 25. NOT works like AND in reverse: walk the positive list and drop any ID the negative list contains.
Exact phrases are the usual follow-up. As a phrase, “night train” should not match “the train left at night”. The index can store, for each post in a list, the positions where the word appears, and check that “train” sits one position after “night”. The book’s rule of thumb is that a positional index is “2 to 4 times as large as a non-positional index” (positional indexes). For short posts there is a cheaper option: index each pair of neighbouring words as a word of its own, so “night train” gets its own list. That is exact for two-word phrases. A longer phrase becomes an AND of its pairs, which can match pairs in different places, so the Search API checks those few results against the text.
The experiment runs three searches three ways. The tabs are walking both lists to the end, walking newest first and stopping at a page, and walking the rarer list while jumping in the other.
The interactive version of this example is available when JavaScript loads.
The gap: Each word’s list has millions of entries, and a search must not read them all to show 25 posts.
Option 1: Read the posts
Scan the post text newest first until 25 posts match.
Works when: A small forum, or a search inside one person’s posts.
Breaks when: About 150 MB for “night train”, and all 630 GB of the week when the words almost never meet.
Option 2: Walk both lists, stop at 25
Walk the two sorted lists in step, newest first, and stop at the 25th match.
Works when: Two words that are about equally common.
Breaks when: A common word drags the walk through its list: 16,667 entries of “the” for 50 of “train”.
Option 3: Walk the rarest list, jump in the others (start here)
Step through the shortest list and jump to each ID in the others through skip pointers; stop at 25.
Works when: Always.
Watch for: Words that rarely meet walk the whole rare list: “night giraffe” costs 2,100 entries and 2,100 jumps.
In the interview: Open with option 3, and say why the walk may stop at 25: the lists are sorted by post ID, and the ID is time. Then give the rule that a search costs as much as its rarest word. Mention positions or word pairs if the interviewer asks about phrases.
Say this: Each word maps to a list of post IDs, sorted newest first, because the ID starts with the time. For an AND, I walk the shortest list, jump into the others through skip pointers, and stop at the 25th match, so a search costs about as much as its rarest word. An OR merges lists and also stops at 25.
Jonas posts, and a deploy kills the server. Why can Farah never find his post?
At 23:10:00 Jonas taps Post. The Post API saves P7 in the posts database at 23:10:00.02. Its next step would be to tell the indexer. At 23:10:00.03 a deploy kills it. Farah searches “night train” at 23:10:10.
The first design has the Post API do both jobs: save the post, then send it to the indexer. Every step of that works on a normal day, and the deploy found the gap. The database has P7. The indexer never heard of it. Nothing in the system compares the two, so the post is missing from search today, tomorrow, and for as long as that index lasts. Reversing the order does not help. Index first and save second, and a crash between them indexes a post the database never kept, which a search finds and cannot fetch. Two writes to two systems, with a crash possible between them, will sooner or later disagree.
The second design stops trusting the Post API with the index. Every night at 03:00 a job reads every post and rebuilds the index. Nothing is lost, because P7 is in the database, so it is in the next index. But Farah is on the platform now. P7 becomes searchable 3 hours 50 minutes after Jonas wrote it. For a question about a train that is 40 minutes late, that is the same as never.
The fix takes the index’s input from the database itself. The transaction that saves P7 also writes one row to an outbox table, saying that P7 was created. A relay reads the outbox and publishes each row to a Kafka topic keyed by post ID, and the indexers read it. The post and its outbox row commit together or not at all, so they cannot disagree. Reading the database’s own log of committed writes, called change data capture, does the same job without the extra table. Each shard has one primary, which commits a post’s changes in one order, so the stream carries them in that order. A relay that crashes may publish a row twice. So every change carries the post’s version, and an indexer ignores any version no newer than the one it has. The same rule is how idempotency is built everywhere: a repeat is recognised and changes nothing.
Replay the deploy. P7 is committed at 0.02 s. The Post API dies at 0.03 s, and it no longer matters, because the change is already committed, outbox row and all. At 0.15 s the relay publishes it. At 0.35 s an indexer adds P7 to the lists of its 20 words. Farah’s search at 23:10:10 finds it.
Adding P7 to a list is not yet the same as being searchable. Many search threads read the index at once. A list that changes during a walk can show half a post: in the list for “night” and not yet in the list for “train”. Twitter describes exactly this hazard for a search with a NOT in it, where a post half added could come back wrongly (Twitter). So each search reads a fixed view of the index. New entries join the view at a refresh, here on every whole second. P7 is added at 0.35 s and searchable at the next refresh, 1 second after Jonas tapped Post. At worst, a post added just after a refresh waits one more second.
Twitter’s numbers show how short it can be. “Until mid-2019, the indexing latency for Twitter’s search system was around 15 seconds,” its engineers wrote. They brought it to about a second, mostly by removing waits. The pipeline had waited for fields that arrive later, such as a link resolved to its real address. Now it sends most of a post at once, “and then send another update when the rest of the data becomes available”. The requirement here is 10 seconds. One second of indexing leaves room for the 5-second cache the hot-search deep dive adds.
The lists stay sorted because posts arrive in roughly the order of their IDs. IDs come from the clock, and each post reaches an indexer a fraction of a second after it is made. Roughly is not always: a post made on a server whose clock runs a little behind can arrive after a newer one. Twitter’s old pipeline held posts for a few seconds to sort them by time. Its new lists are skip lists, which accept an ID in the middle, so the hold could go. A design with plain append-only lists keeps the short hold.
Edits and deletes travel the same way. An edit moves P7 between lists. The indexer compares the new text with the word set it kept for P7. It takes P7 out of the lists for words it no longer contains, and adds it to the lists for new ones. A delete takes it out of every list in the recent tier. Older tiers keep a list of removed IDs, as the deep dive on splitting the index explains. Because the stream is keyed by post ID, all changes to one post arrive in the order they were committed. And the Search API fetches every post it is about to show from the posts database. A post deleted in the last second may still be in the index, and the fetch drops it.
The index is now a copy that can always be rebuilt. If an indexer’s machine dies, its replacement loads the last saved copy of that part of the index. Then it replays the stream from the position where that copy was saved. Kafka keeps the stream for days, so no change is lost while a machine is replaced.
The experiment plays the deploy three ways. The tabs are saving and then telling the indexer, rebuilding every night, and indexing from the change stream.
The interactive version of this example is available when JavaScript loads.
The gap: The post is saved in one system and searched in another, and a crash can land between the two writes.
Option 1: Save, then tell the indexer
The Post API saves the post, then sends it to the indexer.
Works when: A prototype, where a missing post does not matter.
Breaks when: A crash between the two writes leaves a post in the database and never in search.
Option 2: Rebuild every night
A job reads every post at 03:00 and rebuilds the index.
Works when: An archive, where a day’s delay is fine.
Breaks when: A post can be up to a day late: 3 hours 50 minutes for Jonas’s.
Option 3: Index from the change stream (start here)
Indexers read outbox rows committed with each post, keyed by post ID; searchers refresh once a second.
Works when: Always.
Watch for: The stream must be kept long enough to rebuild a lost indexer, and appends need a short hold or lists that accept an ID in the middle.
In the interview: Open with option 3 and name the failure it removes: two writes with a crash between them. Say the numbers: searchable about a second after the post, inside a 10-second target. If the interviewer asks about deletes, say that the Search API fetches every post from the database before it shows it.
Say this: The index is fed from the database’s change stream, never by the API writing twice, so a crash cannot leave a saved post out of search. The stream is keyed by post ID, so each post’s changes arrive in order. Indexers add to in-memory lists and searchers refresh every second, so a post is searchable in about a second. Every result is fetched from the database before it is shown, which drops anything deleted in the meantime.
Jonas’s post gets 50,000 likes a minute. How does most liked stay right?
At 23:20 a news site shares Jonas’s post, and it collects 50,000 likes a minute. Ten seconds later, Farah switches her search to most liked in the past day. By then P7 has 9,300 likes.
Step 3 sent every new count to the index, and the indexer moved P7 up the likes list of each of its words. 50,000 likes a minute is about 833 a second. P7 has 20 words, so that is 833 × 20, about 16,667 list moves a second, for one post. Across the site the peak is 200,000 likes a second, so 200,000 × 20 = 4,000,000 list moves a second. A move is not an append. It takes a post out of the middle of a sorted list and puts it back further up. That work lands on the machines that must also answer 40,000 searches a second.
The opposite idea keeps likes out of the index entirely. The index finds every post that matches, and the Search API asks for each one’s count and sorts. Redis answers a count in well under a millisecond. But “train” matches 2.1 million posts this week alone, so one most-liked search would ask for 2.1 million counts. Neither extreme works. The index cannot follow every like, and the search cannot look up every match.
The fix tells the index something coarse that rarely changes, and reads the exact number only for the few posts that could make the page. The coarse value is a bucket: the largest power of two at or below the post’s likes, counting from 64. A post with 9,300 likes is in bucket 8,192. A post with 4,050 likes is in bucket 2,048, because 4,096 is more than 4,050. A post with fewer than 64 likes is in bucket 0. The counter still adds up every like. It tells the index only when a count crosses a power of two from 64 up: at 64, 128, 256 and so on.
The floor of 64 has a reason. An average post gets 6 billion ÷ 300 million = 20 likes. With buckets from 1, it would cross 1, 2, 4, 8 and 16: five index writes for 20 likes, a quarter of all likes. A post with fewer than 64 likes rarely makes a most-liked page, so its bucket stays 0 and the likes list keeps it in time order. Most posts then never cause a bucket write at all.
For P7 the saving is large. Had it gone on to 100,000 likes, it would have crossed 64, 128 and every power of two up to 65,536, which is 11 crossings. 11 × 20 is 220 list moves over the whole life of the post, instead of 16,667 every second. Even a post with a million likes crosses only 14 times.
The counter must not lose a like or count one twice. It reads like events from the stream in batches, and it stores, with the counts, the stream position it has counted up to. After a crash it resumes from that position, so nothing is skipped or counted again. A restarted counter may publish an old bucket a second time, so each bucket message carries a sequence number and the indexer keeps only the newest. It keeps every post’s count in a counts table, and copies the counts of this week’s posts and of popular posts into Redis, where searches read them. All 1.1 trillion counts would not fit in memory. Unlikes run the other way. When a count falls below its bucket, the counter lowers the bucket, so a bucket is never above its post’s count.
The interactive version of this example is available when JavaScript loads.
The bucket alone does not give the right order. Each recent partition runs a walk over its own posts and returns its best, and the Search API merges them. Follow one partition, with a page of five to keep the walk short. For “night train” it also checks each candidate against the list for “night”, as the first deep dive showed; the walk below follows “train” alone. The likes list for “train” is ordered by bucket, and newest first within a bucket. At the front is P7 in bucket 8,192. Then come A, B and C in bucket 4,096, then D, E and F in bucket 2,048, then G, H and I in bucket 1,024. If the partition takes the first five, it returns D, with 4,000 likes. It leaves out E, with 4,050, because the index knows only that both have between 2,048 and 4,095.
So the partition walks the list in bucket order and reads exact counts from Redis as it goes, in batches, keeping the best five so far. After P7, A, B, C and D it has five, and the fifth best is D’s 4,000. E is in bucket 2,048, so it could have up to 4,095 likes, which would beat 4,000. Read it: 4,050, so E replaces D. F is in the same bucket and could also have up to 4,095. Read it: 2,200, so no. Next comes G, in bucket 1,024. A post in that bucket has fewer than 2,048 likes, and the fifth best is now 4,050. G cannot get in, and nothing after it can either, because the buckets only go down from there. The walk stops after seven lookups, and the five are exactly right: P7, A, B, C and E.
A post’s true count is below twice its bucket, and a post in bucket 0 has fewer than 64. Once twice the next post’s bucket is no more than the fifth best count found, stop. For a real page of 25, the walk reads the posts in the top few buckets, not 2.1 million. The rule assumes the index’s bucket is current. A crossing takes about a second to reach the index, and a fast post can pass several buckets in that second. So for posts that crossed in the last few seconds, the walk widens its bound, to four times the bucket or more. The code below shows the basic rule.
Powers of two are one choice among many. With a factor of 2, a post moves at most 14 times on its way to a million likes. In return, the walk checks every post within a factor of 2 of the page’s last entry. A factor of 1.25 lets the walk stop sooner, and moves each post about 44 times. Any scale whose steps grow by a fixed factor works, and the factor sets that trade.
Buckets add a second producer to the stream, and a second producer brings a race. The share brings strangers into Jonas’s replies, and at 23:21:18 he deletes P7. The delete commits with its outbox row and goes onto the stream. Half a second earlier, a like took P7 past 65,536. The counter runs a little behind the stream, so it counts that like at 23:21:18.2 and publishes bucket 65,536 for P7. That message lands on the stream after the delete. An indexer that simply applies it puts P7 back into the likes lists of its 20 words. A deleted post is in search again.
Two rules close it. The indexer treats a delete as final: it keeps a tombstone, a marker saying P7 was deleted, and ignores any later message about P7. The tombstone is saved with the index, so a replay after a crash still has it. And the Search API fetches each post from the database before showing it, so a deleted post never reaches Farah’s screen, even while the index is wrong.
The experiment finds the top five for “train” three ways. The tabs are moving the post on every like, trusting the buckets alone, and walking the buckets while reading fresh counts.
The interactive version of this example is available when JavaScript loads.
The gap: Likes change 200,000 times a second, and a most-liked page must still be exact.
Option 1: Move the post on every like
Write each like’s count into the index and re-sort the post in each of its words’ lists.
Works when: A small site with a few likes a second.
Breaks when: One viral post makes 16,667 list moves a second, and the site makes 4,000,000.
Option 2: Sort every match at search time
The index returns every match; the Search API reads each count and sorts.
Works when: Rare words with a few hundred matches.
Breaks when: “train” alone has 2.1 million matches this week.
Option 3: Buckets in the index, exact counts at search time (start here)
The index keeps each post’s power of two from 64 up, updated only at a crossing; the walk reads exact counts until the next bucket cannot beat the page.
Works when: Always, for a likes order.
Watch for: A second producer on the stream: a late bucket can follow a delete, so the indexer treats a delete as final.
In the interview: Open with the arithmetic that rules out option 1: 833 likes a second times 20 words. Then give option 3 its two halves, the bucket and the stopping rule, and walk the D and E example out loud. Mention the delete race if the interviewer asks what else can go wrong.
Say this: Likes are added up by a counter that reads the stream, and never written to the index one at a time. The index keeps a bucket per post, the largest power of two at or below its count from 64 up, so a post moves at most 14 times on the way to a million likes. A most-liked search walks the buckets, reads exact counts as it goes, and stops once twice the next bucket cannot beat the page. A delete is final in the index, so a late bucket cannot bring a post back.
Ten years of posts will not fit on one machine. How do you split the index?
Work out the size first. 300 million posts a day for ten years is 300,000,000 × 365 × 10, about 1.1 trillion posts. With 20 words each, the lists hold 22 trillion entries. Inside each machine, posts get small local numbers in time order, and a list stores the gaps between them, so an entry takes about 4 bytes after compression. The lists alone are 22 trillion × 4, about 88 TB. The last seven days are much smaller: 2.1 billion posts × 20 words × 4 bytes is 168 GB, which fits in memory across a few machines. The index has to be split, and how it is split decides how many machines each search must ask.
The first idea splits it by word. Each machine owns some words and holds their whole lists. A search for “night train” asks two machines, one per word. That sounds ideal, and three things break it. Every new post has 20 words, so it writes to about 20 machines. A common word lives on one machine, and every search that contains “the”, or tonight “strike”, lands there. An AND must bring two lists together on one machine. So the owner of one word streams its IDs to the owner of the other, an extra hop on every search. And if every copy of a word’s list is down, that word cannot be searched at all. A split by post would lose only a fraction of the results. Facebook split its search engine for the social graph, Unicorn, the other way for exactly that reason. Its paper says: “it is better to return some fraction of the friends of Jon Jones than no friends at all” (Unicorn paper).
So split by post instead. Each machine owns a set of posts and holds the lists for every word, but only for its own posts. A new post writes to exactly one machine. Every search goes to every machine. Each walks its own lists and returns its own 25 best, and the Search API merges them. The merge is exact, because each post lives on exactly one machine. Any post in the overall top 25 is also in the top 25 of the machine that holds it.
The cost is how many machines a search waits for. Suppose the index ends up on 440 partitions, the number this design will use, and all of them are one pile. Every search asks all 440. A search is only as fast as its slowest answer. If each partition misses its deadline one time in 100, the chance that at least one of 440 misses it is 1 − 0.99^440, about 99%. Jeff Dean and Luiz Barroso give the same arithmetic for 100 servers: “63% of user requests will take more than one second” (The Tail at Scale). The percentiles guide explains why the slowest one in a hundred decides the page.
The fix is to make most searches ask fewer partitions, and time does most of the work. Split the index into tiers. The recent tier holds the last seven days, 168 GB, in memory across 20 partitions of about 8.4 GB each. Older posts go into yearly tiers on SSD, 40 partitions per year: 88 TB over 400 partitions is about 219 GB each. Once a day, the oldest day of the recent tier is sealed and moved into its year’s tier. Sealed does not mean frozen. A delete or a privacy change for an old post goes into a short list of removed IDs that every search of that tier checks. Old posts still gain likes, and a bucket change for one moves it within the popular tier, which stays writable.
A newest-first search starts with the recent tier. “night train” has 105,000 matches in the last week, far more than 25, so the search stops there. It asks 20 partitions, and a slow one delays 1 − 0.99^20, about 18% of searches. That is still too many for a 500 ms target at the 99th percentile. So each partition must be slow far less often than one time in 100, or its slow answers must be hedged, as below. The 400 history partitions are never asked. Each partition walks its own lists for its own 25. For “night train” that is 500 entries of “train” and 500 jumps on each of the 20, about 10,000 of each in all. The Search API keeps 25 of the 500 posts it receives. Only a search whose words are rare this week needs older years. The index knows how long each word’s list is in every tier. So for a rare word the Search API asks every tier it needs at once, instead of one year at a time.
Most liked is harder, because a post from 2019 can have more likes than anything this week. The bucket from the likes deep dive offers a way out. Keep a popular tier holding every post, of any age, whose bucket is at least 1,024. A post that unlikes take below 1,024 leaves it. If one post in a thousand gets there, that is 1.1 billion posts and about 88 GB of lists, in 20 partitions. A most-liked search asks the popular tier first. If it finds 25 matches, each of them has at least 1,024 likes, and every post outside the tier has fewer, so nothing outside can beat them. The search is done after 20 partitions. A post joins the tier within a second or so of crossing 1,024, so for that second the argument can miss it. A fallback to every tier reads counts from the counts table, since old unpopular posts are not in Redis, and such a search has few matches by construction. Only a rare combination such as “night giraffe”, with too few popular matches, falls back to every tier.
Each recent partition still hears from every newest-first search, up to 40,000 requests a second. So each partition has copies on several machines. Ten copies bring each machine down to 4,000 requests a second, and the copies also cover a dead machine. Copies help the tail too. When a partition has not answered by its usual 95th-percentile time, the Search API can send the same request to another copy and take whichever answers first. In a Google benchmark reading from 100 servers, “sending a hedging request after a 10ms delay reduces the 99.9th-percentile latency for retrieving all 1,000 values from 1,800ms to 74ms while sending just 2% more requests.” At its deadline, a search can also return what it has, marked incomplete, rather than wait for one straggler.
The tiers also make the index easy to grow. Twitter built its archive of every public post this way in 2014, “roughly half a trillion documents”, split first into time tiers and then by hash within each tier. “To grow data capacity over time, we will add time tiers. Existing time tiers will remain unchanged,” its engineers wrote, and its root servers avoided “forwarding requests to time tiers not relevant to the search query” (Twitter).
The interactive version of this example is available when JavaScript loads.
The experiment sends three searches to the 440 partitions. The tabs are splitting by word, splitting by post in one pile, and splitting by post in tiers.
The interactive version of this example is available when JavaScript loads.
The gap: 88 TB of lists must be split across machines, and a search is as slow as the slowest machine it asks.
Option 1: Split by word
Each machine owns some words and their whole lists.
Works when: A small index where words are used evenly.
Breaks when: Each post writes to 20 machines, a common word makes one machine hot, and a dead machine takes its words with it.
Option 2: Split by post, one pile
Each machine owns some posts and all their words; every search asks every partition and merges.
Works when: An index small enough for a few dozen partitions.
Breaks when: With 440 partitions, a slow one delays about 99% of searches.
Option 3: Split by post, in tiers (start here)
A recent tier in memory, a popular tier for most liked, yearly tiers on SSD; a search stops at the first tier that fills its page.
Works when: Always, at this size.
Watch for: Rare words still reach every tier, so partitions need copies, hedged requests and a deadline with a marked partial answer.
In the interview: Open by sizing the index: 88 TB of lists, 168 GB for the last week. Explain why splitting by post merges exactly, give the 1 − 0.99^n arithmetic, and use tiers to make n small. Keep the popular tier for the follow-up about most liked.
Say this: I split the index by post, so a new post writes to one partition and each partition returns its own top 25, which merge exactly. Most searches want recent posts, so the last seven days sit in a recent tier of 20 partitions in memory, and older years in tiers on SSD. A most-liked search asks a popular tier of posts with at least 1,024 likes first, and falls back to every tier only for rare words. Slow partitions are hedged.
A rail strike is announced. What happens when everyone searches the same thing?
At 23:40 the rail union announces a strike for Monday. Within a minute, one search in five on the site is “train strike”: 8,000 a second, out of a peak of 40,000. Every one of them has the same answer.
Without a cache, each of those searches goes to the index and asks the 20 recent partitions. This one search sends 8,000 × 20 = 160,000 requests a second to the index. Each recent partition answers the same question 8,000 times a second. The answer changes only when a new post about the strike arrives.
The obvious fix is a cache in front of the index. The key is the search in a standard form: lowercased, with the words of an AND sorted, so “Strike train” and “train strike” share an entry. The value is the list of post IDs, newest first. The entry expires after 5 seconds. A new post then still appears within the 10-second target: about a second to be indexed, and at most 5 in the cache.
Play ten seconds of it. The first search misses and asks the index, and the answer is ready 50 ms later. In those 50 ms, 8,000 × 0.05 = 400 searches arrive, the first among them. Each finds no entry and asks the index too. For the next 5 seconds the cache answers everything. At the 5-second mark the entry expires, and it happens again: 400 identical searches at once, 400 × 20 = 8,000 partition requests in one burst. Over ten seconds that is 800 searches and 16,000 partition requests, down from 1.6 million. The average looks fine. The bursts do not: they arrive every 5 seconds, and they grow with the traffic. This burst has a name, a cache stampede.
The fix is to let only one search do the work, which is called request coalescing. When a search misses, the Search API writes a note in Redis that this key is being fetched, with a short lease. Any other search for the same key, on any server, waits for that fetch instead of starting its own. Each entry also has two ages. After 5 seconds it is old: the Search API still returns it at once and starts one refresh in the background. After 30 seconds it is gone. Over the same ten seconds the index sees two searches, one at the start and one refresh at the 5-second mark: 40 partition requests. After the first fill nobody waits, and no answer is more than about 5 seconds old.
What goes in the cache matters. Two people searching “train strike” may be allowed to see different posts, because some are friends-only. So the cache holds post IDs, from before any privacy check, and the check runs for each reader afterwards, as the privacy deep dive describes. A cache of finished pages would need an entry per reader, which is no cache at all.
A cache helps the searches many people make. Most searches are made once, by one person, and a cache cannot help those. It earns its keep on the popular few, which is exactly where the spikes come from. Each Search API server keeps its hottest few thousand entries in its own memory. A shared Redis tier behind them holds more. A miss on one server is then usually a hit in Redis. The first page or two are worth caching; later pages are asked for far less often.
Most liked needs exact counts, and those change every second. So the cache keeps a most-liked search’s candidates, the posts up to where the walk stopped, with the same 5-second age. On every request it reads their exact counts from Redis, a few dozen in one batch. The page is then exact over candidates the index gave at most 5 seconds ago. Every entry also carries the time it was fetched from the index. Each tier counts its 5 seconds from that time, so copying an entry into a server’s memory does not restart its 5 seconds. The caching guide covers expiry and refresh in general. The hot key guide covers the same burst when one key is hot in a store rather than in a cache.
The interactive version of this example is available when JavaScript loads.
The experiment plays ten seconds of the spike three ways. The tabs are no cache, a cache that expires every 5 seconds, and a cache with one refresh at a time.
The interactive version of this example is available when JavaScript loads.
The gap: Thousands of people send the same search each second, and each would ask 20 partitions for the same answer.
Option 1: No cache
Every search goes to the index.
Works when: Traffic spread over many different searches.
Breaks when: One hot search sends 160,000 partition requests a second.
Option 2: Cache for 5 seconds
Keep each search’s post IDs for 5 seconds.
Works when: Searches made a few times a second.
Breaks when: Each expiry lets 400 copies of the search through at once, 8,000 partition requests in a burst.
Option 3: Cache, one refresh at a time (start here)
A miss is fetched once while others wait; an old entry is served while one refresh runs.
Works when: Always, for hot searches.
Watch for: Answers can be up to 5 seconds old, and the cache holds post IDs, so privacy is checked per reader after it.
In the interview: Open with the arithmetic: 8,000 searches a second times 20 partitions. Then show the burst at expiry, 400 searches in 50 ms, and fix it with one fetch per key. Say that the cache holds post IDs from before the privacy check.
Say this: Hot searches go through a cache keyed by the search in a standard form, holding post IDs for 5 seconds, which keeps newest-first results inside the 10-second freshness target. A miss is fetched once while other searches for the same key wait, and an old entry is served while one refresh runs, so an expiry never releases a burst. The cache holds IDs, not pages, and privacy is checked per reader afterwards.
Jonas makes a post friends-only. Who can still find it?
At 23:15:00 Jonas changes post P21 from public to friends-only. It named his carriage number, and he would rather strangers did not see it. Farah is not his friend. At 23:15:10 she searches “night train”. To keep the example small, use pages of ten.
The first design stores each post’s audience in the index beside its ID. It filters while it walks, keeping public posts and friends-only posts whose author is one of the reader’s friends. It is fast, and it is wrong for as long as the index lags. The audience change is a write like any other, and it reaches the index through the stream. On a normal day that takes a second. On a bad day an indexer is replaying after a restart and is 30 seconds behind. Until it catches up, the index still says P21 is public, and Farah’s page shows it.
Friend lists make it worse. The friends of Jonas change when he unfriends someone. If the index filtered by friendship, every unfriending would have to reach every partition holding one of his posts before any search was safe. Facebook’s search team decided not to try. The Unicorn paper says its index holds no privacy information at all, because “If a user ‘un-friends’ another user, the first user’s friends-only content immediately and irrevocably must become invisible to the second user. Even a 30-second lag-time is unacceptable.”
So the decision moves out of the index. The index finds candidates. Before any is shown, the Search API asks a privacy service, which reads the current audience and friend lists. That stops the leak, and it creates a new problem. Walk Farah’s search. The index returns the ten newest candidates. Six of them are friends-only posts by people who are not her friends, P21 among them. The page shows four posts, although many more she may read exist further down the list.
The fix keeps fetching while the page is short, with a limit. The Search API asks the index for the ten candidates after the tenth, checks them, and repeats. Round two finds four more she may see, eight in all. Round three finds five, and the page takes the first two of them, reaching ten after 30 candidates in three rounds. The limit matters. A search whose matches are nearly all private to this reader would otherwise walk the whole index. So the walk stops after 5 rounds and returns a short page with a cursor to continue. When the walk hits its limit, a short page is the honest answer.
A better first round asks for more than it needs. If a reader usually may see four candidates in ten, a page of 25 needs about 63 on average. Asking for exactly the average falls short almost half the time, about 43%. Asking for 80 falls short about 4% of the time, so the first round asks for 80. Each partition is asked for its best 80, since the merge is exact for any number, not only 25.
Say the index’s copy marks a post friends-only, and the author is not among the reader’s friends. The index may drop that post without asking, so the index can still save work, as long as it only removes candidates. If the copy is stale, a post made public in the last 30 seconds is missed until the index catches up. Every post the index keeps is still checked, because its copy may be the stale one. Used this way, a stale hint can hide a post for up to 30 seconds. It can never show a hidden one.
Results are not the only way to leak. A line such as “About 1,240 results” counts posts before the check, so a search for a rare word can confirm that a hidden post exists. Show counts only after the check, or not at all. The snippet under each result, the text with the search words highlighted, comes from the post fetched after the check, never from the index. And the cache from the hot-search deep dive holds post IDs, so the check runs on every page served from it.
The checks have a cost. At 40,000 searches a second, with about 80 candidates checked for each page of 25, the privacy service answers about 3.2 million questions a second. Most are answered from memory, because a post’s audience and a reader’s friend list are small, and “is Jonas one of Farah’s friends” is one lookup. That memory is updated before an audience change or an unfriending is acknowledged, so it is never behind the way the index can be. Unicorn’s authors call the price of keeping privacy out of the index “a modest efficiency penalty”.
The interactive version of this example is available when JavaScript loads.
The experiment builds Farah’s page three ways. The tabs are trusting the index’s copy of the audience, checking the first ten only, and checking while fetching more.
The interactive version of this example is available when JavaScript loads.
The gap: The index is a copy that can be seconds behind, and a privacy change must take effect at once.
Option 1: Filter by audience in the index
Store each post’s audience and filter while walking the lists.
Works when: Posts whose audience never changes.
Breaks when: The index lags: P21 shows for up to 30 seconds after Jonas hides it.
Option 2: Check the first page only
Take one page from the index and check each post with the privacy service.
Works when: Readers who may see almost every match.
Breaks when: Six of Farah’s first ten are hidden, so her page shows four.
Option 3: Check every result, fetch more while short (start here)
Ask for more candidates than a page, check each, and fetch again while the page is short, up to 5 rounds.
Works when: Always.
Watch for: A call per candidate, about 3.2 million a second at the peak, and a mostly private search returns a short page.
In the interview: Open with the rule: the index finds candidates and the privacy service decides, because the index can lag. Show the short page, then the refill with its limit. Mention counts and snippets if the interviewer asks what else can leak.
Say this: The index finds candidates, and every result is checked against the current audience and friend lists before it is shown, because the index can be seconds behind and a privacy change must apply at once. I fetch more candidates than a page needs and keep fetching while the page is short, up to a limit, then return a short page with a cursor. Counts and snippets come only from checked posts.
The interactive version of this example is available when JavaScript loads.
The code has four tabs: the AND walk, the most-liked walk, the indexer’s rule for applying a change, and one refresh per hot search.
If they ask: how does page two work?
Say page one of a newest-first search ends at post P40. Page two continues from after P40, never from a count of how many were shown. The cursor holds the sort and the last position: for newest first, the last post ID shown. For most liked it holds the last exact count shown and that post’s ID, because page one is sorted by exact counts, not by list order. If page one of the likes example ended at E with 4,050 likes, page two restarts the walk at bucket 2,048, the first that could hold 4,050. It keeps only posts with fewer likes, or 4,050 and a smaller ID. The next page walks the lists from just after that point, so posts that arrived since page one cannot shift it. With tiers, the cursor also records which tier the walk had reached, so page two does not ask the recent tier again for posts it has already passed. The cursor is signed, so a client cannot edit it into a different search. Between pages, a post that gains likes can jump above the cursor and be missed, and one that loses likes can appear again. So the app drops IDs it has already shown.
If they ask: filters, and finding your own post
Farah limits “night train” to the past week, or to posts by Jonas. Each filter is one more condition on the walk. For newest first, a time range is almost free, because the lists are sorted by time and the tiers are split by it. The walk starts at the range’s newest end and stops at its oldest. A most-liked search skips entries outside the range, or picks the tiers the range covers. An author filter indexes the author as a word of its own, “from:jonas”, whose list holds that person’s posts. It joins the AND like any other word.
Jonas expects to find his own post the moment he writes it. The index may be a second behind, and the cache up to 5 seconds more. So the Search API also reads the searcher’s own posts from the last minute. It adds any that match, in their place in the order. Other readers wait a few seconds, and the author never notices.
If they ask: you change how text is split into words. What happens to the index?
The indexers turn text into words with an analyzer: lowercase, split on spaces and punctuation, perhaps reduce “trains” to “train”. The same analyzer must run on every search, or “Trains” typed into search will not find “train” in the index. Changing the analyzer changes the words themselves, so every list must be rebuilt. Build the new index beside the old one from the posts database, catch it up from the change stream, and switch searches over once it has caught up. Twitter built the lists for nearly half a trillion posts in a batch job “in only about two days”, at times with well over a thousand builders running in parallel (Twitter).
If they ask: what about typos, or search by meaning?
Both are out of scope for this round, and both sit beside the index rather than inside it. A typo is fixed by rewriting the search before it reaches the index: “nigth train” becomes “night train” when the corrected form is far more common in past searches. Search by meaning, where “rail delay” finds “train late”, needs a vector for each post and a nearest-neighbour index, a second way of finding candidates. Its results go through the same privacy check and the same fetch from the posts database.
Walk one search through the final design
At 23:10:00 Jonas taps Post. The Post API saves P7 in the posts database. The change stream carries it to an indexer, which adds P7 to the lists of its 20 words in the recent tier. At the next refresh, one second later, it is searchable.
At 23:10:10 Farah searches “night train”, newest first. The Search API checks the result cache and finds no entry. It asks the 20 recent partitions. Each walks its list for “train”, the rarer word, jumps into “night” for each entry, and returns its newest 80 matches, the size of the first privacy round. The Search API merges them and stores the IDs in the cache for 5 seconds. It asks the privacy service about each candidate, fetching more while the page is short, and fetches the posts from the database. P7 is on the first page.
At 23:20:10 she switches to most liked in the past day, which the recent tier covers. Each recent partition walks its likes list for “train” in bucket order and keeps posts that are also in “night”. It reads exact counts from Redis until twice the next bucket cannot beat the page. P7, with 9,300 likes, is at the top. An all-time most-liked search would ask the popular tier first.
The interactive version of this example is available when JavaScript loads.
| Requirement | Where it is met | The trade-off |
|---|---|---|
| FR1 post | The posts database and its change stream, searchable in about a second | A new post can be missing from search for a second |
| FR2 like | Like rows keyed by user and post, counts in Redis, a bucket in the index at each doubling | The index knows likes only to within a factor of two |
| FR3 search words | Lists sorted by post ID, walked from the rarest word with skip pointers | A search costs as much as its rarest word |
| FR4 newest or most liked | A recent tier for newest; a popular tier and exact counts for most liked | Rare words reach every tier |
| Never show a hidden post | A privacy check on every result, with refill up to a limit | A mostly private search returns a short page |
How does the answer change for Twitter search, LinkedIn search or a document index?
| Interview variant | What carries over | What changes |
|---|---|---|
| Design Facebook post search | Everything on this page | The same problem; the privacy deep dive matters more, because friends-only posts are common |
| Design Twitter search | The index, freshness and tiers | Most posts are public, so privacy shrinks to deletes, blocked accounts and protected accounts, and a second from post to search is the headline |
| Design LinkedIn search | The index for posts | People, jobs and companies are separate indexes with their own ranking, merged into one results page |
| Design an inverted index for billions of documents | Word lists, the walk, splitting by document | Documents are long, so positions and compression matter more than freshness, and NOT becomes common |
| Design search without Elasticsearch | Everything on this page | The same question, with the constraint stated up front |
| Design hashtag search | The index, likes and hot searches | A hashtag is one word, so there is no AND, and most liked and hot searches dominate |
What should an answer reach at each level?
| Level | What the answer shows |
|---|---|
| Intern or mid-level | Explains an inverted index, AND as a walk over sorted lists, a posts database, and a search service that fetches the posts it finds. |
| Senior | Sorts lists by a time-ordered ID and stops at a page, walks the rarest word with skip pointers, feeds the index from the change stream, and keeps likes out of the index’s hot path. |
| Staff | Uses buckets with an exact stopping rule, splits by post into tiers and gives the tail arithmetic, collapses hot searches to one fetch, and checks privacy outside the index with a refill and a limit. |
| Principal | Decides the freshness and privacy promises and what they cost, how tiers grow and are rebuilt, and which searches are worth caching or precomputing. |
Test yourself with the quiz, then pick another problem from the System Design interview breakdowns.
By GOAT Engineer. Back to all breakdowns. Privacy Policy · Contact.