Skip to lesson

Design a news feed (basic version)

ShopLite wants a Following tab with the newest posts from the shops and students a customer follows. It must open instantly, even when one account has millions of followers. When should each feed be built?

Your turn: the Following tab

10 million users open the app 10 times a day. Most accounts have about 200 followers; one cricket-star account has 5 million. Think first:

  • Would you build each feed when someone posts or when someone opens the app? What does each choice cost?
  • What goes wrong for the account with 5 million followers?
  • A user scrolls while new posts arrive. How do you avoid showing the same post twice?

Write down your answers, then compare them with the design below.

Requirements: post, follow and read a feed by time

Eventual consistency means all copies of the data agree after a short while, not instantly. A new post may take a few seconds to reach every follower's feed, and that delay is acceptable here.

The requirements, then a short program that turns 10 million users into feed reads and post writes per second.

Example 1 · Estimate reads, posts and fan-out writes

FeedEstimateDemo.javaJava
public class FeedEstimateDemo {    public static void main(String[] args) {        long dailyActiveUsers = 10_000_000;        int feedReadsPerUser = 10;        long postsPerDay = 2_000_000;        int avgFollowers = 200;        int secondsPerDay = 86_400;
        long feedReads = dailyActiveUsers * feedReadsPerUser;        long fanoutWrites = postsPerDay * avgFollowers;
        System.out.println("Feed reads per day: " + feedReads);        System.out.println("Feed reads per second: " + feedReads / secondsPerDay);        System.out.println("Posts per second: " + postsPerDay / secondsPerDay);        System.out.println("Feed inserts per day (fan-out on write): " + fanoutWrites);        System.out.println("Feed inserts per second: " + fanoutWrites / secondsPerDay);    }}
Output
Feed reads per day: 100000000
Feed reads per second: 1157
Posts per second: 23
Feed inserts per day (fan-out on write): 400000000
Feed inserts per second: 4629

What this code does

  • 1,157 feed reads per second against 23 posts per second: reads are about 50 times more frequent.
  • With 200 followers on average, fan-out on write turns 23 posts per second into about 4,600 feed inserts per second, which a Redis cluster handles comfortably.

Functional requirements: a user can create a post, follow and unfollow others, and read a feed of posts from the people they follow, newest first, one page at a time.

Non-functional requirements: the feed loads in about 200 ms and keeps working when some parts fail. The numbers decide the design: 10 million daily users reading 10 times a day make about 1,157 feed reads per second, but only 23 new posts per second. Reads win by far.

Fan-out on write vs fan-out on read

Fan-out on write (push) copies each new post's id into every follower's feed list when it is posted, so reading a feed is one quick lookup. The cost moves to writing: 200 followers means 200 inserts per post.

Push and pull compared with numbers: the writes or lookups each choice costs for a normal account and for a celebrity.

Fan-out on write: when a post is made, its id is copied into the feed list of each follower, so reading is one lookup. Fan-out on read: the post is stored once, and each time a follower opens the app the server fetches the latest posts of everyone followed and merges them.

Example 2 · Cost of each strategy and the celebrity threshold

FanoutCostDemo.javaJava
record Author(String name, long followers) {}
public class FanoutCostDemo {    static final long CELEBRITY_THRESHOLD = 100_000;
    static String strategy(Author a) {        return a.followers() >= CELEBRITY_THRESHOLD ? "fan-out on read" : "fan-out on write";    }
    public static void main(String[] args) {        Author[] authors = {            new Author("hostel-friend", 180),            new Author("college-fest-page", 25_000),            new Author("cricket-star", 5_000_000)        };        int followeesPerReader = 300;
        System.out.println("On write: one post costs one insert per follower.");        for (Author a : authors) {            System.out.printf("  %-18s %10d inserts per post -> %s%n", a.name(), a.followers(), strategy(a));        }        System.out.println("On read: one feed read looks at every followee.");        System.out.printf("  reader following %d accounts -> %d lookups per feed read%n",                followeesPerReader, followeesPerReader);    }}
