Sub topic 7
Storing Timelines in a Bounded Cache
This chapter assumes you know what fan-out on write is, how a key-value store like Redis works, and how to read short Python snippets. Here you will see how the precomputed timelines are stored and why their size has to be capped.
What the cache holds
With fan-out on write, each user has a timeline: an ordered list of the posts they should see. A timeline entry does not hold the post. It holds a reference, the pair (timestamp, post_id).
Storing references has three benefits:
- Entries are small, around 16 bytes each, so millions of timelines fit in memory.
- A post edit or delete changes one record in the post store, not millions of copies.
- The read path hydrates the references. It fetches the post bodies in one batch from a post cache or database.
Bounding the timeline
Most users read only the first few pages of a feed. Keeping a user's full history in memory is wasteful. So each timeline is capped at a fixed length, for example 800 entries. When a new entry arrives and the list is full, the oldest entry is dropped.
The memory cost is easy to estimate:
- 500 million users with a timeline each
- 800 entries per timeline
- 16 bytes per entry
That is 500,000,000 × 800 × 16 bytes, about 6.4 TB. This is before replication and structure overhead. You can reduce it by caching timelines only for recently active users, as described below.
Data structure choices
Redis offers two common structures for a timeline.
| Structure | Insert | Trim | Cursor reads | Notes |
|---|---|---|---|---|
| List | `LPUSH` at the head | `LTRIM` | Index based, which shifts when new items arrive | Simple, but poor for cursors |
| Sorted set | `ZADD` with timestamp as score | `ZREMRANGEBYRANK` | `ZREVRANGEBYSCORE` from the cursor | Handles late or out-of-order inserts |
A sorted set suits cursor pagination. The cursor is a score, not a position, so reads stay stable when new posts arrive. Because the set is keyed by member, adding the same post twice has no effect. That makes retries after a failure safe.
Here is a sorted-set version of the write path, using the redis Python client:
import redis
FEED_LIMIT = 800
r = redis.Redis()
def push_to_feed(follower_id, post_id, timestamp):
key = f"feed:{follower_id}"
pipe = r.pipeline()
pipe.zadd(key, {post_id: timestamp})
# Keep only the newest FEED_LIMIT entries (highest scores).
pipe.zremrangebyrank(key, 0, -(FEED_LIMIT + 1))
pipe.execute()zremrangebyrank(key, 0, -801) removes everything from the lowest rank up to the 801st-newest entry. That leaves the newest 800. The pipeline sends both commands in one round trip.
The in-memory Python version from the plan does the same job with a list. It re-sorts on every insert, which costs O(n log n) per follower. A sorted set inserts in O(log n).
Cache lifecycle
Active users only
Most accounts are dormant. Pushing posts into their timelines wastes memory and write throughput. Two common policies address this:
- Write only to timelines of users who were active in the last N days.
- Give each timeline a time-to-live (TTL) that is refreshed on each read. Idle timelines expire.
Either policy creates a cold start. When a returning user opens the app, their timeline is missing. The system rebuilds it with the fan-out on read query: fetch the accounts they follow, take each one's recent posts, and merge them. Then it stores the result so the next read is fast.
Rebuild safety
A rebuild runs concurrently with live fan-out. Do not overwrite the key with the rebuilt list, or you may lose entries pushed during the rebuild. Instead, use ZADD to merge the rebuilt entries into whatever exists, then trim. Because members are post IDs, duplicates collapse.
Common errors
- Storing full post bodies in timelines. Memory grows by a factor of 50 or more, and deleted or edited posts stay stale in every copy.
- Positional cursors on a list. A new push shifts every index, so users see duplicates or skip posts.
- Trim as a separate, unretried step. If the trim fails, timelines grow without bound. Run it in the same pipeline or script as the insert.
- No rebuild path. A cache node failure then leaves users with empty feeds.
- Hydration without handling missing posts. A referenced post may have been deleted. Skip it and optionally remove the entry.
Exercise
A timeline holds 1,000 entries at 16 bytes each. You have 100 million cached timelines. Roughly how much memory do the entries need, and name one way to reduce it without lowering the cap.
Show answer
100,000,000 × 1,000 × 16 bytes = 1.6 TB. You can reduce it by caching timelines only for recently active users, or by expiring idle timelines with a TTL. Both leave the cap unchanged.
Exercise
Why does a sorted set with timestamp scores work better than a list for cursor pagination when new posts keep arriving?
Show answer
The cursor is a score value, so a read asks for entries below that score. New pushes have higher scores and do not change which entries come next. In a list, the cursor is an index, and each new push shifts every index.