Design Post Search

How to design keyword search over social media posts sorted by recency or likes, and what interviewers ask about the index, like counts and sharding.

Case study27 minLesson 2 of 10
On this page
  1. Clarify the problem
  2. Estimate the scale
  3. Define the API (optional)
  4. Model the data
  5. High-level design
  6. Deep dives
  7. Bottlenecks and failures
  8. What a strong answer sounds like
  9. Follow-up questions

Post search lets users of a social network type keywords and get back the public posts that contain all of them, sorted by recency or by likes. Interviewers ask about it because the index is written to far more often than it is queried, and because sorting by likes means ordering results by a number that changes many thousands of times a second.

This case study builds on Search Systems and follows A Framework for Any Design.

Clarify the problem

The first five minutes
Interviewer

Design search for posts on a social network.

You

Should users be able to type keywords and get matching public posts, either newest first or most liked first? Do we need phrase search, typo tolerance or personalised ranking?

Interviewer

Both sort orders are needed. All of the words must match. There are no phrases, no typo tolerance and no personalisation.

You

How many posts, likes and searches are there per day?

Interviewer

500 million posts a day, 10 billion likes a day and 200 million searches a day. Search covers every post ever made.

You

Then the index receives far more writes than queries. I will aim for new posts to be searchable within 10 seconds, results in under 500 ms, and like order that may lag by a minute.

The functional requirements are to search public posts by keywords that must all match, sort by newest or most liked, optionally limit the time window, and page through results.

The non-functional requirements are that a new post is searchable within 10 seconds, 99% of searches finish within 500 ms, like order may lag by about a minute, deleted posts disappear within seconds, and search keeps working when part of the index is down.

Typo tolerance, phrase search, personalisation, private posts and autocomplete are out of scope; autocomplete is covered in Design Typeahead Search.

Estimate the scale

The estimates use 86,400 seconds a day and a peak of three times the average.

  • New posts arrive at 500 million ÷ 86,400, which is about 5,800 a second on average and about 17,000 a second at peak.
  • Likes arrive at 10 billion ÷ 86,400, which is about 116,000 a second, or 20 times the rate of new posts.
  • Searches arrive at 200 million ÷ 86,400, which is about 2,300 a second on average and about 7,000 a second at peak.
  • That is (5,800 + 116,000) ÷ 2,300, or about 50, write events for every search.
Estimate: Index growth per day

How much does the inverted index grow each day?

You know
  • 500 million posts a day
  • About 30 tokens per post
  • About 5 bytes per posting, compressed

Show the working
  1. Postings: 500 × 106 × 30 = 1.5 × 1010 a day
  2. 1.5 × 1010 × 5 B = 7.5 × 1010 B = 75 GB a day
  3. Last 7 days: 7 × 75 = 525 GB. One year: 75 GB × 365 ≈ 27 TB

Estimate 75 GB (anything from 25 GB to 250 GB is a good answer)

A week of index fits in memory with 3 replicas (about 1.6 TB) but a year does not, so the design has a recent tier and an older tier.

Your turn: Define the API

Write the search endpoint. How does the client get the next page for each sort order?

Compare with a model answer

Use one GET endpoint that takes the query, the sort order and an optional time window. For newest first, the cursor means "posts older than id X". For most liked, the counts keep changing, so the cursor refers to a short-lived saved copy of the ranked list.

Define the API Optional

Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.

HTTP API
GET /v1/search?q=ferry+strike&sort=recent&limit=20&cursor=...
GET /v1/search?q=ferry+strike&sort=likes&since=2026-10-15&limit=20
  200 { "results": [ { "post_id": "1849...", "author": "...", "text": "...",
                       "likes": 1532, "created_at": "..." } ],
        "next_cursor": "...", "partial": false }
  400 Bad Request     empty query, or more than 10 words
  410 Gone            cursor snapshot expired; start again

