Building feeds ahead
After this: Follow a post through the queue and the workers into every follower's feed, and count the inserts.
On this page · 6 sections · 3 checks
Lesson 1 found 20 feed loads for every post. If reading is the common case, make reading cheap: do the work once, when the post is made, and have each feed ready before anyone asks for it.
Copy the post to every follower
Picture a pile of letters, one for each follower. When Ana writes a post, a copy of it goes on top of each follower's pile. When Ben opens the app, his pile is already sorted, newest on top, and the app shows the top of it.
Spreading one item out to many places is called . Doing it when the post is written is , also called push, because the post is pushed into the feeds.
The ready feeds live in a , a fast store in memory. In this design it is the feed cache: one list of post ids per person.
The path of one post
Copying a post into 200 feeds takes time, and the author should not wait for it. So the copying goes behind a , as in Queues and background work. A takes each job later.
Follow two posts. Ana's followers are Ben, Cy and Dee; Cy's followers are Ana and Ben.
- Ana posts p1. The app saves it in the posts database and puts one fan-out job on the queue. Ana gets her answer now.
- A worker takes the job and adds p1 to the feeds of Ben, Cy and Dee: 3 inserts.
- Cy posts p2. It is saved, and a second job goes on the queue.
- A worker adds p2 to the feeds of Ana and Ben: 2 inserts. Each new post goes at the front.
- Ben opens the app. His feed is ready in the cache: p2, then p1. Reading it is one lookup.
In total: 2 jobs and 5 inserts. Run it and watch the counters.
- Feed: 2 postsPress Run it and step through. Ana posts first, then Cy. For each post, watch the job go on the queue, then the worker add the post to each follower's feed. Keep an eye on the inserts counter, and on what Ben finds when he opens his feed.
Press Run it, then step through and watch the requests move.
What it costs
The rule is one insert per follower, for every post. With the numbers from lesson 1:
- 5 million posts a day × 200 followers = 1 billion feed inserts a day.
- 1,000,000,000 ÷ 86,400 is about 11,574 inserts per second.
- Reading is now cheap: each of the 1,157 loads per second is one lookup.
57.9 posts per second became 11,574 inserts per second: the work moved to posting time. That is the trade.
How much memory does the feed cache need? Say it keeps the 500 newest post ids per person, and an id takes 8 bytes. That is 500 × 8 = 4,000 bytes, 4 KB per person, and 4 KB × 10 million people = 40 GB. Ids are small, so the whole feed cache fits in memory, on one large cache server or split across a few.
The code
The worker's job as a function. followers holds each author's list of followers, and feeds holds each person's feed.
followers = { "Ana": ["Ben", "Cy", "Dee"], "Cy": ["Ana", "Ben"],}feeds = {}
def fan_out(author, post_id): for person in followers[author]: if person not in feeds: feeds[person] = [] feeds[person].insert(0, post_id) # newest first return len(followers[author])
inserts = fan_out("Ana", "p1") + fan_out("Cy", "p2")print(inserts)print(" ".join(feeds["Ben"]))5 p2 p1
import java.util.*;
public class Main { static Map<String, List<String>> followers = Map.of( "Ana", List.of("Ben", "Cy", "Dee"), "Cy", List.of("Ana", "Ben")); static Map<String, List<String>> feeds = new HashMap<>();
static int fanOut(String author, String postId) { for (String person : followers.get(author)) { if (!feeds.containsKey(person)) { feeds.put(person, new ArrayList<>()); } feeds.get(person).add(0, postId); // newest first } return followers.get(author).size(); }
public static void main(String[] args) { int inserts = fanOut("Ana", "p1") + fanOut("Cy", "p2"); System.out.println(inserts); System.out.println(String.join(" ", feeds.get("Ben"))); }}5 p2 p1
- fan_outfanOut goes through the followers of the author, one person at a time.
- If that person has no feed yet, it makes an empty one.
- It puts the post id at the front of the person's feed, at position 0, so the newest is first.
- It returns the number of inserts: one per follower.
Ana's post makes 3 inserts and Cy's makes 2, so the program prints 5. Ben's feed is p2 p1, as in the steps above.
Add a third post, fan_out("Ana", "p3")fanOut("Ana", "p3"), before the prints, and predict Ben's feed first.
Check yourself
With fan-out on write, Dee posts once. Dee has 200 followers. How many feed inserts does the worker make for this one post?
Ben follows Ana and Cy. With fan-out on write, Ana posts p1, then Cy posts p2, then Ana posts p3. What is Ben's feed, newest first?
Complete the line that makes fan_outfanOut visit every follower of the author, so that the program prints 5 and then Ben's feed, p2 p1.
followers = { "Ana": ["Ben", "Cy", "Dee"], "Cy": ["Ana", "Ben"],}feeds = {}
def fan_out(author, post_id): ____ # ← go through each follower of the author if person not in feeds: feeds[person] = [] feeds[person].insert(0, post_id) # newest first return len(followers[author])
inserts = fan_out("Ana", "p1") + fan_out("Cy", "p2")print(inserts)print(" ".join(feeds["Ben"]))import java.util.*;
public class Main { static Map<String, List<String>> followers = Map.of( "Ana", List.of("Ben", "Cy", "Dee"), "Cy", List.of("Ana", "Ben")); static Map<String, List<String>> feeds = new HashMap<>();
static int fanOut(String author, String postId) { ____ // ← go through each follower of the author if (!feeds.containsKey(person)) { feeds.put(person, new ArrayList<>()); } feeds.get(person).add(0, postId); // newest first } return followers.get(author).size(); }
public static void main(String[] args) { int inserts = fanOut("Ana", "p1") + fanOut("Cy", "p2"); System.out.println(inserts); System.out.println(String.join(" ", feeds.get("Ben"))); }}Honesty notes
- Explain fan-out on write: when someone posts, a worker copies the post into the feed of every follower.
- Follow a post through the app, the queue and a worker into the feed cache, and count one insert per follower.
- Work out the cost: 5 million posts a day to 200 followers each is 1 billion inserts a day, about 11,574 per second.
- Say why reading is fast with this design: the feed is ready, so opening it is one lookup in the feed cache.
- Size the feed cache: 500 post ids of 8 bytes each is 4 KB per person, and 4 KB × 10 million people is 40 GB, which fits in memory.