Sub topic 7
Storing timelines in a bounded cache
This chapter covers how to store precomputed timelines in a cache, how to keep each one at a fixed size, and what to do when the cache is empty, partial, or out of date. It assumes you have read the chapters on fan-out on write and cursor pagination. You should also know basic Redis commands (sorted sets, EXPIRE, pipelines) and be able to read short Python snippets. The examples use the redis-py client against a local Redis server.
Why the timeline lives in a cache
Fan-out on write produces one list per user: the posts that user should see, newest first. That list is read far more often than it is written. Every app open and every scroll reads it. It also has a simple access pattern: append new entries at the top, read a range from the top, and discard entries from the bottom.
A durable database can hold this data, but you don't need durability for it. Every timeline entry can be recomputed from the posts table and the follow graph. This makes the timeline a cache in the strict sense: losing it costs latency, not data. That decision shapes the rest of the design. You can keep timelines in memory, you can drop them under pressure, and you can rebuild them on demand.
What goes into a timeline entry
Store references, not posts. An entry is a post ID plus a sort key, nothing more. The post body, author name, media URLs, and like counts live in a separate post store, and the feed service looks them up in a batch after reading the timeline (this step is called hydration).
| Approach | Memory per entry | Edit and delete handling | Read cost |
|---|---|---|---|
| IDs only, hydrate on read | Small (tens of bytes) | Change the post store once, all feeds see it | One extra batched lookup |
| Full post copied into each timeline | Large (kilobytes) | Must find and rewrite every copy | Single read |
| IDs plus a few denormalized fields | Medium | Fields can go stale | Usually single read |
IDs only is the standard choice. A post with 10 million followers would otherwise be copied 10 million times, and a delete would have to chase every copy. With references, hydration costs one batched MGET (or a call to a post service that has its own cache). Because popular posts are hydrated by many readers at once, that second cache has a high hit rate.
Choosing the data structure
A Redis sorted set fits the access pattern. Each user gets one key, for example feed:42. The member is the post ID and the score is a sort key that increases with time.
ZADDinserts an entry. Adding the same member again only updates its score, so a retried push does not create duplicates.ZREVRANGEBYSCOREreads the newest entries below a cursor. This maps directly to cursor pagination.ZREMRANGEBYRANKtrims the oldest entries by position.ZREMremoves one post, which you need for deletes.
A Redis list (LPUSH plus LTRIM) is cheaper in memory, but it cannot deduplicate, cannot be read by score, and removing one item is a linear scan. Lists work for a feed that is read only from the top. They are awkward once you add cursors and deletes.
The sort key must be unique per post and time-ordered. Redis stores scores as 64-bit floats, which hold integers exactly only up to 2^53. A millisecond timestamp fits, but two posts in the same millisecond collide. Tied scores are ordered by member as a string, so post ID "9" sorts after "10". A common fix is a composite integer such as timestamp_ms * 1000 + sequence, which stays below 2^53 for current dates. The rest of this chapter assumes the score is already unique.
Bounding the size
An unbounded timeline grows with every post from every followed account. A user who follows 500 accounts and never opens the app would accumulate entries forever. Two limits prevent this.
- A length cap. After every insert, trim the set to its newest
FEED_LIMITentries. The tutorial's earlier examples use 800. - A time-to-live (TTL). Each write refreshes an expiry, for example 7 days. Users who stop opening the app lose their timeline, and the memory is reclaimed.
Choose the cap from user behavior, not from what memory allows. If 95% of sessions never scroll past 200 posts, a cap of 800 buys little. Here is a rough sizing, with the assumptions stated:
- Assume about 100 bytes per sorted-set entry in Redis. This covers the member string, the score, and skiplist and hash-table overhead. Measure with
MEMORY USAGEon your own data before trusting it. - At a cap of 800, one timeline takes about 80 KB.
- With 50 million cached users, that is about 4 TB.
- At a cap of 200, the same population takes about 1 TB.
A 4x reduction in the cap is a 4x reduction in memory and in write cost, because each trim and each insert touches a smaller structure.
Writing into the cache
The write path has one trap that causes real bugs. If a follower's timeline has expired and you ZADD into the missing key, Redis creates a new key containing a single post. The next read finds a key that exists, treats it as a valid cache hit, and shows a feed with one item. The fix is to push only into timelines that already exist. Doing that check and the write in separate round trips leaves a race, so use a small Lua script, which Redis runs atomically.
import redis
FEED_LIMIT = 800
FEED_TTL_SECONDS = 7 * 24 * 3600
r = redis.Redis(decode_responses=True)
# Insert only if the timeline exists, then trim and refresh the TTL.
PUSH_SCRIPT = r.register_script("""
if redis.call('EXISTS', KEYS[1]) == 1 then
redis.call('ZADD', KEYS[1], ARGV[1], ARGV[2])
redis.call('ZREMRANGEBYRANK', KEYS[1], 0, -(tonumber(ARGV[3]) + 1))
redis.call('EXPIRE', KEYS[1], ARGV[4])
return 1
end
return 0
""")
def feed_key(user_id):
return f"feed:{user_id}"
def push_to_feeds(follower_ids, post_id, score):
"""Fan-out on write into existing timelines only."""
pipe = r.pipeline(transaction=False)
for user_id in follower_ids:
PUSH_SCRIPT(
keys=[feed_key(user_id)],
args=[score, post_id, FEED_LIMIT, FEED_TTL_SECONDS],
client=pipe,
)
pipe.execute()The trim ZREMRANGEBYRANK key 0 -(LIMIT+1) removes everything except the newest LIMIT entries. If the set has fewer than LIMIT members, the range is empty and nothing is removed.
Batching the pushes in a pipeline matters at scale. A post with 50,000 followers would otherwise cost 50,000 network round trips. In production the fan-out worker also groups followers by Redis shard, so each pipeline goes to one node.
Reading a page
A read is a range query below the cursor. Following the keyset idea from the pagination chapter, the cursor here is the score of the last item the client saw. The ( prefix makes the bound exclusive.
def read_page(user_id, cursor=None, size=20):
"""Return up to `size` (post_id, score) pairs, newest first."""
max_score = "+inf" if cursor is None else f"({cursor}"
rows = r.zrevrangebyscore(
feed_key(user_id), max_score, "-inf",
start=0, num=size, withscores=True,
)
return [(post_id, int(score)) for post_id, score in rows]New posts land at the top with higher scores, so they never shift the pages below the cursor. This is the same stability that keyset pagination gives in SQL, and it is why you should not use ZREVRANGE with an offset.
After reading the IDs, the feed service hydrates them, drops any whose post no longer exists, and returns the page with a next cursor equal to the last score.
Misses, partial timelines and rebuilds
Three situations send a read to something other than the cached timeline.
- The key is missing. The user is new, has been inactive past the TTL, or the cache node lost its data. Rebuild the timeline.
- The cursor is past the bottom of the cache. The user scrolled beyond the cap. The cache cannot answer, so serve older pages from the database with the SQL keyset query from the pagination chapter.
- The key exists but is missing recent entries. This happens after a failed fan-out job or a restored backup. Chapter 10 covers detection and repair.
A rebuild is fan-out on read run once. Query the recent posts from the accounts the user follows, merge them newest first, take the top FEED_LIMIT, and write them back.
def rebuild_feed(user_id, candidates):
"""candidates: list of (post_id, score), newest first, from the database."""
top = candidates[:FEED_LIMIT]
if not top:
return
key = feed_key(user_id)
pipe = r.pipeline() # MULTI/EXEC, so readers never see a half-built feed
pipe.delete(key)
pipe.zadd(key, {post_id: score for post_id, score in top})
pipe.expire(key, FEED_TTL_SECONDS)
pipe.execute()A rebuild has its own race. A post pushed after you queried the database but before the MULTI/EXEC block runs is overwritten by DELETE, and that post is missing until the next rebuild. Two mitigations are common. One is to use ZADD into the existing key and trim, instead of DELETE, so concurrent pushes survive. The other is to take a short per-user lock during the rebuild and have the fan-out worker skip or retry that user.
Rebuild storms and hot keys
A rebuild is much more expensive than a cache hit, since it queries the follow graph and many authors. Two situations can overload the database.
- Cache node failure. If a node holding 5 million timelines dies, those users all miss on their next open. Rebuild requests arrive in a burst. Mitigate with a replica per shard, rate-limited rebuilds, and a degraded response (for example, a shorter feed built from fewer authors) while the cache refills.
- Many concurrent rebuilds of one user. A user who opens the app on two devices triggers two identical rebuilds. A short lock or a request-coalescing layer (one rebuild, many waiters) removes the duplicate work.
Hot keys are less of a problem for timelines than for posts. Each timeline is read by one user, so load is spread across keys. The hot items are the post objects that every follower's hydration requests, and those belong in the post cache with replication or a small local cache on each feed server.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Pushing into a missing key | Users see a feed with one post | Push only if the key exists, as in the Lua script |
| Trimming with `ZREMRANGEBYRANK 0 LIMIT` | Cache keeps the wrong end, or one entry too few | Remove ranks `0` to `-(LIMIT+1)` so the newest `LIMIT` stay |
| Using offset paging on the cache | Duplicates or skips when new posts arrive | Use the score of the last item as the cursor |
| Non-unique scores | Posts silently dropped at page boundaries | Use a unique composite score |
| No TTL | Memory grows with every inactive user | Refresh a TTL on every write |
| Copying full posts into timelines | Edits and deletes do not propagate | Store IDs and hydrate |
Eviction policy
Redis can also evict keys when memory runs out. For a timeline cache, use a policy such as allkeys-lru, which removes the least recently used timelines first. That matches the desired behavior: inactive users lose their timelines before active ones. Do not mix timelines with data that cannot be rebuilt on the same instance, because the eviction policy applies to all keys. Keep the timeline cache on its own cluster.
The explicit TTL still helps. It gives you a predictable bound on staleness and memory even when the eviction policy never triggers.
Exercise
A feed service caches timelines as Redis sorted sets with FEED_LIMIT = 500 and an estimated 100 bytes per entry. There are 40 million cached timelines. (a) Estimate the total memory for the timelines. (b) A fan-out worker uses plain ZADD followed by a trim, with no existence check. A user's timeline expires, then a followed author posts. What does the user see on the next app open, and why? (c) Name one change that fixes it.
Show answer
(a) 500 entries x 100 bytes = 50 KB per timeline. 40 million x 50 KB = 2 TB (2,000,000 MB), before replication. (b) ZADD creates the missing key with one entry. The next read finds the key, treats it as a cache hit, and returns a feed containing only that single post, because the rebuild path is never triggered. (c) Push only if the key exists, for example with a Lua script that checks EXISTS before ZADD. Missing keys then stay missing and trigger a full rebuild on read.
Exercise
A user has scrolled to the bottom of a cached timeline of 800 entries and requests the next page with the cursor equal to the score of the oldest cached entry. Where should the service get the next page, and why is it safe to switch sources in the middle of a scroll?
Show answer
It should run the SQL keyset query on the posts table (author in followed accounts, createdat and postid below the cursor, ordered newest first, limit 20). Switching is safe because both sources order entries by the same unique, time-based sort key and the cursor is a position in that order, not an offset into one source. Posts arriving at the top do not move the cursor.