The decision worth arguing about is pagination. For sort=recent, post ids are ordered by time (see Unique IDs), so the cursor can mean "ids smaller than the last one shown", and new posts never shift the pages already seen.

That does not work for sort=likes, because a post can gain 500 likes between two page requests and move in the list. The server therefore ranks once and keeps the ordered ids for 10 minutes, and the cursor refers to that saved list. The partial field tells the client that some shards did not answer in time, since a result missing a few posts beats an error.

Your turn: Model the data

What does the index store for each post, and where do the like counts live so that sorting by likes does not require rewriting the index?

Compare with a model answer

The index stores the post id, the tokens and a coarse like tier. The exact counts live in a key-value store that is read at query time. The posts database owns the text and the deleted flag.

Model the data

Records
posts DB (source of truth, partitioned by post_id)
  post_id     64-bit, time-ordered     text        up to 1 KB
  author_id   64-bit                   status      live | deleted
 
index document (one per post, never stores the text)
  post_id     64-bit                   tokens      ["ferry", "strike", ...]
  like_tier   0..6                     -- 0: 0-9 likes, 1: 10-99, 2: 100-999 ...
 
index layout
  one index per day  ->  split into N shards by hash(post_id)
 
like_counts (key-value, partitioned by post_id)
  post_id -> count, last_offset

The posts database is read by key for the text of 20 results, so a key-value or wide-column store fits. The search index answers "which post ids contain all of these words", so it is an inverted index, in a search engine such as Elasticsearch or a purpose-built one. The like counts are updated constantly and read in batches, so an in-memory key-value store backed by a durable table fits. The index document holds no text, so deletions are applied in only one place.

Your turn: High-level design

Sketch how a new post and a like reach the index and the count store, and how a search is answered.

Compare with a model answer

Posts and likes arrive as events on a stream. Indexers add posts to today's index. An aggregator batches likes into the count store and tells the indexers only when a post moves to a different tier. A search checks a cache, asks the shards, reads counts for the likes sort and then fetches the text.

High-level design

Writes arrive as events and never block search. A query tries the cache, then the recent shards, and reaches the older index only when a page is not full.App to Search service (GET /search); Search service to Query cache (get / set); Search service to Recent index (7 days) (top 20 per shard); Search service to Older index (if page not full); Search service to Posts DB (text, deleted?); Search service to Like counts (counts); Post + like events to Like counts (likes, batched), asynchronous; Post + like events to Indexers, asynchronous; Indexers to Recent index (7 days) (posts, tier moves); Indexers to Older index (roll-over, tier moves).AppQuery cacheSearch servicePosts DBLike countsRecent index (7days)Older indexPost + likeeventsIndexersGET /searchget / settop 20 per shardif page not fulltext, deleted?countslikes, batchedposts, tier movesroll-over, tier moves

request and replyasynchronous message

