Sub topic 2
Pushing Posts into Follower Timelines
Assume you know HTTP APIs, relational databases, key-value stores, caching, and message queues. A feed timeline is an ordered list of post references shown to one user.
Fan-out on write
Fan-out on write means copying a new post reference into each follower's timeline when the author publishes. The timeline stores (timestamp, post_id), not the full post. A feed read then needs one lookup.
from collections import defaultdict
FEED_LIMIT = 800
followers = defaultdict(set)
feeds = defaultdict(list)
def publish(author_id, post_id, timestamp):
for follower_id in followers[author_id]:
feed = feeds[follower_id]
feed.append((timestamp, post_id))
feed.sort(reverse=True)
del feed[FEED_LIMIT:]
followers["alice"] = {"bob", "carol"}
publish("alice", "post-7", 100)
print(feeds["bob"])The write cost is proportional to the author's follower count. Reads are fast and predictable, but a very popular author can create a large write burst. Use a queue and workers so publishing does not wait for every timeline update. Workers should retry safely, because duplicate delivery can occur.
Hybrid fan-out for huge accounts
Pushing to millions of followers is inefficient. A hybrid design sets a follower threshold. Normal accounts use fan-out on write. High-follower accounts remain out of follower caches, and their recent posts are fetched during a read.
This trades read work for lower write amplification. Choose the threshold using follower distribution, write capacity, feed latency, and freshness requirements.
Cursor pagination
Use keyset, or cursor, pagination instead of OFFSET. A cursor contains the last returned (created_at, post_id) pair. The unique post ID breaks timestamp ties.
SELECT post_id, author_id, created_at
FROM posts
WHERE author_id IN (:followed_author_ids)
AND (created_at, post_id) < (:cursor_time, :cursor_post_id)
ORDER BY created_at DESC, post_id DESC
LIMIT 20;New posts can arrive between requests without shifting already-seen rows. Validate cursors and keep the ordering columns indexed.
Exercise
Why should a high-follower account usually use fan-out on read?
Show answer
Writing one reference per follower creates an expensive burst, while reading its recent posts adds bounded work for each requesting user.