Show each user a ranked stream of posts from people they follow, fast, even for celebrities.
“Design a news feed, like the home timeline on Facebook, Instagram or Twitter.”
It is short on purpose. Your first job is to make it specific.
| What they check | Why it matters |
|---|---|
| Finding the real problem | The prompt looks like a list query. The real problem is fan-out: one post must reach hundreds, or millions, of feeds. A strong candidate says so early and does the maths. |
| Write path versus read path | Push, pull and hybrid are three answers to one question: do the work when someone posts, or when someone reads? The interviewer wants the reasoning, not a memorised answer. |
| Handling the skewed case | Most accounts have a few hundred followers and a few have tens of millions. A design that only works for the average account fails in the first follow-up. |
| Caches and pagination | A feed is a cached list per user, filled with IDs and hydrated into full posts. Pagination must stay stable while new posts arrive. |
| Trade-offs and honesty | Fresh versus cheap, ranked versus simple, exact versus eventual. There is no perfect feed, only reasoned choices and clear limits. |
A news feed is a per-user list of post IDs that we keep ready in a cache, so opening the app is one fast read. The hard part is filling those lists: when someone posts, who does the work, and when?
| Step | Minutes | What to get done |
|---|---|---|
| 1. Clarify | 4 | Chronological or ranked, follow graph shape, celebrities, media, how fresh, scale. |
| 2. Estimate | 3 | Posts per second, feed opens per second, fan-out inserts per second, feed cache size. |
| 3. API and data | 5 | Post, follow, get feed with a cursor. Posts, graph, feed cache. |
| 4. High-level design | 8 | Post service, fan-out queue, feed cache, graph, ranking. One write path, one read path. |
| 5. Deep dives | 15 | Fan-out strategy and the celebrity problem, feed storage and pagination, ranking, the graph and deletes. |
| 6. Scale and failures | 7 | Fan-out backlog, lost cache, hot posts, counters, multi-region. |
| 7. Wrap up | 3 | Recap, trade-offs, what you would do next. |
| Ask | Why you ask it | Typical answer | How it changes the design |
|---|---|---|---|
| What is in the feed: posts only from people you follow, or also suggestions and ads? | Suggestions need a recommendation system, which is a different problem. | Posts from accounts you follow. Ads and suggestions can be added later. | We build the follow-based feed and leave a clean place to insert other items. |
| Is it newest first, or ranked by relevance? | Chronological is a sorted list. Ranked needs scoring and a second stage. | Ranked, but simple: recent, close to you, and engaging. | A cheap two-stage ranker after we collect the candidates. |
| How many users, how many posts a day, and how many accounts does a user follow? | These numbers decide whether fan-out is a problem. | 300M daily users, 2 posts a day each, about 200 followers on average. | Fan-out is about 1.4M inserts a second, so push is a real cost. |
| Are there accounts with millions of followers? | This is the question that breaks the simple design. | Yes. Some have 50M followers. | We need a hybrid, with a different path for large accounts. |
| How fresh must the feed be? Is a few seconds late fine? | If a few seconds is fine we can use queues and eventual consistency. | A few seconds is fine. It does not need to be instant. | Asynchronous fan-out through a queue. |
| What do posts contain: text only, or photos and video? | Media decides storage and how feeds are served. | Text, links and photos. Video comes later. | Media goes to object storage and a CDN. The feed holds only IDs. |
| How long is the feed? Can a user scroll forever? | Sets the size of the cached list and how pagination works. | Show the latest few hundred, then load older posts on request. | Cache about 800 IDs per user. Older posts are built on demand. |
| What happens when someone deletes a post, unfollows, or blocks? | Feeds are copies, so removals must reach them. | It should disappear quickly, but a short delay is fine. | Filter at read time, and clean the caches lazily. |
| Do we need likes, comments and counts on the post? | Counters are a separate hot-write problem. | Show counts, but they may be slightly stale. | Approximate counters, kept apart from the feed. |
| How available and how fast must the feed be? | The feed is the home page. If it is slow or down the product is down. | 99.99% available and the first page in under 300 ms. | Serve from cache, degrade gracefully, and never block on ranking. |
| Assumption | Value |
|---|---|
| Daily active users | 300 million |
| Posts per user per day | 2 |
| Followers of an average account | 200 (so an average user follows about 200) |
| Feed opens per user per day | 10 |
| Posts on one feed page | 20 |
| Share of followers active in the last 30 days | 50% |
| Feed cached per user | 800 post IDs × 8 bytes = 6.4 KB |
| Registered accounts, of which active are cached | 1 billion, 500 million active |
| Peak compared to average | 3 times |
| Post record without media | about 1 KB |
| Posts with a photo, and photo size | 20%, about 300 KB |
| What | Maths | Result |
|---|---|---|
| Posts per day | 300M × 2 | 600 million |
| Post writes per second (average, peak) | 600M ÷ 86,400 ≈ 6,900, × 3 | about 7,000 and 21,000 per second |
| Feed opens per day, per second | 300M × 10 = 3B; 3B ÷ 86,400 | about 35,000 per second (105,000 at peak) |
| Feed inserts per day if we push to everyone | 600M posts × 200 followers | 120 billion per day |
| Feed inserts per second (all followers) | 120B ÷ 86,400 | about 1.4 million per second (4.2M at peak) |
| Feed inserts per second (active followers only) | 1.4M × 50% | about 700,000 per second (2.1M at peak) |
| One post from a 50M-follower account (active only) | 50M × 50% | 25 million inserts from one post |
| Lookups per feed open if we build the feed at read time | 200 timelines + 20 posts; 35,000 × 220 | 220 lookups, so about 7.7M lookups per second |
| Lookups per feed open with a cached feed | 1 feed list + 20 posts; 35,000 × 21 | 21 lookups, so about 735,000 per second |
| Feed cache size | 500M active users × 6.4 KB | 3.2 TB, about 6.4 TB with overhead, about 64 nodes of 100 GB (128 with replicas) |
| Post storage per year (text), with 3 copies | 600M × 1 KB × 365 × 3 | about 220 TB a year, 660 TB with copies |
| Photo storage per year | 600M × 20% × 300 KB × 365 | about 13 PB a year (object storage and CDN) |
| Follow graph (one direction) | 1B accounts × 200 × 16 bytes | about 3.2 TB (6.4 TB with both directions) |
| Method | Path | Request | Response | Notes |
|---|---|---|---|---|
| POST | /v1/posts | { text, mediaIds[], visibility } | 201 { postId, createdAt } | Idempotency key in a header, so a retry does not create two posts. Media is uploaded first to object storage and referenced by ID. |
| GET | /v1/feed?cursor=&limit=20 | none | 200 { posts: [...], nextCursor } | The cursor is opaque. It encodes the score and the post ID of the last item, not an offset. Auth required. |
| POST | /v1/follows/{userId} | none | 204 | Idempotent: following twice is the same as once. Triggers a small backfill of that account's recent posts into the feed. |
| DELETE | /v1/follows/{userId} | none | 204 | Idempotent. The feed is filtered at read time, so the effect is immediate even if caches still hold the posts. |
| DELETE | /v1/posts/{postId} | none | 204 | Marks the post deleted. Feeds drop it when they hydrate posts. Caches are cleaned in the background. |
| Store | Key and value | Notes |
|---|---|---|
| Posts | post_id → { author_id, text, media_ids, created_at, status } | Sharded by post_id (or author_id). Source of truth. 1 KB per post. Cached by post_id. |
| Follow graph | follower_id → [followee_id, ...] and followee_id → [follower_id, ...] | Two adjacency lists, so we can ask who I follow and who follows me. About 16 bytes per edge. |
| Feed cache | feed:{user_id} → sorted list of (score, post_id), about 800 entries | In Redis, a sorted set per active user. IDs only. Trimmed after each insert. |
| Author timeline | timeline:{author_id} → recent (created_at, post_id) | Each account's own recent posts. Used by pull for celebrities and for the profile page. |
| Post cache | post:{post_id} → post and author summary | Hydration reads. Hot posts stay in memory. |
| Counters | post:{post_id}:likes → count (sharded) | Approximate and eventually consistent, kept apart from the feed. |
ZADD feed:42 1717000000123 "9001" -- score = time (or a ranking score), member = post_id ZREVRANGEBYSCORE feed:42 (cursor_score -inf LIMIT 0 20 -- next page, newest first ZREMRANGEBYRANK feed:42 0 -801 -- keep only the latest 800
| Component | What it does |
|---|---|
| Post service | Validates and saves the post, writes it to the author timeline, and publishes a PostCreated event. It returns before any fan-out happens. |
| Queue | Holds PostCreated events durably. Partitioned by author, so one author's posts stay in order and a spike is absorbed instead of dropped. |
| Fan-out workers | Read the follower list in pages, skip inactive followers, and insert the post ID into each follower's feed list. Skip the whole fan-out for large accounts. |
| Feed cache | One sorted list of post IDs per active user. Rebuildable. Trimmed to about 800 entries. |
| Feed service | On read: fetch the list, merge posts from the large accounts the user follows, filter hidden and deleted posts, rank, hydrate, and return one page. |
| Graph service | Stores follows in both directions. Answers: who does this user follow, who follows this account, and which of those are large accounts. |
| Ranker and feature store | Scores about 200 candidates with a cheap model, using signals such as recency, closeness and engagement. |
| Post cache and object storage with CDN | Posts are read by ID in batches. Photos are served from a CDN, never through the feed service. |
The problem: Every post must show up in many feeds. We can do that work when the post is written, or when the feed is read. Normal accounts have 200 followers and celebrities have 50 million, and one rule must not melt the system for either.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Fan-out on write (push) | When a post is saved, insert its ID into every follower's cached feed. | Reading is one cache lookup. Very fast and predictable for the user. | About 200 times more writes than posts. A celebrity post is 25 million inserts. Wastes work on inactive users. |
| Fan-out on read (pull) | When a feed is opened, read the latest posts of every account the user follows and merge them. | Posting is one write. No wasted work. A new follow or unfollow is instant. | A feed open costs about 220 lookups (7.7M a second in total), and the slowest of them sets the latency. Expensive for the path users feel. |
| Hybrid | Push for normal accounts. For accounts above a follower threshold, skip the push and pull their recent posts at read time. | Writes stay bounded and reads stay cheap. Celebrity storms never reach the write side. | Two code paths. A threshold to tune. A user who follows many large accounts has a slower read. |
| Push only to a hot subset | Push to followers active in the last 30 days, and build the feed on demand for everyone else. | Halves the writes. Great as part of a hybrid. | A returning user has a cold first load. Needs a rebuild path. |
Reads are about 5 times more frequent than posts (35,000 feed opens a second against 7,000 posts), so it is worth paying at write time to keep reads cheap. That is why push is the default. But the cost of a push grows with the number of followers, and the skew is huge, so one rule cannot cover both ends.
Pick a threshold, for example 100,000 followers. Below it we push. Above it we skip the fan-out, and the feed service reads that account's recent posts at read time. A typical user follows only a handful of such accounts, so the extra read work is small (a few more lookups per open). We also skip followers who have not been active for 30 days, because pushing into feeds nobody opens is wasted work.
| Case | Pushed | Inserts for one post | Reads for one feed open |
|---|---|---|---|
| Average account, 200 followers, 50% active | Yes | 100 | 21 (list + 20 posts) |
| Large account, 1M followers, threshold 100k | No (pulled) | 1 | 21 + about 6 big accounts = 27 |
| Celebrity, 50M followers, pushed to active | Would be | 25,000,000 (about 17 s of the whole fleet) | 21 |
| Celebrity, 50M followers, hybrid | No (pulled) | 1 | 24 |
The problem: A feed read must be fast, must return full posts and not just IDs, and must page without showing duplicates even though new posts arrive while the user scrolls.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Cache full posts in every feed | Copy the whole post into each follower's feed. | One read gets everything. | Huge memory (a 1 KB post × 200 copies). Edits and deletes need to fix every copy. |
| Cache IDs, hydrate in a batch | The feed holds post IDs only. On read, fetch the posts by ID with one multi-get from a post cache. | Small and cheap. One copy of each post, so edits and deletes happen once. Cache hit rates are high for popular posts. | A second step on every read. A cache miss goes to the database. |
| Offset pagination | Page 2 is OFFSET 20 LIMIT 20. | Simple. | If three new posts arrive, the item at position 20 moves to 23 and page 2 shows duplicates. Also slow for deep offsets. |
| Cursor pagination | The client sends the (score, id) of the last item it saw. The next page is everything below it. | Stable while new posts arrive. Fast: it is a range read on a sorted set. | No jump to page 50. Needs a unique tiebreaker so equal scores do not skip items. |
IDs are tiny (8 bytes), so 800 of them per user is 6.4 KB, and the whole cache for 500 million active users is about 3.2 TB. Full posts live once, in a post cache keyed by ID, where hot posts are shared by millions of feeds and stay in memory. Edits and deletes then change one record, not 25 million copies.
The cursor is the pair (score, post_id) of the last item. The next page is the items strictly after that pair. New posts get a higher score and appear at the top, so a user who is scrolling down never sees a repeat. Ranked feeds can reorder, so we also keep a short list of IDs the user has already seen and drop them from later pages.
ids = redis.ZREVRANGEBYSCORE(feed:u, max=cursor.score, min=-inf, LIMIT 0 100)
ids += authorTimelines(bigAccountsFollowedBy(u), since=cursor.score) // pull part, a few lookups
ids = ids - seen(u) - hiddenOrBlocked(u) // filter
top = ranker.score(ids.take(200)) // cheap model
page = top.take(20)
posts = postCache.multiGet(page.ids) // 1 batch call, not 20
return { posts: posts.filter(p => p.status == 'ok'), nextCursor: (page.last.score, page.last.id) }The problem: A purely chronological feed is easy but not very good. Ranking needs features and a model, and it runs on every feed open, so it must be cheap, and it must never make the page fail.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Chronological | Sort by post time, newest first. | Simple, predictable, nothing to compute. | Noisy: a heavy poster buries everything else. Lower engagement. |
| Score at write time | Compute a score when the post is inserted into each feed and keep the list sorted by it. | Reads stay cheap. | The score ages (recency changes) and depends on the reader. Hard to change the model. |
| Two stages at read time | Collect candidates (the cached list and pulled posts, about 200), then score only those with a model, using precomputed features. | A good balance. The model can change without rebuilding feeds. Cost is bounded by the number of candidates. | Adds work and a dependency to every read. Needs a fallback. |
| Heavy model on all posts | Score every post from every followed account with a large model. | Best quality. | Far too slow and costly for 35,000 feed opens a second. |
Candidate collection is the cached list plus the pulled posts, which we already have. The ranker scores only about 200 of them, with features that were computed ahead of time and kept in a fast store: how recent the post is, how close the viewer is to the author (messages, likes, profile views), the post type, and how well the post is doing (engagement so far).
Keep it cheap and safe: a hard time limit on the ranker (for example 50 ms), and if it times out, return the chronological order. Add diversity (do not show ten posts in a row from one author), drop posts the user has already seen, and keep a small share of unranked or random posts so we can measure whether the model is actually better, using an A/B test.
| Signal | Example | Where it comes from |
|---|---|---|
| Recency | Newer is better, decays over hours | Post timestamp |
| Affinity (closeness) | How often you like, comment on or message this author | Precomputed in a feature store, updated by a stream |
| Engagement | Likes and comments per view so far | Approximate counters |
| Type | You tend to open photos more than links | Per-user history |
| Negative signals | Hidden, muted, reported | User actions, filtered before scoring |
The problem: Feeds are copies. When a user unfollows, blocks, or a post is deleted or hidden, the copies in millions of lists are now wrong, and users expect removal to be immediate. The graph itself is huge and has hot spots.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Update every copy at once | On delete or unfollow, remove the post or author from every affected feed. | Feeds are always clean. | A delete of a popular post is millions of writes. An unfollow means scanning a list. Slow and expensive. |
| Filter at read time | Leave the copies in place. When a feed is read, check each ID's status and each author against the user's blocks and unfollows, and drop what is not allowed. | Effect is immediate. No fan-out of deletes. Cheap, since we already read the posts. | Stale IDs stay in lists until cleaned. Small cost on every read. |
| Lazy cleanup in the background | A background job removes old, deleted and blocked entries over time, or they age out when the list is trimmed. | Keeps lists tidy at low cost. | Needs a job. Not a guarantee by itself. |
We already fetch the posts to hydrate the page, so checking status and the author against the viewer's block and unfollow list costs almost nothing, and it is correct the moment the change happens. The stale IDs left behind are harmless: they are never shown, and they fall off the end of the list when it is trimmed to 800.
For the graph, store follows in two directions: following(user) and followers(account). Shard both by the user or account ID. A very large follower list is not read as one piece. Fan-out reads it in pages, and the list of big accounts a user follows is a small separate set that the feed service reads on every open (and caches).
| Event | What we do right away | What we do later |
|---|---|---|
| Post deleted | Mark status = deleted. Hydration drops it. | Remove it from caches and author timeline. Trim cleans old IDs. |
| Unfollow | Remove the edge. Read-time filter drops that author at once. | Background job removes that author's IDs from the feed list. |
| Follow | Add the edge. Backfill the account's last 20 posts into the feed. | Future posts arrive by push or pull as usual. |
| Block or mute | Add to the viewer's filter set. Applied at read time. | Same cleanup job as unfollow. |
| Account becomes large | Flip the account to pull-only above the threshold. | Stop pushing. Old pushed entries age out of lists. |
A simplified model with made-up round numbers and no random values: 7k posts a second from ordinary accounts, 35k feed opens a second, fan-out capacity 1.5M inserts a second, cache capacity 5M lookups a second, 1 billion accounts with 6.4 KB feed lists (800 ids × 8 bytes). The “accounts followed above the threshold” counts (12, 6, 3, 1) are only there to show the idea. Round trips assume 20 parallel lookups of about 1 ms. Real systems queue, batch and vary.
| Bottleneck | Fix |
|---|---|
| Fan-out write volume (1.4M inserts a second) | Hybrid for big accounts, skip inactive users, batch and pipeline inserts per Redis node, and scale the workers. Partition the queue by author. |
| Celebrity post storm | Never push above the threshold. Pull their recent posts at read time and cache that small timeline, since many users read the same one. |
| Feed read latency | One list read plus one batch hydration. Keep the pull part to a few accounts. Parallelise calls and set a timeout on each step. |
| Hot posts in the post cache | Replicate hot entries, add a short in-process cache in the feed service, and spread keys across nodes (see Hot Keys). |
| Like and comment counters | Sharded counters: split one counter into N sub-counters and add them up on read, or batch the updates through a stream. |
| Feed cache memory (3.2 TB) | Cache only active users, cap the list at 800 entries, shard by user ID with consistent hashing, and add replicas. |
| Graph reads for big accounts | Read follower lists in pages, keep a cached set of big accounts per user, and shard the graph by ID. |
| Failure | How the design copes |
|---|---|
| Fan-out queue backs up | Users see older posts for a while, not an error. Add workers, watch the lag, and process recent posts and active users first. |
| A feed cache node dies | Replicas take over. Lists that are missing are rebuilt by pull for the first page, then refilled in the background. |
| The whole feed cache is lost | Serve every feed by pull for a while (slower), warm the most active users first, and use rate limits so the database is not flattened. |
| The ranker is slow or down | A 50 ms limit, then fall back to chronological order. The feed still works. |
| A fan-out worker crashes halfway | The queue redelivers the event. Inserts are idempotent (same member, same score), so repeats are safe. |
| A region goes down | Serve from another region. Feeds there may be slightly behind, because fan-out is replicated asynchronously. Posts are replicated by the store. |
A post is saved, published to a queue, and fanned out by workers into a cached list of post IDs per active follower. Large accounts are not pushed: their recent posts are pulled and merged when the feed is read. Reading is one list lookup, a small merge, a cheap two-stage ranker with a chronological fallback, and one batch hydration of posts, paged by a score-and-ID cursor. Deletes, blocks and unfollows are filtered at read time and cleaned lazily. Photos come from object storage and a CDN.
| Decision | What we gain | What it costs |
|---|---|---|
| Hybrid fan-out | Bounded writes, fast reads, and no celebrity storms. | Two code paths and a threshold to tune. Heavier reads for users who follow many big accounts. |
| Feed holds IDs only | Tiny feeds (6.4 KB), one copy of each post, easy deletes and edits. | An extra batch lookup on every read. |
| Skip inactive users | About half of the fan-out writes disappear. | A returning user gets a slower first load while the feed is rebuilt. |
| Asynchronous fan-out | Posting is fast and bursts are absorbed by the queue. | A few seconds of delay, and eventual consistency between feeds. |
| Filter deletes at read time | Removal is immediate without chasing millions of copies. | A small check on every read, and stale IDs until cleanup. |
| Approximate counters | No hot rows, and very high write rates. | Counts are a little stale and may differ between users. |
The part interviewers push hardest. Know the numbers and say them.
A change in requirements is a test of whether you understand why your design looks the way it does.
| New requirement | What changes in the design |
|---|---|
| The feed must be strictly chronological, with no ranking | Drop the ranker and feature store. Scores become timestamps, which makes cursors and merges simpler. Fan-out is unchanged. |
| Users follow up to 5,000 accounts (not 200) | Pull gets much worse, and push gets cheaper per user. Raise the cap on list size, and lean harder on push with a lower threshold for big accounts. |
| Posts must appear in followers' feeds within 1 second | Tighter fan-out SLO: more workers, smaller batches, priority queues for recent posts, and fewer skipped paths. Possibly push to followers who are online right now first. |
| Add stories that disappear after 24 hours | A separate, short-lived feed with a TTL on every entry. Read at the top of the app. Same fan-out idea, smaller lists. |
| Add live video posts | Posts become events with a state (live, ended). Notifications and fan-out are urgent, and the video itself goes through a streaming path, not this system. |
| Groups and pages (many-to-many) as feed sources | More edges per user and large groups behave like large accounts: pull for large groups, push for small ones. |
| Private posts visible to a custom list of friends | Fan-out targets the list, and the visibility check at read time uses the list. Larger risk of leaks, so test it carefully. |
| Strong consistency for the author's own post | Show it locally on the client at once, or merge the author's own timeline into their feed on read. No change to global fan-out. |
| Area | Weak | Good | Great |
|---|---|---|---|
| Requirements | Starts drawing boxes. | Asks scale, ranking and freshness, and states the scope. | Finds the skew (celebrities) and the freshness-versus-cost trade-off before drawing anything. |
| Estimation | Skips it, or only counts posts. | Posts, feed opens and storage. | Computes fan-out inserts (200 times the post rate) and the celebrity post, and uses them to choose the design. |
| Fan-out design | Only push, or only pull. | Explains push and pull and picks one. | Hybrid with a threshold, skips inactive users, and quantifies where each strategy breaks. |
| Deep dives | Stays on the diagram. | Covers caching and pagination. | Cursor pagination, ID-only lists, two-stage ranking with a fallback, and read-time filtering of deletes. |
| Failures and scale | Says add more servers. | Mentions replicas and queues. | Backlog behaviour, cache loss and rebuild, thundering herd, idempotent inserts, and monitoring fan-out lag. |
| Communication | Silent or jumps around. | Follows the seven steps. | States numbers, names costs of each choice, and says what is out of scope and what comes next. |
| Mistake | Do this instead |
|---|---|
| Computing the feed with a big join at read time | Keep a cached list of IDs per user and fill it by fan-out. A join over 200 accounts per open does not scale. |
| Pushing every post to every follower, with no exceptions | Do the celebrity maths out loud (25 million inserts) and add the pull path for big accounts. |
| Using offset pagination | Use a cursor of score and ID so new posts do not cause duplicates, and deep pages stay fast. |
| Storing whole posts in each feed | Store IDs, keep one copy of each post, and hydrate in a batch. |
| Ranking with a heavy model on every post | Collect candidates cheaply, score only the top 200, and have a time limit and a chronological fallback. |
| Trying to delete or edit every copy in every feed | Filter by post status and viewer at read time, and clean up lazily. |
| Forgetting inactive users | Skip fan-out to users inactive for 30 days, and rebuild on return. |
| Never saying what it costs | For each choice say what you gain and what you pay (staleness, two paths, extra read). |
The feed list and the post cache are a read-through, write-ahead cache.
Celebrity timelines, hot posts and counters are all hot-key problems.
Posts and the follow graph are sharded by ID.
The fan-out queue absorbs spikes and retries failures.
Cursor pagination is the right way to page a moving list.
Rebuilding and prefetching feeds for returning users.
Spreading feed lists over cache nodes with little movement.
Protects posting, following and feed reads from abuse.