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.
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
| Quantity | Math | Result |
|---|---|---|
| Daily active users | 100 million | |
| Page views | 100M × 20 / 86,400 | about 23,000/s (peak 70,000/s) |
| Votes | 200M a day / 86,400 | about 2,300/s (peak 10,000/s) |
| New comments | 10M a day | about 115/s |
| New posts | 1M a day | about 12/s |
| Storage per day | posts 1 GB + comments 5 GB + vote rows 6 GB | about 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=programmingSending 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
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.
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 − downsorder = log10(max(|score|, 1)): the first 10 votes count as much as the next 90, and as the next 900.secondssince 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.
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.
log10 of the score instead of the raw score?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:
- The user's vote (who voted what) is written synchronously to
votes, sharded byuser_id. Different users never contend. - 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.
Order what happens when Sam upvotes a post.
- Tap the steps below in the right order.
Deep dive 3: storing nested comments
Comments form a tree. Here is a small thread:
Top-level comments have the post as their parent. Each comment stores its parent and its path: the chain of positions from the root.
| Approach | Store | Read a thread | Insert | Move a subtree |
|---|---|---|---|---|
| Adjacency list | parent_id | Recursive CTE or one query per level | Trivial | Change one row |
| Materialized path | path like 0001.0003 | One range scan, already in display order | Need parent's path | Rewrite 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.
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.
1, 2, ..., 10. What goes wrong when you ORDER BY path?Search
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_idso 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
postsandcommentsbypost_id,votesbyuser_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 problem to the technique.
- 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.