The Timeline Service: Redis Sorted Sets

The precomputed home timeline is a bounded, ordered list of tweet IDs per user, stored in Redis. Two design choices carry all the weight: store IDs, not tweet bodies, and cap the list at ~800 entries.

The intuition first

Your mailbox isn't infinitely deep, and it doesn't hold the full newspapers — it holds claim tickets. Each ticket says "tweet #T exists; go fetch its contents from the warehouse." The mailbox keeps only the most recent ~800 tickets; older ones fall out the bottom. This keeps every mailbox small, uniform, and cheap to update — and the heavy content lives once in a shared warehouse.

The data structure: a Redis sorted set per user

A sorted set (ZSET) is the perfect fit. Each viewer's home timeline is one sorted set:

key:    home_timeline:{user_id}
member: tweet_id  (Snowflake)
score:  tweet_id  (Snowflake — which is time-ordered, see Section 6)

ZADD home_timeline:42  <T>  <T>      ← fan-out inserts here
ZREVRANGE home_timeline:42 0 N       ← read fetches newest N, already sorted

Why member and score are the same value: Redis sorted sets order entries by their score. Snowflake IDs are time-ordered (bigger = newer), so using the tweet ID as the score gives you chronological ordering for free — no separate timestamp field needed.

What operations look like end-to-end:

# fan-out worker inserts a tweet into viewer 42's timeline:
ZADD home_timeline:42  score=9001  member=9001

# reader fetches newest 20 tweets:
ZREVRANGE home_timeline:42  0  19
→ [9001, 8980, 8800, ...]   ← tweet IDs, newest first, already sorted

# hydration step — batch fetch tweet bodies:
GET tweet:9001  →  { author, text, media, ts, ... }
GET tweet:8980  →  { ... }

The sorted set is a pre-sorted inbox of claim tickets — the heavy content lives once in the tweet store, and the timeline holds pointers to it in the right order.

Why a sorted set and not a list?

  • Ordered by score = ordered by time (because Snowflake IDs are time-sortable). The newest-N read is a single range query.
  • De-duplication for free — a member appears once. Re-delivery of the same tweet ID is idempotent.
  • O(log N) inserts and range reads — cheap at this size.
  • Trivial trimming — ZREMRANGEBYRANK to drop everything beyond the newest ~800.

De-duplication for free, explained: a Redis sorted set is a set — membership is unique, enforced by an internal hash table mapping member → score that sits alongside the skip list. ZADD on a member that's already present doesn't insert a second entry; it just updates that member's score (a no-op here, since we always set score = tweet ID = itself). This matters because fan-out delivery is not guaranteed exactly-once — a retried job, a worker crash-and-resume, or overlapping fan-out paths could all attempt to insert the same tweet ID into the same timeline more than once. With a List (RPUSH), each of those attempts would blindly append, producing duplicate tweets in the feed and requiring the application to track "have I already delivered tweet T to user 42?" itself (e.g., an extra SISMEMBER check per insert). The ZSET gets that idempotency as a structural property, no extra lookup required.

O(log N), explained: a Redis sorted set is backed by a skip list (plus that hash table for O(1) member→score lookup). A skip list is a linked list with several "levels" stacked on top of the base list; most nodes only live at the bottom level, but a random subset also link at higher levels, letting a search skip over many nodes at once — similar in spirit to descending a balanced tree. - ZADD (insert): Redis walks down the levels to find where the new score belongs. Each level skips roughly half the remaining nodes, so that's O(log N) hops instead of the O(N) scan a plain sorted array or list would need to find the insertion point. - ZREVRANGE 0 19 (range read): locating the start of the range (highest score) is O(log N); walking forward to collect the next 19 members is O(1) per step since base-level nodes are linked, giving O(log N + M) overall for M results.

At this timeline's scale (capped at ~800 entries via trimming below), log₂(800) ≈ 10 — each insert or read touches on the order of 10 skip-list hops, not hundreds of comparisons. That's what keeps fan-out writes cheap even as they hit millions of follower timelines, and keeps reads fast regardless of total tweet volume.

Choice 1: store tweet IDs, not tweet bodies

Each timeline entry is just a tweet ID (8 bytes), not the tweet text/media/metadata. The full tweet lives once in the tweet store (T-bird) and a separate tweet cache.

