Sub topic 3
Storing Timelines in a Bounded Cache
This chapter assumes you understand HTTP APIs, relational databases, key-value stores, caches, and message queues. A timeline cache stores references to posts, not complete post objects. The post database remains the source of truth.
Bounded per-user timelines
Store each user's recent post references under a user-specific key. Each entry should contain a timestamp and a post ID. Keep only a fixed number, such as 800 entries. This limits memory use and keeps reads predictable.
from collections import defaultdict
FEED_LIMIT = 800
feeds = defaultdict(list) # user_id -> [(timestamp, post_id)]
def add_to_feed(user_id, timestamp, post_id):
feed = feeds[user_id]
feed.append((timestamp, post_id))
feed.sort(reverse=True)
del feed[FEED_LIMIT:]
add_to_feed("u1", 105, "p5")
add_to_feed("u1", 101, "p1")
print(feeds["u1"])A feed request reads the references, fetches post details in batches, and removes unavailable posts. A cache miss can fall back to fan-out on read or rebuild the cache asynchronously.
Ranking the candidate feed
The cache provides candidates. A ranking stage orders those candidates using signals such as recency, author relationship, and previous engagement. Ranking should happen after candidate retrieval, because scoring every post in the system is too expensive.
| Stage | Responsibility |
|---|---|
| Candidate cache | Find recent possible posts |
| Ranker | Score and order candidates |
| Response service | Fetch details and return a page |
Sharding and scaling the pipeline
Shard, or split, feed data by user ID so different machines handle different users. Partition fan-out work through a queue. Workers can retry failed jobs and process them independently. Very large accounts should bypass ordinary fan-out and be merged during reads.
Freshness, consistency and failure handling
Fan-out is usually eventually consistent: a post may appear shortly after publication. Record a durable event before updating caches. Retries must be idempotent, so processing the same event twice does not create duplicate references. Monitor queue age, cache hit rate, and repair failures.
Handling deletes, unfollows, blocks and privacy
Use tombstones or deletion events to remove post references from caches. At read time, recheck visibility because cached entries can outlive a privacy change. Filter blocked authors and unfollowed accounts before ranking or before returning the response.
Exercise
Why should a feed cache store post IDs instead of complete post objects?
Show answer
IDs keep the cache small and let the post database remain the source of truth when content changes or is deleted.