Skip to content

Lesson 26 of 38Case studies

Design Reddit

Design a Reddit-style forum with hot ranking, vote counting at scale, nested comment trees, and cached front pages.

20 min read0/5 questions

Reddit looks like a simple forum: communities, posts, votes, comments. Underneath are three classic problems: ranking that mixes popularity with freshness, counting hundreds of millions of votes without melting a database, and storing comment threads that nest ten levels deep. Each one shows up on its own in interviews, so this case study pays off three times.

Requirements

Functional

  • Users join subreddits (communities) and create posts (text, link, or image).
  • Users upvote or downvote posts and comments, once each, and can change their vote.
  • Subreddit pages and the front page list posts by hot, new, and top.
  • Posts have nested comments, shown as a tree.
  • Search posts by keyword.

Non-functional

  • Listing pages load in under 200 ms; most visitors are logged out and see the same page.
  • Vote counts can be a few seconds stale (eventual consistency is fine), but a user's own vote must show immediately and never count twice.
  • Very read-heavy: about 100 views for every vote and 1,000 for every post.

Out of scope: moderation tools, chat, awards, recommendations, ads.

Back-of-the-envelope numbers

QuantityMathResult
Daily active users100 million
Page views100M × 20 / 86,400about 23,000/s (peak 70,000/s)
Votes200M a day / 86,400about 2,300/s (peak 10,000/s)
New comments10M a dayabout 115/s
New posts1M a dayabout 12/s
Storage per dayposts 1 GB + comments 5 GB + vote rows 6 GBabout 12 GB/day, 4.4 TB/year

Votes are the busiest write. Page views dwarf everything, so caching listing pages is the biggest lever.

API

GET  /r/{sub}/hot?after={cursor}&limit=25
POST /r/{sub}/posts                 { "title": "...", "body": "...", "url": null }
POST /v1/votes                      { "target": "t3_8812", "dir": 1 }     dir is 1, 0, or -1
GET  /v1/posts/{post_id}/comments?sort=top&depth=5
POST /v1/posts/{post_id}/comments   { "parent_id": "t1_77a", "body": "..." }
GET  /v1/search?q=rust+async&sub=programming

Sending dir: 0 removes a vote, so the same endpoint handles vote, change, and undo. Repeating a request with the same direction changes nothing, which makes votes safe to retry.

Data model

posts    (post_id PK, sub_id, author_id, title, body, url, score, ups, downs, created_at)
           INDEX (sub_id, created_at)                 -- "new"
comments (comment_id PK, post_id, parent_id, path, author_id, body, score, created_at)
           INDEX (post_id, path)                      -- whole thread in tree order
votes    (user_id, target_id, dir, PRIMARY KEY (user_id, target_id))

The votes primary key is the double-vote guard: one row per user per target. Changing a vote updates the row; the counter changes by the difference (an up to down switch is −2).

High-level design

Reddit architecture
Vote pipelineBrowserBrowserCDN: cached pagesCDNcached pagesAPI serversAPI serversHot lists: Redis ZSETsHot listsRedis ZSETsComments: by post_idCommentsby post_idPosts + votes: PostgresPosts + votesPostgresSearch: OpenSearchSearchOpenSearchVote queueVote queueVote worker: batchesVote workerbatchesHTTPSmissZREVRANGEvote deltascore +=ZADD

Logged-out read. Most visitors are anonymous and see the same /r/programming/hot. The CDN serves a copy cached for about 30 seconds. Our servers never see the request.

1/6
Quick check
70% of page views are logged-out users reading the front page. What is the single most effective optimisation?
Need a nudge? A hint rules out a wrong answer.

Deep dive 1: the hot ranking

"Top" is just ORDER BY score. "New" is ORDER BY created_at. Hot must blend both, so a post with 50 votes from ten minutes ago can beat one with 5,000 votes from a day and a half ago. Reddit's original open-source code uses this formula:

  • score = ups − downs
  • order = log10(max(|score|, 1)): the first 10 votes count as much as the next 90, and as the next 900.
  • seconds since a fixed epoch, divided by 45,000 (12.5 hours).
  • hot = sign(score) × order + seconds / 45000

Because time is added, newer posts always get a head start. A post needs 10x the votes to beat a post that is 12.5 hours younger. Hot values never decay; new posts simply arrive with bigger numbers.

Pythonhot.py
from datetime import datetime, timezonefrom math import log10 EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc) def hot(ups: int, downs: int, posted: datetime) -> float: score = ups - downs order = log10(max(abs(score), 1)) sign = 1 if score > 0 else -1 if score < 0 else 0 seconds = (posted - EPOCH).total_seconds() - 1134028003 return round(sign * order + seconds / 45000, 7) now = datetime(2026, 10, 20, 12, 0, tzinfo=timezone.utc)posts = { "fresh, 50 votes": hot(60, 10, now), "36h old, 5,000 votes": hot(5600, 600, datetime(2026, 10, 19, 0, 0, tzinfo=timezone.utc)), "12.5h old, 500 votes": hot(520, 20, datetime(2026, 10, 19, 23, 30, tzinfo=timezone.utc)), "fresh, downvoted": hot(3, 40, now),}for name, value in sorted(posts.items(), key=lambda kv: kv[1], reverse=True): print(f"{value:.4f} {name}")
Output
Press Run (⌘ Enter) to see what happens.