Output
On write: one post costs one insert per follower.
  hostel-friend             180 inserts per post -> fan-out on write
  college-fest-page       25000 inserts per post -> fan-out on write
  cricket-star          5000000 inserts per post -> fan-out on read
On read: one feed read looks at every followee.
  reader following 300 accounts -> 300 lookups per feed read

What this code does

  • On write, cost grows with the author's followers: 180 inserts for a hostel friend, 5 million for a cricket star.
  • On read, cost grows with how many accounts the reader follows: 300 lookups for every feed open.
  • strategy applies the hybrid rule: authors with 100,000 or more followers are pulled at read time instead of pushed.

Fan-out on read (pull) stores each post once. When you open the app, the server fetches recent posts from everyone you follow and merges them. Writing is cheap, but every feed read does hundreds of lookups.

The celebrity problem breaks pure push: a cricket star with 5 million followers would cause 5 million inserts per post. The usual answer is a hybrid: push for normal users, pull for accounts above a follower threshold, and merge the two at read time.

Predict the output

Count the work

Work out how much each strategy costs.

Round 1 of 3

Push: an author with 200 followers posts 3 times today. How many feed inserts?

int followers = 200;
int postsToday = 3;
int inserts = followers * postsToday;
System.out.println(inserts);

Feed cache per user and pagination with cursors

Cursor is a marker for the last item a user has seen, such as 110_4 (time 110, post 4). The next request asks for items older than the cursor, so new posts on top cannot shift the page.

Offset and cursor paging on the same feed while a new post arrives.

Example 3 · Offset vs cursor when a new post arrives

