Designing a news feed: fan-out on write vs fan-out on read
Push every post into follower inboxes, or build the feed when someone opens the app? I built both in Go with Postgres and Redis, measured them, and ended with the hybrid most feeds use to handle accounts with huge follower counts.
A news feed looks simple. Show me the latest posts from the people I follow, newest first. The trouble is that one post can belong in thousands of feeds, and one feed pulls from hundreds of authors. You have to pay for that combining somewhere, either when someone posts or when someone reads.
This is an intermediate post. You should be fine with Go, SQL and a little Redis. I built both approaches and the hybrid in Go 1.27.3 against Postgres 18.7 and Redis 8.10 in two throwaway containers, and I'll show the numbers I got. It follows the same format as the other design posts, like the URL shortener: requirements, estimates, a diagram, then the deep dive.
💻 The full code for this tutorial is on GitHub: FenixAra/tutorials/System-Design/designing-a-news-feed-fan-out-on-write-vs-fan-out-on-read. Clone it and run each step yourself.
Requirements
Functional, kept small on purpose:
- A user can post a short text.
- A user can follow and unfollow others.
- A user opens the app and sees the newest 20 posts from the people they follow, then can page back.
Non-functional: opening the feed must be fast, a few tens of milliseconds at most on the server. A new post can take a few seconds to show up in followers' feeds. Nobody notices five seconds. And some accounts have millions of followers while most have a few hundred.
See, that last line is the whole problem. We'll come back to it.
Estimates
Let us assume 10 million daily users, each opening the feed 10 times a day, and 1 million posts a day. If you haven't done these estimates before, system design basics walks through the method.
- Feed reads: 100 million a day, about 1,200 per second on average and maybe 5,000 at peak.
- Posts: 1 million a day, about 12 per second.
- Average 200 followers per author. So pushing every post to every follower is 200 million inbox writes a day, about 2,300 per second.
Reads beat posts by 100 to 1. That ratio is why feeds usually do the work at write time.
Two ways to build it
fan-out on read (pull)
open feed -> get my followees -> latest posts of each -> merge -> top 20
fan-out on write (push)
new post -> get author's followers -> add post id to each follower's inbox
open feed -> read top 20 ids from my inbox -> load the posts
hybrid
normal authors: push
authors with huge follower counts: pull at read time, merge with the inbox
Postgres holds users, follows and posts. Redis holds the inboxes, one sorted set per user, scored by post id. The schema is small.
CREATE TABLE users (
id bigint PRIMARY KEY,
name text NOT NULL,
follower_count int NOT NULL DEFAULT 0
);
CREATE TABLE follows (
follower_id bigint NOT NULL REFERENCES users (id),
followee_id bigint NOT NULL REFERENCES users (id),
PRIMARY KEY (follower_id, followee_id)
);
CREATE INDEX follows_followee ON follows (followee_id, follower_id);
CREATE TABLE posts (
id bigserial PRIMARY KEY,
author_id bigint NOT NULL REFERENCES users (id),
body text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX posts_author_id ON posts (author_id, id DESC);
The primary key on follows answers "who do I follow". The second index answers "who follows this author", which is the fan-out query. I order by id rather than created_at because a single Postgres sequence only goes up, and ids make cheap cursors for paging. With many writers across shards you'd want a time ordered id like a Snowflake id instead.
Fan-out on read
The pull version is one query. Get my followees, join their posts, newest first.
func (f *Feed) ReadPull(ctx context.Context, user int64, limit int) ([]int64, error) {
return f.ids(ctx, `
SELECT p.id FROM follows fo
JOIN posts p ON p.author_id = fo.followee_id
WHERE fo.follower_id = $1
ORDER BY p.id DESC LIMIT $2`, user, limit)
}
Posting is free. Reading does all the work. It is fine while a user follows a few dozen accounts and the posts table fits in memory. Now what happens is, it gets worse with every account followed, and every feed open hits the main database.
Fan-out on write
Here the post goes into each follower's inbox when it's created. I send the writes to Redis in pipelines of 500, and trim each inbox to the newest 800 ids so memory stays bounded.
func (f *Feed) fanOut(ctx context.Context, author, postID int64) (int, error) {
rows, err := f.DB.Query(ctx, `SELECT follower_id FROM follows WHERE followee_id = $1`, author)
if err != nil {
return 0, err
}
defer rows.Close()
pipe := f.RDB.Pipeline()
n := 0
for rows.Next() {
var follower int64
if err := rows.Scan(&follower); err != nil {
return 0, err
}
key := inboxKey(follower)
pipe.ZAdd(ctx, key, redis.Z{Score: float64(postID), Member: postID})
pipe.ZRemRangeByRank(ctx, key, 0, -FeedCap-1) // keep the newest FeedCap
n++
if n%500 == 0 {
if _, err := pipe.Exec(ctx); err != nil {
return n, err
}
}
}
if err := rows.Err(); err != nil {
return n, err
}
_, err = pipe.Exec(ctx)
return n, err
}
Reading is now a ZREVRANGE on one key. In a real system the fan-out runs on queue worker, not inside the request, so posting returns at once. The notification system post covers that worker side, and since ZADD of the same id twice is a no-op, retries are safe.
The celebrity problem
Now give one account 20 million followers. Every post from them is 20 million inbox writes, at the same moment, and most of those inboxes belong to people who won't open the app today. That's the celebrity problem. So the hybrid skips the fan-out for authors over a threshold, and readers pull those authors' posts at read time.
func (f *Feed) ReadHybrid(ctx context.Context, user int64, limit int) ([]int64, error) {
members, err := f.RDB.ZRevRange(ctx, inboxKey(user), 0, int64(limit-1)).Result()
if err != nil {
return nil, err
}
ids := make([]int64, 0, len(members)+limit)
for _, m := range members {
id, _ := strconv.ParseInt(m, 10, 64)
ids = append(ids, id)
}
celeb, err := f.ids(ctx, `
SELECT p.id FROM follows fo
JOIN users u ON u.id = fo.followee_id AND u.follower_count >= $3
JOIN LATERAL (
SELECT id FROM posts WHERE author_id = u.id ORDER BY id DESC LIMIT $2
) p ON true
WHERE fo.follower_id = $1`, user, limit, f.Celeb)
if err != nil {
return nil, err
}
ids = append(ids, celeb...)
slices.SortFunc(ids, func(a, b int64) int { return cmp.Compare(b, a) }) // newest first
ids = slices.Compact(ids)
if len(ids) > limit {
ids = ids[:limit]
}
return ids, nil
}
The LATERAL join takes at most 20 posts per celebrity, using the (author_id, id DESC) index, so it stays cheap even if a celebrity has posted for years.
Running it
The full code (schema, feed.go and a main.go that seeds and measures) is under 350 lines. The seed makes 20,000 users. User 1 is followed by everyone else, and everyone else follows 50 random people. The celebrity threshold is 10,000 followers.
docker run -d --name feed-pg -e POSTGRES_PASSWORD=dev -p 127.0.0.1:45917:5432 postgres:18-alpine
docker run -d --name feed-redis -p 127.0.0.1:46917:6379 redis:8-alpine
go mod init example.com/newsfeed
go get github.com/redis/go-redis/v9@v9.23.0 github.com/jackc/pgx/v5@v5.13.0
DATABASE_URL=postgres://postgres:dev@127.0.0.1:45917/postgres \
REDIS_ADDR=127.0.0.1:46917 go run .
This is what I got on my Mac.
normal author: 54 inbox writes
celebrity: 0 inbox writes (pulled at read time)
forced celebrity fan-out: 19999 inbox writes in 57ms
2000 posts: 99303 inbox writes in 8.605s
checked 300 feeds, mismatches=0
avg read: pull 398µs, hybrid 1.622ms
user 7 inbox: 8 ids, 76 bytes
The main check is mismatches=0. For 300 random users the hybrid feed was exactly the same list as the pure pull feed, which is the ground truth. I'd keep that comparison as a test in any real version of this.
Two numbers surprised me. Fanning out the celebrity post anyway took only 57 ms for 20,000 inboxes, because pipelined Redis on localhost is very fast. Scale that to 20 million followers and a network hop, and it's minutes of work per post. Not milliseconds.
And pull was faster than hybrid here, 0.4 ms against 1.6 ms. I didn't expect that at first. But the whole dataset sits in Postgres memory, nobody follows more than 51 accounts, and the hybrid makes two round trips instead of one. A laptop with 20,000 users basically doesn't show the cost of pull. What it hides is that every one of those 5,000 peak reads a second would land on the primary database, and the query gets slower for users who follow thousands of accounts. Push moves that load to Redis, which is easy to add more of.
Follows and the empty feed
One thing push gets wrong by default. If I follow someone now, my inbox has none of their old posts, so the feed looks empty until they post again. The fix is to backfill on follow.
recent, err := f.ids(ctx, `SELECT id FROM posts WHERE author_id = $1 ORDER BY id DESC LIMIT 50`, followee)
if err != nil || len(recent) == 0 {
return err
}
zs := make([]redis.Z, len(recent))
for i, id := range recent {
zs[i] = redis.Z{Score: float64(id), Member: id}
}
return f.RDB.ZAdd(ctx, inboxKey(follower), zs...).Err()
Unfollow is the reverse, and it's fine to be lazy about it: filter out authors you no longer follow at read time and let the old ids age out of the 800 cap.
Trade-offs
- Inbox memory. 800 ids per user times 10 million users is real money in Redis. Only keep inboxes for users active in the last few weeks, and rebuild an inbox with the pull query when an inactive user comes back.
- Redis is a cache here. Lose it and you rebuild from Postgres with the pull query, slowly. That's why the source of truth stays in the database only.
- The threshold. An account that crosses it mid life has old posts in inboxes and new ones pulled. The merge handles that, since
Compactafter the sort drops any id that shows up from both sides. - Ranking. Real feeds aren't newest first. Ranking usually means taking a few hundred candidates from exactly this machinery and scoring them, so the design still holds.
- When the posts table itself gets too big for one machine, see sharding and partitioning. Shard posts by author, since every query here is "posts by these authors".
Clean up the containers when you are done.
docker rm -f feed-pg feed-redis
If you only build one thing from this post, build the mismatch check. It's the only way I trust a hybrid feed.