Timeline (Redis):           Tweet store / cache:
  home_timeline:42           tweet:T → { author, text, media, ts, ... }
   → [T, T', T'', ...]        tweet:T'→ { ... }
       │  │   │               (each tweet stored ONCE, shared by all timelines)
       └──┴───┴──── hydrate ──►

Why this matters enormously:

If you stored full tweets in every timeline... Storing only IDs...
A 280-char tweet + metadata (~hundreds of bytes to KBs) duplicated into every follower's list 8-byte ID duplicated instead
100K-follower tweet = 100K × (KBs) of duplicated storage 100K × 8 bytes
Edits/deletes must be propagated to every copy Edit/delete the one canonical tweet; timelines just hold a pointer
Memory blows up; Redis is RAM-bound Timelines stay tiny → fit in RAM cheaply

The read does an extra hydration step (fetch tweet bodies for the ~N IDs you're about to show from the tweet cache), but that's a bounded batch fetch of only the tweets actually on screen — cheap and cacheable. Storing IDs trades a tiny read-time hydration for a massive reduction in storage amplification and a clean single-source-of-truth for tweet content. (This is also what makes deletes sane: you don't hunt down millions of copies.)

Choice 2: bound the timeline at ~800 tweet IDs

Each home timeline is capped (historically ~800 entries). Beyond the cap, oldest IDs are evicted.

Why cap it, and why ~800 specifically:

  • Nobody scrolls 800 tweets. A reader consumes the top tens of tweets per session. Keeping thousands per user buys nothing for the common case.
  • Bounded memory per user = bounded, predictable cluster size. 200M users × 800 IDs × 8 bytes is a knowable RAM budget; "unbounded history per user" is not.
  • Fan-out writes stay cheap — inserting into a small, capped set is cheap and trimming is O(small). Each insert is O(log N) where N=800, so ≈10 operations. After every insert, a ZREMRANGEBYRANK evicts the oldest entry (K=1 removed, so also O(log N)). The cap makes this cost a permanent constant — a user's timeline never grows, so write cost never degrades over time.
  • It's a cache, not the source of truth. The timeline service is a materialized cache of recent timeline; the durable truth is the tweet store + social graph. If a timeline is lost or a user scrolls past the cap, you can reconstruct older timeline by falling back to read-time computation (pull from the authors). So the cap is safe: you're not deleting data, just bounding the cache.
home_timeline:42   (capped at ~800)
 ┌───────────────────────────────────────────────┐
 │ newest ──────────────────────────────► oldest  │
 │  T₈₀₀  ...  T₃  T₂  T₁                          │
 └───────────────────────────────────────────────┘
        ▲                          │
   new tweets pushed in        oldest evicted when
   at the top (ZADD)           size > 800 (ZREMRANGEBYRANK)
        │
   scroll past 800? ──► fall back to read-time computation (pull from authors)

The read-time fallback, explained: "pull from the authors" is a scatter-gather + k-way merge, not a sequential fetch-and-cache loop. When a user scrolls past the cached 800, the read path fires parallel requests to every account they follow (their profile timeline / the tweet store), asking each for "tweets older than the ID I've already shown." Because every author's own tweets are already time-sorted by Snowflake ID, merging N sorted streams into one is a classic k-way merge: repeatedly take the highest ID across all the streams' current fronts. The result is handed to the user directly. Critically, this does not grow or evict anything in home_timeline:42 — it's recomputed fresh on each request precisely because it's the expensive path with no cache backing it; writing it into the capped ZSET would just push out the 800 you're already serving fast. At most it might sit behind a short-lived, per-request cache to survive a page refresh, but it isn't a structure that fetches-one-then-evicts-the-oldest the way the push-side ZSET is.

Why it's a cache you can afford to lose

The timeline service is rebuildable:

  • The durable facts are: every tweet (tweet store) and every follow edge (graph).
  • A home timeline is a function of those: "the recent tweets of everyone I follow."
  • So if a Redis timeline shard dies, you don't lose user data — you lose a cache that can be recomputed by the pull path.

This is why Twitter could run timelines on Redis (in-memory, not the most durable thing) without risking permanent data loss: the in-memory timeline is derived state, and the derivation inputs are stored durably elsewhere. Replication (multiple copies of each timeline shard) handles availability; recomputation handles the worst case. Durability lives in T-bird and the graph, not in the timeline cache.

How the cache actually gets repopulated after a crash — three layers, cheapest first:

  1. Redis's own persistence (RDB/AOF). A plain process crash-and-restart on one node reloads from its on-disk snapshot/append log. No reconstruction needed at all — this handles the common "the process died" case in seconds, using no other system.
  2. Replica promotion. If the node itself is gone (disk failure, host death) but its replica(s) survived, the replica — which has been asynchronously mirroring writes — is promoted to primary. It's already got (nearly) the full dataset, so this is a failover, not a rebuild; the tiny window of un-replicated writes is the only loss, and that's bounded by normal async-replication lag.
  3. Lazy, per-user pull reconstruction — only when both of the above fail (e.g. an entire shard's primary and replicas are lost together). There is no eager bulk job that recomputes all 200M affected timelines up front — that would itself be a thundering herd against the tweet store and social graph. Instead, reconstruction is lazy and on-demand: the next time an affected user opens the app, the read path finds home_timeline:{user_id} empty, falls back to the same scatter-gather + k-way merge described above (pull from everyone they follow, merge, take top N), serves that result immediately, and ZADDs those IDs back into the (now-recreated) key — repopulating the cache for that one user as a side effect of serving their read. Users who don't come back soon simply never trigger any reconstruction work; the cost is paid only for the users who actually need it, exactly when they need it.

Pros and cons of the IDs-in-bounded-ZSET design

✅ Pros ❌ Cons
Tiny, uniform per-user footprint → predictable RAM budget Extra hydration hop at read time (fetch bodies for shown IDs)
Single source of truth for tweet content → sane edits/deletes Capped history → deep scroll falls back to slower pull path
Sorted set gives order + de-dup + cheap trim for free In-memory cache → needs replication for availability
Cache is rebuildable from durable stores → safe to lose Hot-shard risk if a popular viewer/timeline concentrates load