Design Reddit
medium 50 minA service like Reddit: communities, posts, nested comments and votes.
See it run
Load a feed, vote, post, comment, read a thread and rank. Then a viral post and two failures.
Operations
Load a feed
IDs first, details in batches, personal parts last.
Step 1 of 11
Open
sort
hot
A person opens a community in Hot order. Why: Hot joins votes and time.
Step 1: Open
def feed(user, community, sort, cursor): ids, after = lists.page(community, sort, cursor, 25) posts = cache.get_many(ids) posts |= db.get_many(missing(ids, posts)) counts = cache.counts(ids) mine = votes.get_many(user, ids) page = [card(posts[i], counts[i], mine.get(i, 0)) for i in ids if visible(user, posts[i])] try: page = boost(user, page, timeout=0.03) except Timeout: pass return page, after- Latency
- < 200 ms p99
- Load
- 35,000/s peak
- Posts on a page
- 25
Fetch a few extra IDs, because hidden and deleted posts leave gaps.
In the real world
The same a service like reddit doing real jobs. Pick one and step through it.
Millions read it and 10,000 people vote each second.
Step 1 of 4
Reads
The edge and Redis serve its card. Each service keeps it for a second or two.
Step 1: Reads
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Adding age to hot
criticalOlder posts would rank higher.
Wronglog10(s) + age_seconds / 45000Rightlog10(s) + created_seconds / 45000Reading the old vote outside the update
criticalTwo requests can both see the same old value.
Wrongold = get(user, item)pipeline.incr(item, new - old)Rightold = lock_row(user, item)save(new)A toggle call
majorA repeat undoes the vote.
WrongPOST /toggle-voteRightPUT /votes/t3_abc {"dir": 1}Karma tiers on each event
majorVoting at one rate and undoing at another leaves free points.
Wrongkarma += delta * rate(karma)Rightraw += weighted_deltashown = concave(raw)Posts partitioned by community only
majorOne huge community fills one partition.
Wrongpartition = community_idRightpartition = post_id # lists separate
Interview tips
Find the hot thing
- Rows spread by user.
- The total is shared.
- Batch the total.
Know the formula
- 10 times the votes = 12.5 hours.
- Creation time, not age.
- Wilson for few votes.
Bound the page
- 25 posts.
- 200 comments, ten levels.
- Markers for the rest.
Fail softly
- Skip boosts and awards.
- Freeze counts, keep votes.
- Rebuild busy lists first.