AlgoViz

Design Reddit

medium 50 min

A 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

Our systemClientCDN edgeGatewayFeed serviceRedislists, countsPosts DBBoost serviceoptional

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

Our systemClientCDN edgeGatewayFeed serviceRedislists, countsPosts DBBoost serviceoptional

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

    critical

    Older posts would rank higher.

    Wrong
    log10(s) + age_seconds / 45000
    Right
    log10(s) + created_seconds / 45000
  • Reading the old vote outside the update

    critical

    Two requests can both see the same old value.

    Wrong
    old = get(user, item)pipeline.incr(item, new - old)
    Right
    old = lock_row(user, item)save(new)
  • A toggle call

    major

    A repeat undoes the vote.

    Wrong
    POST /toggle-vote
    Right
    PUT /votes/t3_abc {"dir": 1}
  • Karma tiers on each event

    major

    Voting at one rate and undoing at another leaves free points.

    Wrong
    karma += delta * rate(karma)
    Right
    raw += weighted_deltashown = concave(raw)
  • Posts partitioned by community only

    major

    One huge community fills one partition.

    Wrong
    partition = community_id
    Right
    partition = 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.