News feed
Choose between fan-out on write and read and handle celebrity accounts.
By Invicly Tech, , in System Design Deep Dive. About 11 minutes to read.
In short
A news feed shows each user recent posts from people they follow. The central choice is fan-out on write (precompute feeds) versus fan-out on read (merge at request time), and most real systems use a hybrid for celebrities.
Explained simply
A news feed is the scrolling list you see when you open a social app: recent posts from the people and pages you follow. It looks simple, but a big network has hundreds of millions of users opening the app many times a day. Each feed must load in well under a second.
There are two basic ways to build a feed. You can do the work when someone posts: copy the new post into the feed of every follower (fan-out on write, also called push). Or you can do the work when someone reads: collect the latest posts from everyone they follow and merge them (fan-out on read, also called pull).
Push makes reading fast but makes posting expensive. If a pop star with 100 million followers posts, push means 100 million writes. Pull makes posting cheap but makes every read slow. Real systems mix both: push for normal accounts, pull for very popular ones.
After you collect the candidate posts, you still need to decide the order. A simple feed sorts by time. Most modern feeds rank posts with a score, for example how likely you are to like or comment. Ranking is a separate step that runs on a few hundred candidates, not on everything.
Press Play on a diagram to walk through it one step at a time.
- Insert post into followers' feeds
- Very fast feed reads
- Costly for millions of followers
- Wasted on inactive users
- Fetch followees' posts at read time
- Cheap writes
- Slow reads, heavy merging
- Fits celebrity accounts
- Push for normal users
- Pull for celebrities
- Merge both at read
- Used by large networks
- Author to Post svc: POST /posts1POST /posts
- 2Save post to DBPost svc to Post svc: Save post to DB
- Post svc to Fan-out workers: Enqueue fan-out job3Enqueue fan-out job
- Post svc to Author: 201 Created4201 Created
- 5Load follower IDs, skip if celebrityFan-out workers to Fan-out workers: Load follower IDs, skip if celebrity
- Fan-out workers to Feed cache: Prepend post ID to followers' feeds6Prepend post ID to followers' feeds
- 1GET /v1/feed
Feed service gets user ID and cursor
- 2Read pushed IDs
Range read on feed:{userId} after the cursor
- 3Pull hot accounts
Recent posts of followed celebrities
- 4Merge and filter
Sort by time, drop deleted or blocked
- 5Rank
Score candidates, keep the top 20
- 6Hydrate and return
Multi-get posts, return page and nextCursor
In depth
Requirements and the numbers that drive the design
Start by asking what the feed must do. Typical answers: show posts from followed accounts, newest or ranked first, with text, images and video; support likes and comments; load the first page in under 200 ms at p99. Ask whether the feed must be perfectly fresh. Usually a delay of a few seconds is fine, which allows eventual consistency (data that becomes correct after a short delay).
Then estimate. Say 300 million daily active users, each opening the feed 10 times a day. That is 3 billion feed reads a day, about 35,000 per second on average and around 100,000 at peak. If each user posts once a day and has 200 followers on average, push fan-out creates 300 million times 200, or 60 billion feed inserts a day, about 700,000 per second. That write number is why the fan-out choice matters so much.
- Reads outnumber posts by about 10 to 1 here
- Average follower counts hide a long tail of huge accounts
- Fresh within seconds is usually acceptable
APIs and the data model
Keep the public API small. POST /v1/posts creates a post and returns its ID. GET /v1/feed?cursor=X&limit=20 returns one page plus a nextCursor. Use cursor pagination (the cursor is the last post ID or timestamp you showed) instead of page numbers, because new posts arrive at the top all the time and page numbers would shift and show duplicates.
Store three kinds of data separately. Posts live in a sharded database keyed by post ID. The follow graph stores edges in both directions: who I follow, for building my pull feed, and who follows me, for push fan-out. Feeds live in a cache such as Redis as a list of post IDs per user, trimmed to a few hundred entries. Post IDs that sort by time (for example Snowflake-style IDs with a timestamp in the high bits) let you sort and paginate without reading the post itself.
- 1Feed cache
feed:{userId} holds the latest post IDs
- 2Post cache
Hot posts by ID, used to fill in the page
- 3Social graph store
Follower and following lists, sharded by user
- 4Post database
Source of truth, sharded by post ID
- 5Media in object storage
Images and video served through a CDN
The hybrid fan-out in detail
With a hybrid, the system marks some accounts as hot, for example anyone with more than about 10,000 to 100,000 followers (the exact threshold is a tuning knob). When a normal user posts, a fan-out worker reads their follower list in batches and prepends the post ID to each follower's feed list. When a hot account posts, nothing is pushed; the post just sits in that account's own recent-posts list.
At read time the feed service takes your precomputed list, then fetches recent posts from the hot accounts you follow, merges the lists by time, removes duplicates and hands the candidates to ranking. A further saving: skip push for users who have not opened the app in weeks. Build their feed by pull when they come back, since pushing to inactive users wastes most of the writes.
- Hot threshold is tuned, not fixed
- Skip push for inactive followers
- Merge pushed and pulled lists, then deduplicate
Ranking, caching and keeping feeds correct
Ranking usually runs in stages. Candidate generation gathers a few hundred to a few thousand post IDs. A light model scores them quickly, then a heavier model reorders the top part using signals like how often you interact with the author, post age, and engagement so far. The result for the first page can be cached briefly per user.
Precomputed feeds go stale when something changes. If a post is deleted or its privacy changes, you cannot cheaply remove it from millions of lists. The common fix is to filter at read time: when hydrating post IDs into full posts, drop any that are deleted, hidden or from someone you have since blocked or unfollowed. Hydration (turning IDs into full posts) uses a multi-get against the post cache, so one page needs only a few round trips.
Learn it in 6 short steps
About 40m each. Track them with a timer in your plan.
- 1Clarify requirements and estimate scale~40m
- 2Design the post and feed APIs~40m
- 3Model posts, follows and feeds~40m
- 4Compare fan-out on write and read~40m
- 5Handle celebrity accounts with a hybrid~40m
- 6Cache and rank the feed~40m
Key points
- Feed caches store post IDs, not full posts, to save memory.
- Fan-out runs asynchronously through a queue.
- Celebrity posts are pulled at read time and merged in.
- Paginate feeds with a cursor based on post ID or time.
- Ranking can be applied after candidate posts are gathered.
Key terms
Tap a card to flip it. 0/5 known
Examples
POST /v1/posts { text, mediaIds } -> postId
GET /v1/feed?cursor=... -> posts[], nextCursor
posts(post_id, author_id, text, created_at)
follows(follower_id, followee_id)
feed cache: feed:{userId} -> list of last 500 post IDs
Read: ids = feed:{me} + recent posts of followed celebs
merge by time, hydrate posts from cache, rankAPIs, data model and hybrid read path.
Estimating the cost of pure push
An interviewer asks: why not just push everything? Step 1: take 300 million users posting once a day with 200 followers on average, which is 60 billion inserts a day. Step 2: now add the tail. One account with 100 million followers posting 10 times a day adds 1 billion inserts by itself, all in short bursts. Step 3: store only 8-byte post IDs, capped at 500 per user: 300 million times 500 times 8 bytes is about 1.2 TB of cache, which is fine. Conclusion: memory is affordable, but the write bursts from hot accounts are not, so pull those.
push writes/day = 300M users * 1 post * 200 followers = 60B
≈ 700K inserts/s average
one celebrity = 100M followers * 10 posts = 1B inserts/day
feed cache = 300M * 500 IDs * 8 B ≈ 1.2 TB (plus overhead)A fan-out worker with Redis
When a normal user posts, the post service saves the post and puts a job on a queue. A worker picks it up, pages through the follower list, and for each follower adds the post ID to the front of their list and trims it to 500 entries. Using a pipeline sends many commands in one round trip. If the worker crashes halfway, the job is retried, so the insert should be safe to repeat; a sorted set keyed by post ID gives that for free because adding the same member twice changes nothing.
import redis
r = redis.Redis()
def fan_out(post_id: int, ts: float, follower_ids: list[int]) -> None:
pipe = r.pipeline(transaction=False)
for uid in follower_ids:
key = f"feed:{uid}"
pipe.zadd(key, {post_id: ts}) # same post twice is a no-op
pipe.zremrangebyrank(key, 0, -501) # keep the newest 500
pipe.execute()Quick reference
- Push for normal users, pull for hot accounts, merge at read time
- Store post IDs in feeds; hydrate full posts from a post cache
- Use cursor pagination, never page numbers, for feeds
- Time-sortable IDs (Snowflake style) let you sort and page by ID
- Filter deleted, private or blocked posts at read time
- Skip push for long-inactive users; build their feed on return
- Run fan-out asynchronously through a queue with retries
- Cap each feed list (for example 500 IDs) to bound memory
Common mistakes
- Pushing a celebrity's post into 100 million feeds synchronously.
- Storing full post bodies in every follower's feed.
- Ignoring deletes and privacy changes in precomputed feeds.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write the two main API endpoints for a feed, including request and response fields.
- Exercise 2medium
Estimate the push fan-out rate for 100 million DAU who post twice a day with 150 followers on average. Is it feasible?
- Exercise 3hard
Describe the read path when a user follows 300 normal accounts and 5 celebrities, and say how you keep p99 under 200 ms.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Does Twitter or Instagram use push or pull?
- Public talks from these companies describe hybrids: precomputed timelines for most users, with posts from very large accounts merged in at read time. The exact details change over time and are not fully public.
- How is a ranked feed different from a chronological one?
- A chronological feed sorts candidates by time. A ranked feed scores the same candidates with a model that predicts how much you will care, then sorts by that score.
- Where should I start in a news feed interview?
- Clarify features and scale, then sketch the post and feed APIs, the data stores, and the fan-out choice. The celebrity problem is the deep dive most interviewers expect.