CursorPageDemo.javaJava
import java.util.ArrayList;import java.util.Comparator;import java.util.List;
record FeedItem(long time, long postId) {}
record Page(List<FeedItem> items, String nextCursor) {}
public class CursorPageDemo {    // newest first; ties on time are broken by the larger postId first    static final Comparator<FeedItem> NEWEST_FIRST =            Comparator.comparingLong(FeedItem::time).thenComparingLong(FeedItem::postId).reversed();
    static Page page(List<FeedItem> feed, String cursor, int size) {        List<FeedItem> items = new ArrayList<>();        for (FeedItem item : feed) {            if (cursor != null) {                String[] parts = cursor.split("_");                FeedItem last = new FeedItem(Long.parseLong(parts[0]), Long.parseLong(parts[1]));                if (NEWEST_FIRST.compare(item, last) <= 0) {                    continue; // not older than the last item already shown                }            }            items.add(item);            if (items.size() == size) {                break;            }        }        FeedItem tail = items.get(items.size() - 1);        return new Page(items, tail.time() + "_" + tail.postId());    }
    static List<FeedItem> sorted(List<FeedItem> feed) {        List<FeedItem> copy = new ArrayList<>(feed);        copy.sort(NEWEST_FIRST);        return copy;    }
    public static void main(String[] args) {        List<FeedItem> feed = new ArrayList<>(List.of(                new FeedItem(100, 1), new FeedItem(105, 2), new FeedItem(105, 3),                new FeedItem(110, 4), new FeedItem(120, 5), new FeedItem(130, 6)));
        Page first = page(sorted(feed), null, 3);        System.out.println("Page 1: " + ids(first) + " next=" + first.nextCursor());
        feed.add(new FeedItem(140, 7)); // a new post arrives while the user reads page 1
        List<FeedItem> now = sorted(feed);        System.out.println("Offset page 2: " + idsOf(now.subList(3, 6)) + "  (post 4 shown twice)");        Page second = page(now, first.nextCursor(), 3);        System.out.println("Cursor page 2: " + ids(second) + " next=" + second.nextCursor());    }
    static List<Long> ids(Page p) {        return idsOf(p.items());    }
    static List<Long> idsOf(List<FeedItem> items) {        return items.stream().map(FeedItem::postId).toList();    }}
Output
Page 1: [6, 5, 4] next=110_4
Offset page 2: [4, 3, 2]  (post 4 shown twice)
Cursor page 2: [3, 2, 1] next=100_1

What this code does

  • Page 1 shows posts 6, 5 and 4 and returns the cursor 110_4 (time and id of post 4).
  • Post 7 arrives. "Skip 3" now lands one place earlier and shows post 4 again.
  • The cursor asks for items older than (110, 4), so page 2 is 3, 2, 1 with no repeat. Posts 2 and 3 share time 105; the id breaks the tie.

Each user's feed is a list of post ids in a cache such as Redis, under a key like feed:u42. Keep only the newest few hundred ids: nobody scrolls back weeks, and older pages can be built by fan-out on read if someone does.

Offset pagination ("skip 3, take 3") breaks on a feed: when a new post arrives between two requests, everything shifts down one place and the user sees a post twice. A cursor points at a real item, so new posts on top do not move it. The post id is added to the time so that two posts in the same second still have a clear order.

Single-file simulation: fan-out on write into per-user feeds

Follow graph is the record of who follows whom, usually kept as a map from each author to that author's followers. Fan-out uses it to find where a new post must be copied.

Fan-out on write into capped lists: each follower's feed keeps only the newest 3 post ids.

Example 4 · Fan-out on write into capped feed lists

FanoutOnWriteDemo.javaJava
import java.util.ArrayDeque;import java.util.Deque;import java.util.HashMap;import java.util.LinkedHashSet;import java.util.Map;import java.util.Set;import java.util.TreeMap;
record Post(long id, String author, String text, long time) {}
class FeedService {    static final int FEED_SIZE = 3; // a real feed cache keeps a few hundred ids    private final Map<String, Set<String>> followers = new HashMap<>();    private final Map<Long, Post> posts = new HashMap<>();    private final Map<String, Deque<Long>> feeds = new TreeMap<>();    private long nextId = 1;    int inserts = 0;
    void follow(String follower, String author) {        followers.computeIfAbsent(author, a -> new LinkedHashSet<>()).add(follower);        feeds.computeIfAbsent(follower, f -> new ArrayDeque<>());    }
    void post(String author, String text, long time) {        Post p = new Post(nextId++, author, text, time);        posts.put(p.id(), p);        for (String f : followers.getOrDefault(author, Set.of())) {            Deque<Long> feed = feeds.computeIfAbsent(f, k -> new ArrayDeque<>());            feed.addFirst(p.id());            // newest at the front            inserts++;            if (feed.size() > FEED_SIZE) {                feed.removeLast();            // drop the oldest id            }        }    }
    void printFeeds() {        feeds.forEach((user, ids) -> {            StringBuilder sb = new StringBuilder(user + ": ");            for (long id : ids) {                Post p = posts.get(id);                sb.append("[").append(p.author()).append(": ").append(p.text()).append("] ");            }            System.out.println(sb.toString().trim());        });    }}
public class FanoutOnWriteDemo {    public static void main(String[] args) {        FeedService service = new FeedService();        service.follow("aman", "riya");        service.follow("aman", "fest-club");        service.follow("meera", "fest-club");        service.follow("meera", "aman");
        service.post("fest-club", "Fest passes open", 100);        service.post("riya", "Lab done", 105);        service.post("aman", "Who has DBMS notes?", 110);        service.post("fest-club", "DJ night 9 pm", 120);        service.post("riya", "Library open till 9 pm", 130);
        service.printFeeds();        System.out.println("Feed inserts: " + service.inserts);    }}
Output
aman: [riya: Library open till 9 pm] [fest-club: DJ night 9 pm] [riya: Lab done]
meera: [fest-club: DJ night 9 pm] [aman: Who has DBMS notes?] [fest-club: Fest passes open]
Feed inserts: 7

What this code does

  • post stores the post once and calls addFirst on each follower's deque, so the newest id is at the front.
  • removeLast keeps each feed at 3 ids; aman's oldest post ("Fest passes open") was dropped.
  • Reading a feed is just walking the deque and looking up posts by id, which is why push makes reads cheap.

Each post is stored once, and its id is pushed to the front of every follower's feed list, an ArrayDeque capped at 3 ids.

Printing the feeds shows each user only posts from people they follow, newest first, and the oldest ids dropped. The insert count shows the price of push: 5 posts became 7 feed inserts.

Order of execution

What happens to one new post

Put the push steps in order.

Storage choices, and ranking as a later extension

Hybrid fan-out pushes the posts of normal accounts into followers' feeds and leaves posts of very large accounts out, so readers pull those at read time and merge them with their precomputed feed.

The storage plan as a diagram, then the hybrid read: the precomputed feed plus the celebrities' own posts, merged and paged.

Text
[Client] --> [LB] --> [Feed service x N][Feed service] --read feed ids--> [(Redis: feed:<userId> list, 500 ids)][Feed service] --get posts by id--> [(Posts DB, sharded by authorId)] + [(Post cache)][Post service] ..new post event..> [[fan-out queue]] ..> [Fan-out workers] --> [(Redis feeds)]Media (photos) --> [(Object storage)] --> [CDN]

Example 5 · Hybrid read: precomputed feed plus celebrity posts

HybridFeedDemo.javaJava
import java.util.ArrayList;import java.util.Comparator;import java.util.List;import java.util.Map;import java.util.Set;
record Item(long time, String author, String text) {}
public class HybridFeedDemo {    // Built by fan-out on write for normal authors (newest first).    static final List<Item> precomputed = List.of(            new Item(130, "riya", "Library open till 9 pm"),            new Item(110, "aman", "Who has DBMS notes?"),            new Item(100, "fest-club", "Fest passes open"));
    // Celebrity posts are NOT pushed to followers; they are read from the author's own list.    static final Map<String, List<Item>> celebrityPosts = Map.of(            "cricket-star", List.of(new Item(125, "cricket-star", "Century today"),                                    new Item(90, "cricket-star", "Training at 6 am")));
    static List<Item> readFeed(Set<String> celebritiesFollowed, int size) {        List<Item> merged = new ArrayList<>(precomputed);        for (String celeb : celebritiesFollowed) {            merged.addAll(celebrityPosts.getOrDefault(celeb, List.of()));        }        merged.sort(Comparator.comparingLong(Item::time).reversed());        return merged.subList(0, Math.min(size, merged.size()));    }
    public static void main(String[] args) {        for (Item i : readFeed(Set.of("cricket-star"), 4)) {            System.out.println(i.time() + "  " + i.author() + ": " + i.text());        }    }}
Output
130  riya: Library open till 9 pm
125  cricket-star: Century today
110  aman: Who has DBMS notes?
100  fest-club: Fest passes open

What this code does

  • precomputed is what fan-out on write built; the cricket star's posts were never pushed to anyone.
  • readFeed adds the posts of followed celebrities, sorts everything by time and keeps one page.
  • The star's post at 125 lands in the right place between 130 and 110, at the cost of one extra lookup per celebrity followed.

Posts live in a database sharded (split across servers) by author id, so one author's posts sit together. The follow graph is a simple table of (follower, followee) pairs with indexes both ways. Feed lists live in Redis, and photos go to object storage behind a CDN. Fan-out runs in background workers fed by a queue, so posting stays fast.

The hybrid read merges the precomputed feed with the celebrities' own recent posts, sorts by time and returns one page. Ranking is a later step: instead of time alone, sort by a score that mixes recency, likes and how often you interact with the author. Interviewers expect you to mention it as an extension, not to design it fully in a basic round.

Next step

Check your understanding

12 quick questions