Writes arrive as events and never block search. A query tries the cache, then the recent shards, and reaches the older index only when a page is not full.
A post, its likes, a search, and two failuresUse the arrows or ← → keys
  1. A post, its likes, a search, and two failures, step 1App to Search service; Search service to Query cache; Search service to Recent index (7 days); Search service to Older index; Search service to Posts DB; Search service to Like counts; Post + like events to Like counts, asynchronous; Post + like events to Indexers, asynchronous; Indexers to Recent index (7 days); Indexers to Older index.AppQuery cacheSearch servicePosts DBLike countsRecent index (7days)Older indexPost + likeeventspost 9120Indexers

    1Ana posts "Ferry strike again today". The post is saved in the posts database, and change data capture publishes it to the stream.

  2. A post, its likes, a search, and two failures, step 2App to Search service; Search service to Query cache; Search service to Recent index (7 days); Search service to Older index; Search service to Posts DB; Search service to Like counts; Post + like events to Like counts, asynchronous; Post + like events to Indexers, asynchronous; Indexers to Recent index (7 days); Indexers to Older index.AppQuery cacheSearch servicePosts DBLike countsRecent index (7days)9120 in tier 0Older indexPost + likeeventsIndexers

    2An indexer turns the post into tokens and adds it to one of today's shards, where it is searchable within a second.

  3. A post, its likes, a search, and two failures, step 3App to Search service; Search service to Query cache; Search service to Recent index (7 days); Search service to Older index; Search service to Posts DB; Search service to Like counts; Post + like events to Like counts, asynchronous; Post + like events to Indexers, asynchronous; Indexers to Recent index (7 days); Indexers to Older index.AppQuery cacheSearch servicePosts DBLike counts9120: 1,100Recent index (7days)Older indexPost + likeeventsIndexers

    3The post gets 300 likes in one second and goes from 800 to 1,100. The aggregator adds 300 to the count store once and does not touch the index.

  4. A post, its likes, a search, and two failures, step 4App to Search service; Search service to Query cache; Search service to Recent index (7 days); Search service to Older index; Search service to Posts DB; Search service to Like counts; Post + like events to Like counts, asynchronous; Post + like events to Indexers, asynchronous; Indexers to Recent index (7 days); Indexers to Older index.AppQuery cacheSearch servicePosts DBLike countsRecent index (7days)9120 in tier 3Older indexPost + likeeventsIndexers

    4Passing 1,000 likes moves the post from tier 2 to tier 3, so its index document is updated once. Over its life it has caused three updates, at 10, 100 and 1,000 likes.

  5. A post, its likes, a search, and two failures, step 5App to Search service; Search service to Query cache; Search service to Recent index (7 days); Search service to Older index; Search service to Posts DB; Search service to Like counts; Post + like events to Like counts, asynchronous; Post + like events to Indexers, asynchronous; Indexers to Recent index (7 days); Indexers to Older index.AppQuery cachemissSearch servicePosts DBLike countsRecent index (7days)Older indexPost + likeeventsIndexers

    5Leo searches for "ferry strike", newest first, and the query is not in the cache.

  6. A post, its likes, a search, and two failures, step 6App to Search service; Search service to Query cache; Search service to Recent index (7 days); Search service to Older index; Search service to Posts DB; Search service to Like counts; Post + like events to Like counts, asynchronous; Post + like events to Indexers, asynchronous; Indexers to Recent index (7 days); Indexers to Older index.AppQuery cacheSearch servicePosts DBLike countsRecent index (7days)hedgedOlder indexPost + likeeventsIndexers

    6Each shard reads its lists from the newest id downwards and stops after 20 matches. One replica is slow, so after 50 ms the service asks another replica and uses the first answer.

  7. A post, its likes, a search, and two failures, step 7App to Search service; Search service to Query cache; Search service to Recent index (7 days); Search service to Older index; Search service to Posts DB; Search service to Like counts; Post + like events to Like counts, asynchronous; Post + like events to Indexers, asynchronous; Indexers to Recent index (7 days); Indexers to Older index.AppQuery cacheSearch servicePosts DB1 deletedLike countsRecent index (7days)Older indexPost + likeeventsIndexers

    7The service merges the shard lists into the newest 20, fetches their text and drops one deleted post. The older index was not needed, and the ranked ids are cached for 15 seconds.

  8. A post, its likes, a search, and two failures, step 8App to Search service; Search service to Query cache; Search service to Recent index (7 days); Search service to Older index; Search service to Posts DB; Search service to Like counts; Post + like events to Like counts, asynchronous; Post + like events to Indexers, asynchronous; Indexers to Recent index (7 days); Indexers to Older index.AppQuery cacheSearch servicePosts DBLike countsRecent index (7days)Older indexPost + likeeventsbacklog 60 sIndexersdown

    8An indexer crashes. New posts wait in the stream and become searchable late, but none are lost, and the indexer resumes from its saved offset when it restarts.

1 / 8

Deep dives

Indexing new posts quickly

