← Back to SQL, page 20

sql-0391 · Hard senior

Design the tables behind a social feed where users follow each other and see recent posts from people they follow.

Store follows(follower_id, followee_id) and posts(id, author_id, created_at). A pull model builds the feed at read time by joining follows to recent posts; a push model writes each new post into a feed_items table for every follower. Pull is simple and suits modest scale; push makes reads fast but is costly for authors with millions of followers, so large systems mix the two.

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