Full answer
text
follows(follower_id, followee_id, created_at, PRIMARY KEY (follower_id, followee_id))
posts(id, author_id, body, created_at) -- index (author_id, created_at DESC)
feed_items(user_id, post_id, created_at, PRIMARY KEY (user_id, created_at, post_id))Pull (fan-out on read):
text
SELECT p.* FROM follows f JOIN posts p ON p.author_id = f.followee_id
WHERE f.follower_id = :me AND p.created_at < :cursor
ORDER BY p.created_at DESC LIMIT 50;Fine for hundreds of followees; slow when a user follows thousands.
Push (fan-out on write): on each post, insert a feed row per follower, so reading is one index range on feed_items. A celebrity with ten million followers creates ten million rows per post.
Hybrid: push for normal authors, pull for very popular ones, merged at read time. A reverse index follows(followee_id, follower_id) serves 'who follows me'. Feed rows can be trimmed to the latest few hundred per user.
Key points
- follows as a two-column key
- Pull joins at read time
- Push writes per follower
- Celebrities break pure push
- Hybrid models are common
Common mistakes
- Pure push with no special case for huge accounts
- OFFSET paging through feeds
Follow-ups
- How would you remove posts from feeds when someone unfollows?
- How would you rank the feed instead of sorting by time?
Tips
- Compare read and write costs of both models