Postings lists are sorted and compressed, which makes them cheap to read and expensive to edit. At peak there are about 17,000 new posts a second, or about 510,000 postings a second (17,000 × 30 tokens), so editing lists in place would mean locking and rewriting them constantly.

The alternative is immutable segments. The indexer buffers new posts in memory and, once a second, writes them as a small new segment with its own postings lists. A search reads every segment of a shard and merges the results, and a background job merges small segments into larger ones. This is the same idea as log-structured storage in a key-value store. A deleted id goes on a list that search skips and is removed at the next merge.

Time-ordered ids also help, because a new post is appended to the end of each list it appears in, and a newest-first query can read the lists from the end and stop as soon as it has 20 ids that appear in all of them. The older entries are never read.

Answering a multi-word query

Every word of a query must match, so a shard looks up the postings list of each word and intersects them, meaning it keeps only the post ids that appear in all of the lists. The shard starts with the shortest list and checks its ids against the longer ones, so a query that contains a rare word does little work even if another word appears in millions of posts.

Sorting by likes without rewriting the index

The problem is that the likes sort needs a number that changes 116,000 times a second, and the index is expensive to update. There are four ways to handle it.

Update the document on every like. The index always holds the exact count, but that is 116,000 delete-and-reinsert operations a second, mostly for posts nobody searches for.

Keep counts outside the index only. Likes never touch the index, but a query such as "most liked posts about weather" may match 10 million posts, and each needs a count lookup before sorting.

Refresh the counts in bulk. A batch job rewrites changed counts every 10 minutes. A viral post shows a count that is up to 10 minutes old.

Store a tier in the index and exact counts outside it. The tier is the number of digits in the like count minus one (0 to 9 likes is tier 0, 10 to 99 is tier 1, 100 to 999 is tier 2 and so on), so it changes only when the count crosses a power of ten. The exact counts live in the key-value store and order the posts within a tier.

Keeping like counts sortable
OptionGood atBad atPick it when
Update the document on every likeSorting is built in and the count is exact.It causes 116,000 index rewrites a second.Choose this when counts change rarely.
Counts outside the index onlyLikes never touch the index.A broad query needs millions of count lookups.Choose this when queries match few documents.
Periodic bulk refreshChanged counts are written in one batch.Counts are up to 10 minutes old.Choose this when fresh popularity matters little.
Tiers in the index, exact counts outside Usual defaultThe index changes only a few times per post.Two stores must stay in step.Choose this when both the like rate and the query rate are large, as here.

The choice is tiers. A post with 1 million likes changes tier 6 times, not a million times, so the index sees far fewer updates than the like stream.

A likes query reads the highest tier first and works down. Suppose "ferry strike" matches 4 posts in tier 4 and 150 in tier 3. Every post in a lower tier has fewer likes than every post in tier 3, so these 154 posts contain the top 20. The service fetches their exact counts in one batch, sorts them and returns 20.

A broad word over 30 days can put 50,000 matches into one tier. Each shard then sends only its newest few hundred from that tier, which bounds the work but makes the order approximate. The aggregator sums likes per post once a second before writing, as in Design Photo Sharing, and stores the last applied stream offset with each count so that replayed events are not counted twice.

Sharding the index

One machine cannot hold or search a year of posts, so the index must be split.

Partitioning by term puts the whole postings list of each word on one machine. A query for "ferry strike" then needs two lists from two machines, which must be sent over the network to be intersected, and a new post must be written to about 30 machines, one for each token.

Partitioning by document assigns each post to a shard by hash(post_id), and each shard holds a complete small index of its own posts. A new post is written to one shard. The cost is that every query goes to every shard and the results are merged. This is the usual choice, as Search Systems explains.

Splitting by time first gives each day its own index, split into shards by document. All writes go to today's index, newest-first queries read only the latest days, and an old day, which never gets new posts, can be merged into one large segment on cheaper machines. The cost is more fan-out, since a year-long query reads 365 daily indexes times their shards. Older days are therefore rolled up into weekly and monthly indexes, and likes queries default to a 30-day window.

