AlgoViz

Design a news feed like Facebook's

hard 50 min

Show each person the best recent posts from everyone they follow, in a fifth of a second.

A small hybrid feed

Read it, run it, change a line and run it again.

Loading editor…

One process, dictionaries instead of Redis, Kafka and a database. The limit is 2 followers so that the big account path is easy to see.

The same in TypeScript
// Fan-out on write, with one copy for big accountsasync function fanOutPost(postId: string, authorId: string, time: number) {  if ((await graph.followerCount(authorId)) > 10_000) {    await bigPosts.publish({ authorId, postId, time }); // feed servers keep it in memory    return;  }  for await (const batch of graph.warmFollowers(authorId, 1000)) {    const pipe = redis.pipeline(); // batches round trips; not a transaction    for (const user of batch) {      pipe.zadd(`feed:${user}`, time, postId);      pipe.zremrangebyrank(`feed:${user}`, 0, -501);    }    await pipe.exec(); // safe to repeat  }}// Feed generationasync function getFeed(viewer: string): Promise<Page> {  const follows = await graph.following(viewer);  const ids = new Set([    ...(await redis.zrevrange(`feed:${viewer}`, 0, 499)),    ...follows.flatMap((a) => bigAccounts.recent(a)), // in memory    ...(await posts.recentIdsBy(viewer)),  ]);  const headers = await posts.headers(lightPass([...ids], viewer, 100));  const visible = headers.filter((p) => maySee(viewer, p, follows));  const order = await ranking.rank(viewer, visible, { timeoutMs: 60 }).catch(() => newestFirst(visible));  return page(await sessions.save(viewer, order), 0, 20);}// A score that can be explainedfunction score(p: Features) {  return p.affinity * 0.4 + p.recency * 0.3 + p.engagement * 0.2 + p.typeBoost * 0.1;}