Notice the fresh post with 50 votes and the 12.5-hour-old post with 500 tie exactly: 10x the votes buys exactly 12.5 hours.

Since the hot value only changes when votes arrive, the vote worker recomputes it then, and stores it as the score in a Redis sorted set per subreddit. Reading a hot page is a range read, the same trick as the leaderboard lesson.

Quick check
Why does the hot formula use log10 of the score instead of the raw score?
Need a nudge? A hint rules out a wrong answer.

Deep dive 2: counting votes at scale

The naive design runs UPDATE posts SET score = score + 1 WHERE post_id = ? on every vote. A post at the top of the front page can get thousands of votes a minute, all queuing on one row lock.

The fix splits the vote into two parts:

  1. The user's vote (who voted what) is written synchronously to votes, sharded by user_id. Different users never contend.
  2. The counter is updated asynchronously. Deltas go to a queue; a worker sums them per post every second and applies one update.

Counts are now eventually consistent: a few seconds behind. That is acceptable for a number nobody can verify by eye. For extra speed, the live count can also live in Redis (INCRBY), with the database updated in batches. Reddit also adds a little noise to displayed counts to frustrate vote-manipulation bots.

Put it in order5 steps

Order what happens when Sam upvotes a post.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Deep dive 3: storing nested comments

Comments form a tree. Here is a small thread:

A comment thread
postt3_8812c6path 0001.0001.0001c3path 0001.0001c4path 0001.0002c1path 0001c5path 0002.0001c2path 0002root

Top-level comments have the post as their parent. Each comment stores its parent and its path: the chain of positions from the root.

1/4
ApproachStoreRead a threadInsertMove a subtree
Adjacency listparent_idRecursive CTE or one query per levelTrivialChange one row
Materialized pathpath like 0001.0003One range scan, already in display orderNeed parent's pathRewrite every descendant

Comments are never moved, and threads are read far more than written, so a materialized path (stored alongside parent_id) is a great fit. Load the whole thread by post_id (one shard if you shard by post), sort by path, then build the tree in memory.

TypeScriptthread.ts
type Row = { id: string; path: string; body: string }; const rows: Row[] = [ { id: "c2", path: "0002", body: "Second top-level" }, { id: "c3", path: "0001.0001", body: "Reply to first" }, { id: "c1", path: "0001", body: "First!" }, { id: "c6", path: "0001.0001.0001", body: "Reply to the reply" }, { id: "c5", path: "0002.0001", body: "Reply to second" }, { id: "c4", path: "0001.0002", body: "Another reply to first" },]; rows.sort((a, b) => a.path.localeCompare(b.path)); // depth-first orderfor (const r of rows) { const depth = r.path.split(".").length - 1; console.log(" ".repeat(depth) + `${r.id}: ${r.body}`);}
Output
Press Run (⌘ Enter) to see what happens.

Zero-padding (0001 not 1) matters: as strings, "10" sorts before "9", so unpadded paths would put the tenth reply before the ninth. Real threads sort siblings by score instead of position, which the API does in memory after loading. Huge threads load the top few levels first and fetch "load more replies" lazily.

Quick check
Paths are stored without padding: 1, 2, ..., 10. What goes wrong when you ORDER BY path?
Need a nudge? A hint rules out a wrong answer.

Postgres LIKE '%rust%' cannot use an index and does not rank by relevance. Posts and comments are streamed into a search engine (OpenSearch or Elasticsearch) via change data capture: every insert or edit in Postgres becomes an event that an indexer consumes. Search results lag writes by a few seconds, which is fine.

Bottlenecks, failures, and 10x scale

  • Hot post thundering herd. When a post hits the front page, its comment thread is read by millions. Cache the rendered top of the thread for a few seconds.
  • Vote queue lag. Counts go stale but nothing breaks. Alert on queue depth; add workers (partition the queue by post_id so one worker owns each post's sum).
  • Brigading and bots. Rate-limit votes per account and IP, weight votes from new accounts lower, and detect rings of accounts voting together.
  • 10x: shard posts and comments by post_id, votes by user_id; one Redis hot list per subreddit spreads across a cluster; the CDN absorbs the logged-out growth. Old posts (archived after six months) move to cheaper storage and stop accepting votes.
Match the pairs0/5 matched

Match the problem to the technique.

Choose an item, then its match on the other side.
Key terms
hot ranking
A score that blends popularity and age: log10 of net votes plus seconds / 45000.
eventual consistency
Readers may see slightly stale values for a while, but all copies converge once updates stop.
counter batching
Summing many increments in memory and applying them as one write, to avoid hot-row contention.
adjacency list
Each tree node stores only its parent ID. Simple writes, harder subtree reads.
materialized path
Each node stores the full path from the root (like 0001.0003), so a subtree is one range scan.
change data capture
Streaming every database change as an event so other systems (like search) can stay in sync.