The choice is time first, then document. With 20 shards, a query that waits for all of them is slow whenever any one shard is slow, and if each is slow 1% of the time, the query is slow 1 − 0.9920 ≈ 18% of the time. The search service therefore sends a hedged request: if a replica has not answered within 50 ms, it asks another replica and uses the first answer.

Keeping recent data in memory and caching queries

The problem is that almost every newest-first query is answered from recent posts, while the whole index is too large for memory. The recent 7 days of index (525 GB) are kept in memory with 3 replicas, and older data (about 27 TB a year) sits on SSDs with fewer replicas. If the older index is unavailable, the service returns recent results with partial: true.

During a news event thousands of users search for the same words, so the service caches the ranked ids for 15 seconds, keyed by normalised query, sort order and window. For finished days it also caches per-shard results for an hour, because those indexes rarely change.

Bottlenecks and failures

At 10 times the load (5 billion posts a day), today's index receives about 170,000 posts a second at peak and needs about 10 times as many shards. The like aggregators scale out because the stream is partitioned by post id. Fan-out latency suffers first, and rolling old days into larger indexes and narrowing the default windows reduces it.

When this failsWhat happensWhat you do
An indexerNew posts become searchable late.The indexer resumes from its saved offset in the stream.
A recent-index replicaA shard has one copy fewer.Queries use the other replicas while this one is rebuilt.
A whole shardAbout 1 in 20 of that day's posts is missing from results.The service returns partial: true and alerts the on-call engineer.
The like count storePosts cannot be ordered exactly within a tier.The service sorts by tier and then by recency, and marks the order as approximate.
The query cacheEvery search reaches the shards, 7,000 a second at peak.The shards are sized for that load, so the cache is a saving and not a requirement.
The whole indexSearch is down.The index is rebuilt from the posts database, starting with the newest days.

What a strong answer sounds like

LevelWhat the answer does
JuniorPuts posts in a search engine, sorts in the query and adds a cache.
MidFeeds the index from a change stream, shards by document, and keeps the fast-changing like counts outside the index.
SeniorStarts from the 50-to-1 ratio of writes to searches, splits by time and then by document, uses tiers for likes with the arithmetic, and explains tail latency caused by fan-out.
Sorting by likesStrong answer
Interviewer

How do you sort results by likes?

You

Likes arrive at about 116,000 a second, so they cannot each rewrite the index. I would index a power-of-ten tier, which changes only a few times per post, and keep the exact counts in a key-value store.

Interviewer

How does a query use that?

You

It reads the top tiers until it has at least 20 candidates, looks up their exact counts in one batch and sorts them. A post that has just crossed a tier can be misplaced for a few seconds, which is acceptable because like order may lag by a minute.

Follow-up questions

How do you add relevance ranking?

Each shard returns a few hundred candidates chosen with a cheap score such as text match, tier and recency. The service merges them and re-ranks the merged list with a more expensive model, so the costly scoring runs on only a few hundred posts.

A post is deleted. How quickly does it disappear?

It disappears from results immediately, because the service filters out deleted ids when it fetches the text. The index entry is marked dead within a few seconds and removed at the next merge.

How would you search hashtags or a single user's posts?

A hashtag is one more token in the index document. A single user's posts need an author_id field and a filter on it.

How do you change the analyser, for example to add stemming?

You build new indexes beside the old ones from the posts database, newest days first, and switch reads over one day at a time. Because each day has its own index, the change can be rolled back for a single day.

The system adds about 75 GB of index a day and about 5,800 new posts a second, which is more than the text index of a single database can absorb, and such an index cannot easily be split by time. For a few million posts it would be the right first answer.

Self-review: post search0 of 10

After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".

Before drawing

Numbers and interfaces

Design and depth

Failure