TweakCode
Worked Systems lessons

News Feed

How News Feed works

Before you start

  • Requirements

    Each worked system starts from a scoped list of verbs and numbers.

    Open lesson
  • Queues

    Slow work leaves the request path through a queue.

    Open lesson

Why it matters

Home must show the newest text posts from followed accounts, in stable pages. A reader may follow 500 accounts, and opening home is far more common than publishing, so work repeated on every open can dominate the system even when each merge is computationally small. The finished feed must make home a range read on one user’s timeline, not rebuild it from hundreds of account histories.

Example

Design a text home timeline

Users post short text. Home shows the latest posts from accounts they follow, newest first, paged.

Input
posts = {"ana": [[9, "a9"], [4, "a4"]], "bo": [[8, "b8"], [7, "b7"]], "cy": [[6, "c6"], [1, "c1"]]}, following = ["ana", "bo", "cy"], limit = 4
Output
["a9", "b8", "b7", "c6"]

Approach 2 · Resolve the bottleneck

The idea

Keep one example in view

Design a text home timeline

posts = {"ana": [[9, "a9"], [4, "a4"]], "bo": [[8, "b8"], [7, "b7"]], "cy": [[6, "c6"], [1, "c1"]]}, following = ["ana", "bo", "cy"], limit = 4→["a9", "b8", "b7", "c6"]

The baseline, Collect and sort everything, is O(P log P) · O(P). The better model below keeps this exact input and removes that bottleneck.

Instead of collecting and sorting every post, merge Ana’s [a9, a4], Bo’s [b8, b7], and Cy’s [c6, c1] only until four items fill home; the result is efficient computation but still one read per followee.

For the concrete pull model, Ana’s posts are a9 then a4, Bo’s are b8 then b7, and Cy’s are c6 then c1. Keep one front from each sorted list and repeatedly take the newest, producing [a9, b8, b7, c6] without loading and sorting every historical post.

This k-way merge touches three account lists here and up to 500 for the drill’s reader. It is always fresh and makes publishing cheap, but each home open performs hundreds of reads. That read amplification is the estimate that rules out pull-only home for ordinary accounts.

Pro

The rest of this is on Pro

The idea above is free. The walkthrough, the cost, and the practice are on Pro.