Design Facebook Post Search
Understanding the Problem
📝 What is post search? Post search lets users type a keyword like "taylor swift" or "#worldcup" and see matching status updates from across the platform, sorted either by most recent or by most liked. Unlike web search, the documents are short, there are enormous numbers of new ones every second, and the ranking signal (likes) changes constantly after a post is published.
You may hear this as "status search," "search over status updates," or as "design a search API that third-party developers can call." These are the same problem: the same index serves the app's search box and a public API. The API version adds authentication, rate limits, pagination and stricter rules about what can be returned, which we'll cover as its own requirement.
Interviewers often add a constraint: don't just use Elasticsearch. They want to see you build the inverted index yourself. We'll do that, and mention where an off-the-shelf engine would fit.
Functional Requirements
Core Requirements
- Users should be able to search posts by one or more keywords and get results sorted by recency or by like count.
- New posts, and changes to like counts, should be reflected in search results within about a minute.
- Third-party developers should be able to search public posts through an authenticated API.
Below the line (out of scope)
- Fuzzy matching, typo correction and synonyms.
- Personalized or ML-based ranking. Recency and likes are the two sort orders.
- Images, video and comments. Only post text.
- Creating posts and likes themselves. Other services own those; we consume their events.
Non-Functional Requirements
Ask about scale, and in particular about the ratio of writes to reads, because it's unusual here. We'll assume:
Core Requirements
- The system should handle about 1 billion new posts a day and 10 billion likes a day.
- The system should handle about 10k searches per second at peak.
- Searches should return in under 500ms.
- A new post or like should be reflected in search within 1 minute.
- Search should cover all posts ever made, though older posts may be slower to find.
Below the line (out of scope)
- Strong consistency. A like count in search results can be a few seconds or a few likes behind the real one.
- Exact result counts.
Do the arithmetic:
- Posts: 1B / 86,400 ≈ 12k posts per second, call it 30-40k at peak.
- Likes: 10B / 86,400 ≈ 115k likes per second, a few hundred thousand at peak.
- Searches: about 10k per second at peak.
So this system takes in more than ten times as many writes as it serves reads. If every like has to update the index, the like stream is the hardest part of the design.
For storage: a post has around 20 distinct indexable words, so 1B posts a day produce 20B index entries a day. At 8 bytes per post ID, that's 160 GB of posting data per day, or about 60 TB per year, before any overhead. Ten years of posts won't fit in memory, so we'll need to tier the index by age.
This is a good moment to tell your interviewer that the write path is where the design lives. Most candidates design a search problem from the read side; here the reads are comparatively easy and the 115k likes a second are what break naive designs.
The Set Up
Planning the Approach
We'll build the indexing and query path for keyword search first, then add likes as a ranking signal, then the third-party API. The deep dives cover the like write volume, the size of the index, query performance and the API's protections.
Defining the Core Entities
- Post:
postId,authorId, text,createdAt, visibility (public or restricted), and its like count. Post IDs are time-ordered (Snowflake-style), so sorting by ID is sorting by time. - Like: a user liked a post. We only care about the resulting count.
- Posting list: for one keyword, the post IDs that contain it. We keep two orderings: by recency and by likes.
- API client: a registered third-party app, with credentials, scopes and a rate limit.
API or System Interface
// In-app search
GET /search?q=world+cup&sort=recent|likes&cursor=<opaque>&limit=25
-> { results: [ { postId, authorId, text, createdAt, likeCount } ], nextCursor }
// Public API for third-party developers
GET /v1/posts/search?q=world+cup&sort=recent&cursor=<opaque>&limit=100
Authorization: Bearer <app access token>
-> { data: [ { id, text, created_at, like_count } ], next_cursor }
-> 429 { retry_after }
// Events we consume (owned by other services)
post_created { postId, authorId, text, visibility, createdAt }
post_deleted { postId }
like_added { postId, userId }
Cursors are opaque, so we can change what's inside (a post ID, a score, a snapshot time) without breaking clients.
High-Level Design
1) Users should be able to search posts by keyword, sorted by recency or likes
The tempting first version uses the posts database: SELECT ... WHERE text LIKE '%world cup%' ORDER BY created_at DESC LIMIT 25. A leading wildcard can't use a B-tree index, so this scans every post. With hundreds of billions of rows, it's hopeless.
We need an inverted index: for each keyword, the list of posts containing it. Building it is a streaming job:
- The Post Service writes the post to its own database and publishes
post_createdto Kafka. - An Ingestion Service consumes the event, tokenizes the text (lowercase, split on whitespace and punctuation, keep hashtags and mentions as tokens, drop very common stop words like "the"), and for each distinct keyword appends the post ID to that keyword's posting list.
- A Search Service handles queries by reading posting lists.
Where do the posting lists live? We need fast appends and fast reads of the first N entries, at tens of thousands of writes a second, which suggests an in-memory store. Redis fits well:
- By recency: a list per keyword. Post IDs are time-ordered, so new posts simply go to the front:
LPUSH idx:recent:worldcup <postId>. The first 25 entries are the 25 newest posts. - By likes: a sorted set per keyword, scored by like count:
ZADD idx:likes:worldcup <likeCount> <postId>.ZREVRANGE ... 0 24gives the most liked.
A single-keyword search is one read from Redis, plus a batch lookup of the post details (text, author) from a post cache. A multi-keyword search like "world cup" intersects the lists: read the top entries for each keyword and keep the post IDs in all of them (for sorted sets, ZINTERSTORE does this inside Redis, but only when the keys are on the same shard, which we'll come back to).
The posting lists only store IDs. The text and author live once in the Post DB (Cassandra or DynamoDB, keyed by postId) with a cache in front, and the Search Service "hydrates" the final 25 IDs into full results.
2) New posts and like changes should appear in search within a minute
New posts are already handled: the Ingestion Service indexes them within seconds of the event.
Likes are the problem. The simple approach mirrors posts: the Like Service publishes like_added to Kafka, and the Ingestion Service, for each like, looks up the post's keywords and bumps the score in each keyword's sorted set with ZINCRBY.
That works, but look at the numbers: 115k likes a second times about 20 keywords per post is over 2 million sorted-set updates a second on average, several times that at peak, and most of them go to posts that are already far down the rankings. We also need to know each post's keywords at like time, which means storing them (a postId -> keywords table) or re-tokenizing the text.
We'll keep this structure for now and fix the volume in the first deep dive.
3) Third-party developers should be able to search public posts through an API
External developers call a separate endpoint that reuses the same Search Service but goes through an API Gateway that adds what internal callers don't need:
- Authentication: apps register and get credentials; calls carry an OAuth access token (client credentials for app-level access). The gateway validates it and attaches the app's ID and scopes.
- Rate limiting and quotas per app, say 300 requests per 15 minutes on a free tier, more for paid tiers.
- Visibility rules: the API only returns public posts, never posts restricted to friends, whatever the in-app search might show.
- A stable, versioned contract:
/v1/..., its own response schema (snake_case, documented fields), and opaque cursors.
The gateway keeps external traffic from competing with in-app search. Partner traffic gets its own pool of Search Service instances (a bulkhead), so a partner hammering the API can't slow down search for users of the app.
Potential Deep Dives
1) How do we handle 115k likes a second?
This is the core write problem. Every option has to keep "sort by likes" roughly correct within a minute.
Bad Solution: Update Every Keyword on Every Like
Approach
The high-level design as is: for each like, ZINCRBY the post's score in every keyword's sorted set.
Challenges
Millions of Redis writes a second, mostly to posts nobody will see in search. A viral post getting 50k likes a minute generates 50k × 20 updates to the same keys, creating hot shards. And the like stream is far bigger than the post stream, so the index ends up sized for likes rather than for searches.
Good Solution: Batch Likes per Post
Approach
Put a stream processor (Flink, or Kafka Streams) between the like events and the index. It counts likes per post in short windows, say 30 seconds, and emits one update per post per window: postId: +412. The Ingestion Service then applies one ZINCRBY per keyword per post per window instead of one per like.
A post that gets 50k likes in a minute now causes 2 updates per keyword, not 50,000. The total update rate is now bounded by the number of distinct posts liked per window, which is much smaller than the number of likes.
Challenges
It's still a lot of writes. Many posts get a handful of likes each, and each of those still costs 20 index updates per window. And we're still keeping exact counts in the index, which search doesn't need.
Great Solution: Update the Index Only at Like Milestones
Approach
Search doesn't need the exact like count to rank well; it needs the right order of magnitude. A post with 1,000 likes and one with 1,003 are equally good results. So we only update the index when a post's count crosses a milestone: 1, 2, 4, 8, 16... (powers of two). The exact count lives in a separate Like Counter store (owned by the Like Service, or a Redis counter we maintain from the same stream).
A post that ends up with 1 million likes crosses only about 20 milestones in its life, so it updates its index entries about 20 times instead of a million. Across the whole system, the update rate falls by orders of magnitude.
At query time, we correct for the approximation with a two-stage read:
- Fetch more candidates than needed from the sorted set, say the top 100 by milestone score for the top 25 results.
- Look up their exact counts in the Like Counter (one batched read) and re-sort.
Since the milestone scores are within a factor of two of the truth, the true top 25 are almost always inside the top 100.
Challenges
Ranking near a milestone boundary is fuzzy: a post at 1,020 likes (milestone 1,024 not yet reached) is stored with score 512 and can briefly rank below a post at 600. The re-sort fixes this within the top 100 candidates. If the interviewer wants a finer index, use smaller steps (powers of 1.5), trading more writes for more accuracy.
The general idea, "write to the index only when the change could matter to a reader," is worth naming. It appears in leaderboards, trending systems and feeds: decouple the exact counter from the coarse ranking structure, and reconcile at read time.
2) How do we store an index this big?
At 20B new entries a day, the index grows by about 60 TB of raw post IDs a year, and much more in Redis, where a sorted-set entry costs on the order of 50-100 bytes with overhead. Keeping years of posts in memory isn't affordable.
Bad Solution: Keep Everything in Redis
Approach
Scale the Redis cluster to hold every posting list for all time.
Challenges
Petabytes of RAM. And almost none of it is read: search traffic heavily favors recent posts (recency is the default sort), and "most liked" queries mostly hit the same few thousand posts per keyword.
Good Solution: Cap What Lives in Memory
Approach
Observe that searches read only the head of each list. So for each keyword, keep in Redis only:
- the most recent posts, by time window (say the last 7 days), and
- the top few thousand posts by likes, regardless of age.
Trim on write: after LPUSH, LTRIM keeps the recent list bounded; a periodic job trims the sorted sets to their top entries with ZREMRANGEBYRANK. Common keywords like "love" or "happy" get millions of posts a week, so we also cap the recent list by count per keyword.
Challenges
Searches that go deeper ("show me posts about my small town from 2019") find nothing. That breaks the requirement to cover all posts.
Great Solution: Hot and Cold Tiers
Approach
Split the index by time:
- Hot tier (Redis): the last few days of postings per keyword, plus the top posts by likes. Serves almost all queries.
- Cold tier (blob storage): everything older. A batch job runs daily and writes that day's postings as immutable index segments to S3: files sorted by keyword, each keyword's post IDs compressed with delta encoding. A small dictionary maps each keyword to an offset in the file. A Cold Search service reads the right segment ranges (with a local cache for popular ones) when the hot tier runs out.
The Search Service reads the hot tier first. If it can't fill the page and the user keeps scrolling, it continues into the cold segments, newest day first, using the cursor to remember where it stopped. Recency-sorted queries naturally walk backwards in time. For likes-sorted queries, each day's segment stores its keywords' postings sorted by the like milestone at segment-build time, and a separate yearly "best of" list per keyword covers the most liked posts of all time.
Cold searches are slower (tens to hundreds of milliseconds per segment read from S3), which is acceptable for deep pagination.
Challenges
It's more code: segment format, a compaction job to merge daily segments into weekly and monthly ones (so a query for 2019 doesn't open 365 files), and cursor logic that spans tiers. If your interviewer allows it, Elasticsearch or OpenSearch with time-based indices (one index per day or week, older ones moved to cheaper nodes) gives you the same hot/cold shape out of the box.
Sharding the hot tier. A Redis cluster shards by key, so each keyword's posting list lives on one shard. That's ideal for single-keyword queries (one shard, one read) but means a very hot keyword ("#worldcup" during a final) puts all its writes and reads on one shard. Split hot keywords by time bucket (idx:recent:worldcup:2026-11-29T14), so writes rotate to new keys every hour, and replicate the read side. Multi-keyword intersections across shards happen in the Search Service: fetch the head of each list in parallel and intersect in memory.
3) How do we keep searches fast, including multi-keyword and popular queries?
Most searches are fine: one or two Redis reads and a batched post lookup. Two cases need more care.
Multi-keyword queries over long lists. "world cup" intersects two lists that may each have millions of recent entries. Reading them in full is slow. Instead:
- Read lists in chunks from the head (newest first) and intersect as you go, stopping once you have enough results. Because both are sorted by post ID, this is a merge, and for recency queries the newest matches surface first.
- Start from the rarer keyword and check its candidates against the more common one's posts (or against each post's text directly, from the post cache).
- For pairs that are queried very often, index the bigram as its own keyword (
world_cup), turning an intersection into a single list read. The ingestion service can do this for the top few thousand bigrams seen in the query log.
Popular queries. During a big event, thousands of people search the same thing. Cache results per (normalized query, sort) in Redis or a CDN, with a short TTL: 10-30 seconds for recency (new posts arrive constantly, and a few seconds of staleness is invisible) and a minute or two for likes. The hottest queries then cost one cache read. This doubles as protection: a viral search can't stampede the index.
Deletions and privacy changes. A deleted post must disappear from search quickly, but removing it from 20 posting lists in Redis and from immutable cold segments is expensive. Instead, keep a tombstone set of deleted or hidden post IDs (a Redis set, plus a Bloom filter for the cold tier) and filter results through it during hydration. The hydration step reads the post anyway, so it also checks the post's current visibility. Background jobs clean tombstoned IDs out of the lists and the next compaction drops them from segments.
When results go through a "fetch IDs from the index, then hydrate from the source of truth" step, that step is the natural place for anything that has to be exactly right right now: deletions, visibility, exact like counts. The index can then be approximate and lazily cleaned.
4) How do we protect the third-party API?
External callers are a different trust level: they're automated, sometimes abusive, and they build products that break when our API changes.
Bad Solution: Expose the Internal Endpoint with an API Key
Approach
Hand out API keys and let partners call the same /search the app uses.
Challenges
Partners would see whatever the in-app search returns, which may include posts visible only to the logged-in user, so a third-party app could see restricted posts. There's no per-partner limit, so one scraper can consume the whole search capacity. And every internal change to the response breaks someone's integration.
Good Solution: A Separate, Rate-Limited, Public-Only Endpoint
Approach
Build the API as described in the high-level design: OAuth tokens, a versioned /v1 endpoint with its own schema, a filter that only allows public posts, and per-app rate limits. The rate limiter is a token bucket per app, kept in Redis: each request does an atomic decrement (in a Lua script), and the gateway returns 429 with Retry-After when the bucket is empty. Responses carry X-RateLimit-Remaining headers so well-behaved clients can pace themselves.
Challenges
Rate limits per request don't stop someone from scraping everything slowly over weeks, and offset-based paging (page=500) gets slower and inconsistent as new posts arrive.
Great Solution: Add Cursors, Depth Limits, Quotas and a Stream
Approach
On top of the good solution:
- Cursor pagination. The cursor encodes the last returned position (post ID for recency, score plus post ID for likes) and is signed so clients can't forge one. New posts arriving at the top don't shift the next page, so clients never see duplicates or gaps.
- Depth and window limits. The standard tier searches only the last 7 days, and a query can page through at most a few thousand results. Full-archive search is a separate, more expensive product tier, served from the cold index with a lower rate limit.
- Monthly quotas per app (posts returned per month), tracked asynchronously from gateway logs, on top of the short-term rate limit.
- A filtered stream for real-time use cases. Partners who poll search every second ("give me everything new about our brand") are the most expensive callers. Offer a streaming endpoint instead: partners register keyword rules, a stream job matches new public posts against all rules as they're ingested (an inverted index over the rules, so each post checks only rules for its own keywords), and matching posts are pushed over a long-lived HTTP connection or webhooks. Polling load disappears.
- Compliance. Partners must delete posts that were deleted on the platform. Publish deletion events on the stream as well, and make it part of the terms of use.
Challenges
More product surface to maintain. Interviewers rarely want all of it; pick cursors and rate limits as the must-haves, and mention the filtered stream as the answer to "partners keep polling us."
Final Design
The full flow:
- When a post is created, the Post Service stores it and publishes
post_created. The Ingestion Service tokenizes it and pushes its ID onto the recent list for each keyword, and adds it to each keyword's likes sorted set with a starting score. - Like events go through a Flink job that maintains exact counts in the Like Counter and emits an index update only when a post crosses a like milestone.
- A daily job moves postings older than a few days from Redis into compressed, immutable segments in S3, and compacts older segments.
- In-app searches go to the Search Service, which checks the query cache, reads the hot tier (and the cold tier for deep pages), intersects keywords, fetches extra candidates, re-sorts likes queries by exact counts, filters tombstones and visibility, and hydrates the results from the post cache.
- Third-party requests go through the API Gateway for authentication, rate limits and quotas, then to an isolated pool of Search Service instances restricted to public posts, with signed cursors. Partners with real-time needs use the filtered stream instead of polling.
What is Expected at Each Level?
Mid-level
You should explain why a LIKE query fails and build an inverted index from keywords to post IDs, populated asynchronously from post events. You should support both sort orders (a recency list and a likes-scored set are fine) and hydrate IDs into posts. With prompting, you should notice that likes generate a lot of index updates and propose batching them, and add caching for popular queries.
Senior
You should do the write math early and identify likes as the main scaling problem, then reduce index updates with batching or milestones and correct the order at read time. Expect to discuss index size and a hot/cold split, sharding by keyword and what happens to a hot keyword, multi-keyword intersection, and deletions. For the API, you should cover OAuth, per-app rate limits, public-only filtering and cursor pagination.
Staff+
You should frame the problem around the asymmetry between writes and reads and around which parts need to be exact (visibility, deletions) versus approximate (like order). Expect to argue when to build the index yourself and when Elasticsearch with time-based indices is the better choice, to handle the operational side (compaction, rebuilding the index from Kafka or the Post DB after a bug), and to treat the public API as a product: versioning, tiers, quotas, the filtered stream, and partner compliance with deletions.