Skip to content

Design a Community Forum (Reddit)

Advanced 76 min read Part 17 of 18

Design Reddit: communities, posts, nested comment trees, voting at scale, hot/top/best ranking, home feeds, moderation, spam defence and hot-thread caching.

The Problem#

Design a community forum like Reddit. Users create and join communities (subreddits) about any topic. Inside a community, users submit posts (a link, text, an image or a video). Other users vote posts up or down and write comments, which can reply to other comments, forming deep nested threads. Each community shows its posts sorted in several ways (Hot, New, Top, Rising, Controversial), and each user gets a home feed mixing posts from the communities they joined. Volunteer moderators run each community, and the platform fights spam and vote manipulation.

Reddit was founded in 2005 by Steve Huffman and Alexis Ohanian. Its 2024 IPO filing reported tens of millions of daily active users and over 100,000 active communities. Reddit open-sourced its original codebase (known as "r2") in 2008 and archived it in 2017, which is why some of its algorithms, like the Hot ranking formula, are publicly known and used in this design. We will name those where they are well documented, and design our own system for everything else.

What makes this problem interesting:

  • Votes are the most frequent write. Many more people vote than post or comment. Every vote changes a counter and can change a post's rank. Counting votes correctly, quickly and resistant to cheating is a core challenge.
  • Ranking depends on time and votes together. "Hot" must surface new, quickly rising posts while letting older posts sink, and the ranking must be cheap to maintain as votes stream in.
  • Comments are trees, not lists. A popular thread can have tens of thousands of comments nested ten levels deep. Storing, sorting and loading them quickly (without fetching all 50,000 for every page view) is a classic data-structure problem.
  • Two kinds of feeds. Community listings (shared by everyone viewing that community) and home feeds (unique per user, merging dozens of communities).
  • Moderation is distributed. Each community has its own rules and volunteer moderators, plus platform-wide policy enforcement and automated spam defences.
  • Hot threads. When a post hits the front page, millions of people open the same thread within an hour. Caching must absorb that while still showing new comments and up-to-date vote counts.

Analogy. Reddit is like a giant building full of clubrooms. Each clubroom (community) has a noticeboard where members pin notes (posts). Members put stickers on notes they like or dislike (votes), and the most liked recent notes move to the top of the board (ranking). People write replies on sticky notes stuck under a note, and replies to replies under those, forming hanging chains (comment trees). Each club elects its own caretakers (moderators) who remove notes that break club rules, while building security (platform admins) throws out vandals. Every visitor also gets a personal summary sheet listing the best new notes from all the clubs they belong to (home feed). When one note becomes famous, a crowd forms in front of it, and the building puts photocopies at the entrance (caching) so everyone can read it without crushing the clubroom.

Background: a few terms used in this design#

  • Community (subreddit): a named forum (r/science) with its own posts, rules, moderators, settings and subscribers.
  • Post (submission, "link" in Reddit's original code): a top-level item in a community: title plus a link, text body, image, video or poll.
  • Comment: a reply to a post or to another comment. Comments form a tree rooted at the post.
  • Vote: an upvote (+1), downvote (−1), or no vote (0) from one user on one post or comment. A user can change or remove their vote.
  • Score: upvotes minus downvotes. Karma: a user's reputation, derived from scores of their posts and comments.
  • Listing: an ordered list of posts for a view (a community sorted by Hot, a user's home feed, a user's own posts).
  • Hot, New, Top, Rising, Controversial, Best: sort orders, explained in Deep Dive 3.
  • Moderator (mod): a volunteer who manages a community: removes content, bans users, sets rules. Admin: a platform employee enforcing site-wide policy.
  • Shadowban: a ban where the user's content becomes invisible to everyone else without the user being told, used against spammers.
  • Fan-out: copying an item to many destinations (on write) or gathering from many sources (on read).

Clarifying Questions#

QuestionAssumption for this design
Which features are in scope?Communities, posts, nested comments, voting, sorted community listings, home feed, moderation, spam defence.
Out of scope?Chat, live video, ads, awards and payments, recommendations for non-members (mentioned only as extensions).
What post types?Text, link and image or video; media is uploaded to object storage and served by a CDN.
Scale?About 70 million daily active users, 100,000+ active communities, a few million posts and tens of millions of comments per day.
Read versus write?Heavily read: most users only read and vote. Votes are the dominant write.
How fresh must vote counts be?Approximately live: a vote should change the visible score within seconds; exact real-time accuracy is not required.
How fresh must rankings be?Hot listings within about a minute; new posts in New within seconds.
Comment depth limit?Unlimited in storage; the UI loads about 10 levels and shows "continue this thread" beyond.
Can users edit and delete?Yes; edits keep the same ID, deletes leave a "[deleted]" placeholder so replies keep their place in the tree.
Anonymous access?Reading yes (most traffic is logged-out); voting, posting and commenting require an account.
Moderation model?Per-community moderators plus platform admins and automated filters.
Latency targets?Listings under 200 ms p99 from the server; thread page under 300 ms for the first screen of comments.

Requirements#

Functional requirements#

  1. Users can create communities, join and leave them; communities have rules, moderators and settings.
  2. Users can submit posts (text, link, media) to a community.
  3. Users can comment on posts and reply to comments, to any depth.
  4. Users can upvote or downvote posts and comments, change or remove their vote, and see scores.
  5. Each community shows posts sorted by Hot, New, Top (by time range), Rising and Controversial.
  6. Each post shows its comment tree, sorted by Best, Top, New, Controversial or Old, loading more on demand.
  7. Each user has a home feed of posts from joined communities; logged-out users see a Popular feed.
  8. Moderators can remove posts and comments, ban users, lock threads and pin posts; users can report content.
  9. The system detects spam and vote manipulation.

Non-functional requirements#

  • High availability for reads. Viewing listings and threads must work even if voting or posting is degraded. Prefer availability over consistency: a score a few seconds stale is fine.
  • Low latency. Listings under 200 ms and thread pages under 300 ms at p99 from the server; votes acknowledged in under 100 ms.
  • Scale. Hundreds of thousands of reads per second at peak, tens of thousands of votes per second.
  • Durability. Posts, comments and votes must never be lost once acknowledged.
  • Correctness where it matters. One vote per user per item, always; a user's own vote and own comments visible to them immediately (read-your-writes).
  • Abuse resistance. Vote counts and rankings must resist bots and coordinated manipulation.

Capacity Estimation#

These are design targets of a plausible size, not Reddit's real internal figures. See Back-of-the-Envelope Estimation.

Users and reads.

  • 70 million daily active users (DAU). Each opens about 30 pages a day (listings, threads, home feed refreshes): 70 million × 30 ≈ 2.1 billion page views per day ≈ 24,000 per second on average.
  • Daily peaks of about 3× give 75,000 page views per second; a viral event can double that: plan for about 150,000 page views per second at peak. Each page makes a few API calls (listing, vote states, user info), so the API tier handles a few hundred thousand requests per second at peak.
  • A large share of traffic is logged out (people arriving from search engines and links). Logged-out pages are identical for everyone and highly cacheable.

Writes.

  • Votes: suppose 30% of DAU vote, about 20 votes each: 70 million × 0.3 × 20 ≈ 420 million votes per day ≈ 5,000 per second average, about 20,000 per second at peak.
  • Comments: about 20 million per day ≈ 230 per second, about 1,000 per second at peak.
  • Posts: about 1.5 million per day ≈ 17 per second, 60 per second at peak.
  • Subscriptions and other writes: small (a few hundred per second).

So votes outnumber comments about 20 to 1 and posts about 300 to 1. Reads outnumber all writes about 5 to 1 by request count, but much more by bytes, and reads concentrate: a few thousand hot threads and the first page of popular communities account for a large share of views.

Storage.

  • Comments: 20 million × about 700 bytes (body plus metadata) ≈ 14 GB per day ≈ 5 TB per year before indexes and replicas.
  • Posts: 1.5 million × about 2 KB ≈ 3 GB per day.
  • Votes: 420 million × about 30 bytes (user ID, item ID, direction, time) ≈ 13 GB per day ≈ 4.6 TB per year raw, two to three times that with indexes. Votes are the largest structured dataset by row count: over 150 billion rows a year.
  • Media: perhaps 300,000 images and videos a day × 0.5–20 MB, in object storage behind a CDN; tens of TB per month, dominated by video.

Hot threads. A front-page post can receive 20,000–50,000 comments. At 700 bytes each, the full tree is 14–35 MB: far too large to send to a browser in one response, so the server must send only the top part of the tree (around 200 comments) and load the rest on demand.

Listings. 100,000 active communities × 6 sort orders (Hot, New, Rising, Controversial, Top by several time ranges) × the first 1,000 post IDs × 16 bytes (ID plus score) ≈ about 10 GB of precomputed listings: easily held in a cache cluster.

QuantityEstimate
Page views~24k/s average, ~150k/s peak
Votes~5k/s average, ~20k/s peak
Comments~230/s average, ~1k/s peak
Posts~17/s average, ~60/s peak
Vote rows~150 billion per year
Text storage~6 TB per year (comments and posts), plus indexes
Precomputed listings~10 GB
Largest thread~50k comments, ~35 MB uncompressed

Core Entities#

  • User (account): ID, username, karma, creation time, flags (suspended, shadowbanned), preferences.
  • Community (subreddit): ID, name, description, rules, type (public, restricted, private), settings (allowed post types, filters), subscriber count, creation time.
  • Subscription (membership): (user, community) pair, with join time.
  • Moderator: (user, community, permissions) triple.
  • Post: ID, community, author, title, kind (text, link, media, poll), body or URL or media reference, creation time, score, upvotes, downvotes, comment count, flags (removed, locked, pinned, NSFW, spoiler).
  • Comment: ID, post, parent (a comment or null for top-level), author, body, creation time, score, depth, flags (removed, deleted, edited).
  • Vote: (user, item, direction, time), one per user per item.
  • Moderation action: (moderator, community, action, target item or user, reason, time): an audit log.
  • Report: (reporter, item, reason, time).
  • Ban: (community or site-wide, user, expiry, reason).

API Design#

A REST-style API serves both the website and mobile apps. Items use typed IDs (Reddit's public API uses "fullnames" such as t3_abc123 for posts and t1_def456 for comments, a type prefix plus a base-36 ID), which makes cursors and mixed lists easy. See API Design Best Practices.

# Listings (cursor pagination by item ID within a precomputed listing)
GET  /v1/r/{community}/{sort}?t=day&after=t3_abc123&limit=25    sort = hot | new | top | rising | controversial
GET  /v1/home?sort=hot&after=...&limit=25                       (logged-in: joined communities; else Popular)
GET  /v1/popular?after=...&limit=25
 
# Posts and comments
POST /v1/posts            { community, title, kind, body | url | mediaId }        → 201 { postId }
GET  /v1/posts/{postId}                                                           → post + first screen of comments
GET  /v1/posts/{postId}/comments?sort=best&limit=200&depth=10
GET  /v1/comments/more?postId=...&ids=t1_x,t1_y,...&sort=best                     → "load more comments"
POST /v1/comments         { postId, parentId | null, body }                       → 201 { commentId }
PATCH  /v1/comments/{id}  { body }        DELETE /v1/comments/{id}
 
# Votes: idempotent, the request states the desired final state
PUT  /v1/items/{itemId}/vote   { dir: 1 | 0 | -1 }                                → 204
 
# Communities, moderation, reports
POST /v1/r/{community}/subscribe        DELETE /v1/r/{community}/subscribe
POST /v1/mod/{community}/remove   { itemId, reason }
POST /v1/mod/{community}/ban      { userId, days, reason }
POST /v1/reports                  { itemId, reason }

Design notes:

  • Votes are a PUT of the desired state, not an increment. "Set my vote on t3_abc to +1" is idempotent: retries and double-clicks have no extra effect, and switching from +1 to −1 is one request. The server computes the counter delta (here −2). See Idempotency and Safe Retries.
  • Cursors are item IDs within a listing (after=t3_abc123): stable enough for listings, which change slowly relative to a user's browsing. Deep Dive 6 discusses the drift problem.
  • The thread endpoint returns a bounded tree: at most limit comments down to depth levels, with placeholder "more" stubs listing the IDs of omitted children. The client calls /comments/more with those IDs.
  • Logged-out responses carry Cache-Control: public, max-age=30 or similar and are served by the CDN; logged-in responses are personalised (your votes, your hidden posts) and are not cached publicly.
  • Writes are rate limited per user and per IP, with stricter limits for new accounts. See Rate Limiting and Throttling.

High-Level Design#

We build the design one requirement at a time, then combine the pieces. The guiding principle: writes go to a durable store and publish an event; everything derived (scores, listings, comment trees, caches, search) is updated asynchronously from those events. That keeps the write path short and lets read paths be precomputed.

1) Communities and posts#

The post service validates a new post (community exists, user is not banned, community allows this post type, rate limits), runs fast inline spam checks, writes the post to the posts database, and publishes a post-created event to an event log (Kafka). Media is uploaded directly to object storage with a presigned URL before the post is submitted; the post stores only a media reference. The community service owns community metadata, rules, moderators and subscriptions.

2) Comments#

The comment service writes comments to a comments store partitioned by post ID, so every comment of a thread is in one partition. Each comment row records its parent ID; the tree is rebuilt or incrementally maintained by a comment tree builder that consumes comment-created events and keeps a compact, sorted tree structure per post in a cache. Thread pages read the cached tree structure, choose the visible comments, then fetch their bodies.

3) Votes#

The vote service is the hot write path. It records the user's vote in a vote store keyed by (user, item), which enforces one vote per user per item and lets us compute the delta from the previous vote. It then publishes a vote-changed event (item, delta in ups and downs). A vote aggregator consumes these events, batches deltas per item over a short window (for example 1 second), and applies them to the item's counters and score. Score changes are published as score-changed events for the listing updaters.

4) Listings and feeds#

A listing updater consumes post-created and score-changed events and maintains precomputed sorted listings per community and sort order (Hot, New, Top by period, Rising, Controversial) as sorted sets in Redis, each capped at about 1,000 entries. The listing service reads a page of IDs from the right sorted set and fetches the post cards. The home feed service builds each user's feed on read by merging the Hot listings of the communities they joined (Deep Dive 7).

5) Moderation and spam#

Inline checks in the write services stop obvious spam (rate limits, banned domains, banned users, community filters). Every write also flows as an event to the safety pipeline: automatic rules per community (an AutoModerator-style rule engine), machine-learned spam and abuse classifiers, and vote-manipulation detection. Results become actions (remove, filter to a mod queue, shadowban, discount votes). Moderators work in a mod queue service; every action is written to a mod log.

6) Serving and caching#

Logged-out page views go through a CDN that caches whole responses for popular listings and threads for tens of seconds. Logged-in requests reach the API tier, which composes responses from caches: listing IDs from Redis, post and comment bodies from a content cache (Memcached or Redis), and the user's own vote states from the vote store or a per-user vote cache. Hot threads get special treatment (Deep Dive 8).

The full high-level design#

Components:

  • API gateway: authentication, per-user and per-IP rate limits, routing.
  • Post and community services: create posts, manage communities, rules, moderators and subscriptions.
  • Comment and thread services: write comments; assemble thread pages from the tree cache and content cache.
  • Vote service: record one vote per user per item and emit deltas.
  • Vote aggregator: batch deltas into counters and scores, emit score changes.
  • Listing updater: keep per-community sorted listings current; tree builder: maintain sorted comment trees.
  • Listing and home feed services: read listings, merge home feeds.
  • Safety pipeline: rule engine, classifiers and manipulation detection feeding the mod queue.
  • Data stores: sharded relational database for posts, users and communities; wide-column store for comments and votes; Redis for listings, counters and trees; caches, search index and object storage.

Key Flows#

Flow 1: a user upvotes a post#

The client sends PUT /v1/items/t3_abc/vote {dir: 1}. The vote service reads the user's previous vote on that item (here none), writes the new vote, and publishes the delta (+1 up). The client updates the arrow and score locally right away (an optimistic update). The aggregator applies the batched delta within about a second, and the listing updater repositions the post in its community's Hot listing if its score crossed a neighbour's.

If the user later switches to a downvote, the vote service sees the previous value (+1) and emits a delta of −1 up and +1 down. Because the request states the final value, duplicate requests compute a zero delta and change nothing.

Flow 2: a reader opens a hot thread#

The thread service checks the CDN (logged-out) or its own caches (logged-in). It reads the post card, then the comment tree structure for the post from the tree cache: parent-to-children lists already sorted by the requested order. It walks the tree to select the first screen (about 200 comments, 10 levels deep), multi-gets those comment bodies from the content cache, and for logged-in users also fetches the user's votes on the visible items to colour the arrows.

Flow 3: a user comments and sees it immediately#

The comment service writes the comment to the comments store and publishes comment-created. The response returns the full new comment, which the client inserts in place under its parent. The tree builder adds it to the cached tree within a second or two. If the same user reloads the page before that, the thread service merges the user's own recent comments (kept in a short-lived per-user cache) into the tree, so the user always sees their own comment: read-your-writes for the author, eventual consistency for everyone else.

Data Model#

Two diagrams keep the data model readable: communities and membership, then posts, comments and votes.

Posts, users and communities fit a relational database well: modest write rates, relationships, unique names, and moderation queries. Shard posts by post ID (with a community-plus-time index for "New") once one primary is not enough.

CREATE TABLE post (
  post_id       BIGINT PRIMARY KEY,           -- time-ordered ID (Snowflake-style)
  community_id  BIGINT NOT NULL,
  author_id     BIGINT NOT NULL,
  kind          SMALLINT NOT NULL,            -- text, link, media, poll
  title         TEXT NOT NULL,
  body          TEXT, url TEXT, media_key TEXT,
  ups           INT NOT NULL DEFAULT 0,
  downs         INT NOT NULL DEFAULT 0,
  comment_count INT NOT NULL DEFAULT 0,
  flags         INT NOT NULL DEFAULT 0,       -- removed, locked, pinned, nsfw, spoiler
  created_at    TIMESTAMPTZ NOT NULL
);
CREATE INDEX post_by_community_new ON post (community_id, created_at DESC);

Comments and votes are the high-volume tables. A wide-column store such as Cassandra (or a sharded relational table with the same keys) fits their access patterns:

-- CQL: all comments of a post in one partition, ordered by time-ordered ID
CREATE TABLE comments_by_post (
  post_id bigint, comment_id bigint, parent_id bigint, author_id bigint,
  depth int, body text, ups int, downs int, flags int,
  PRIMARY KEY ((post_id), comment_id)
);
-- CQL: one row per (user, item); page loads fetch a user's votes for 25-200 items in one partition
CREATE TABLE votes_by_user (
  user_id bigint, item_id bigint, direction tinyint, voted_at timestamp,
  PRIMARY KEY ((user_id), item_id)
);
DataStoreWhy
Users, communities, subscriptions, moderatorsRelational (PostgreSQL), sharded laterRelationships, uniqueness, transactions, modest volume
PostsRelational, sharded by post IDRich queries for moderation and profiles; moderate volume
CommentsWide-column, partition by postOne-partition reads of a thread; high write volume
VotesWide-column, partition by userOne vote per (user, item); fast "my votes on this page" lookup
Counters, listings, comment treesRedisSorted sets and hashes in memory, rebuildable from durable stores
Post and comment bodies (hot)Memcached or RedisMulti-get by ID
SearchElasticsearch or OpenSearchFull-text search over posts and comments
MediaObject storage plus CDNLarge immutable blobs
EventsKafkaDecouples writes from derived views

Choosing among these is discussed in Choosing a Database: A Decision Guide.

Deep Dives#

1. Communities, posts and nested comments: modelling the core data#

Communities. A community is a row with a unique, case-insensitive name (enforce uniqueness with an index on the lower-cased name), a type (public, restricted, where anyone can read but only approved users post, or private), rules, settings and a moderator list. Subscriber counts are counters updated asynchronously; the exact number does not matter to the second. Community metadata is small (100,000 active communities × a few KB) and read constantly, so it is cached everywhere, with invalidation on change.

Subscriptions. The (user, community) relation is many-to-many and asymmetric in size: a user joins tens or hundreds of communities, while a large community has tens of millions of members. Two access patterns: "which communities did user U join" (home feed, sidebar), and "how many members does community C have" (display). Store subscriptions keyed by user (one partition per user lists their communities) and keep a counter per community. We rarely need "list all members of C" in real time, except for notifications, which can use an offline export.

Posts. A post has a kind, and each kind has different fields (text body, URL, media reference, poll options). Options: one table with nullable columns (simple, used above), or a common table plus per-kind detail tables. Link posts also carry a URL fingerprint (normalised URL hash) so the system can show "other discussions of this link" and detect reposts and spam domains.

Time-ordered IDs. Post and comment IDs are 64-bit, roughly time-ordered IDs (a Snowflake-style layout: timestamp, worker, sequence). Sorting by ID approximates sorting by creation time, which makes "New" listings and comment partitions cheap, and lets services generate IDs without a central counter. Shown to users in base 36, they make short URLs. See Unique ID Generation.

A historical note on schema flexibility. In talks and in its open-source code, Reddit described an early storage layer called "Thing" storage: for each type (account, link, comment, subreddit), a narrow table of fixed fields (ID, ups, downs, dates, deleted and spam flags) plus a key-value "data" table holding all other attributes. Adding a feature meant adding a key, not altering a huge table. The trade-off of such entity-attribute-value designs is well known: flexible and migration-free, but harder to query, index and validate, and most of the heavy lifting moves into caches. Modern designs usually prefer typed columns plus a JSON column for rare attributes. See Data Modeling.

Comments as a tree. Each comment points to its parent (another comment, or null for a top-level comment on the post). Depth (distance from the post) is stored to avoid recomputation. Deleting a comment with replies cannot remove it from the tree, or the replies would be orphaned: mark it deleted, blank the body and author, and keep the node. Removing (by a moderator) is similar but visible as "[removed]". Only leaf comments can be physically removed without consequences.

Edits. Edits update the body and set an edited_at time. Keep previous versions in an edit history table if moderation needs them (for example a user editing a comment into spam after it gained votes).

Counters on items. Each post stores ups, downs and comment_count. These are derived data, maintained from vote and comment events; the vote store and comments store are the sources of truth. Keeping derived counters on the row makes reads cheap; the cost is that counters can drift if events are lost, which a periodic reconciliation job fixes by recounting from the source tables.

2. Voting and vote counters#

Voting is the busiest write path (about 20,000 per second at peak) and the one most targeted by cheaters. The requirements pull in different directions: exactly one vote per user per item (strict), fast visible feedback (seconds), and cheap aggregation (no hot rows).

Storing the vote. The vote store holds one row per (user, item): direction +1, 0 or −1. Partitioning by user means:

  • Writing a vote touches one partition.
  • Loading a page with 25 posts or 200 comments asks "how did this user vote on these items?" with one single-partition read.
  • The table is huge (150 billion rows a year) but evenly spread, since even heavy voters cast only thousands of votes a day.

Computing the delta safely. The counter change depends on the previous vote: none → +1 is "+1 up"; +1 → −1 is "−1 up, +1 down"; +1 → +1 is nothing. A race appears if the same user sends two different votes concurrently (two devices, or a double click with different states): both read "none" and both add. Three ways to make it safe:

  1. Conditional write: "set direction = new where direction = old" (a compare-and-set). In Cassandra this is a lightweight transaction (Paxos-based, several round trips, noticeably slower); in a relational database a row lock or UPDATE ... WHERE direction = $old works.
  2. Serialise per user: send all vote commands to a log partitioned by user ID. A single consumer per partition processes one user's votes in order, keeps the user's recent votes in local state, computes the delta, writes the vote store and emits the delta. No locks are needed, because one thread owns each user. This is a good fit for a high-volume, per-key-ordered workload. See Pub/Sub and Event Streaming.
  3. Recompute rather than delta: periodically recount votes per item from the vote store. Too slow for live scores, but ideal as a reconciliation job.

A practical design uses option 2 for the live path and option 3 as nightly or on-demand repair.

Aggregating counters without hot rows. A viral post can get hundreds of votes per second. Updating post.ups in a relational row per vote creates a hot row with lock contention. Instead:

  • The aggregator consumes vote-changed events partitioned by item ID, sums deltas per item in memory for a short window (for example 1 second or 500 events), then applies one increment per item: HINCRBY item:t3_abc ups 37 in Redis, and a periodic write-back to the durable post row (for example every 10–30 seconds per changed item).
  • For extremely hot items, the counter can be sharded: N sub-counters per item, each increment going to a random shard, reads summing them. Batching usually makes this unnecessary.
  • See Pattern: Scaling Writes and Pattern: Dealing with Contention.

Batching trades a second of delay for orders of magnitude fewer writes. That is invisible to users because the voter's own client already shows the change.

Read-your-writes for the voter. After voting, the user reloads the page. The aggregate might lag by a second, but the arrow colour must reflect their vote. The page's "my votes" lookup reads the vote store (or a per-user recent-votes cache updated synchronously), not the aggregate, so the arrow is always right. The displayed score may be one vote behind, which nobody notices.

Vote fuzzing. Reddit has long said publicly that it "fuzzes" displayed vote numbers: the shown score is close to, but not exactly, the true number, and changes slightly between views. The reason is anti-spam: if a bot operator can see exactly whether their votes counted, they can test which accounts are detected. Fuzzing denies them that feedback while the ranking uses true (filtered) counts. In this design, the display layer adds small noise to the score of items with many votes; small scores stay exact so new posts feel responsive.

Which votes count. Not every vote from the vote store feeds the score. Votes from suspended or shadowbanned accounts, very new accounts, or accounts flagged by the manipulation detector (Deep Dive 10) are recorded but weighted at zero (or discounted). The aggregator applies weights by consulting a cached per-user trust score. Votes can be re-weighted retroactively when an account is later found to be part of a ring, by recounting affected items.

Karma. A user's karma is derived from the scores of their posts and comments. Update it asynchronously from score-changed events, with damping (karma does not need second-level freshness) and with the same discounting of fraudulent votes. Karma is a common gate for posting in some communities, so it must not be cheaply farmable.

Archiving old items. Votes on very old posts are rare but keep the vote store growing. Reddit historically archived posts after about six months (no new votes or comments) and later let communities choose. Archiving freezes counters, lets old partitions move to cheaper storage, and removes a spam surface (old high-ranking threads edited to include spam links).

3. Ranking algorithms: Hot, New, Top, Rising, Controversial and Best#

Each sort answers a different question. The engineering trick is to choose formulas whose sort keys are cheap to maintain as votes stream in.

New sorts by creation time (newest first). The time-ordered post ID is the key, so New needs no score at all and changes only when posts are created or removed.

Hot answers "what is popular right now?". The formula in Reddit's open-source code is well known:

from math import log10
 
def hot(ups, downs, created_epoch_seconds):
    s = ups - downs
    order = log10(max(abs(s), 1))
    sign = 1 if s > 0 else -1 if s < 0 else 0
    seconds = created_epoch_seconds - 1134028003   # a fixed epoch in December 2005
    return round(sign * order + seconds / 45000, 7)

How to read it:

  • Votes count logarithmically. Going from 1 to 10 net votes adds as much as going from 10 to 100, or from 100 to 1,000. The first votes matter a lot; a post with 10,000 votes is not ten times "hotter" than one with 1,000.
  • Newness counts linearly. Every 45,000 seconds (12.5 hours) of later submission adds 1 to the key, the same as a tenfold increase in net votes. A post submitted 12.5 hours later needs only one tenth of the votes to rank equally.
  • The key does not depend on the current time. Older posts do not lose score; newer posts are simply born with a higher time term. This is the crucial engineering property: a post's hot key changes only when its votes change, so no background job has to rescore every post every minute. Sorting by the key is always correct.
  • Net-negative posts get a negative vote term, so they fall quickly below everything else.

Compare with the formula commonly attributed to Hacker News, (points − 1) / (age_hours + 2)^1.8: it depends on current age, so every item's score changes continuously and the list must be periodically rescored. That is fine for one front page with a few hundred candidates, but expensive for 100,000 communities. Reddit's form (log votes plus linear creation time) is equivalent to a decay in rank while being static per item, which suits sorted-set maintenance.

A worked example: post A was submitted at 08:00 and has 1,000 net votes; post B was submitted at 20:30 (12.5 hours later) with 100 net votes. Key A = log10(1000) + t_A/45000 = 3 + x. Key B = log10(100) + (t_A + 45,000)/45000 = 2 + x + 1 = 3 + x. They tie. If B reaches 200 votes, B ranks above A.

Top answers "what was best in this period?": sort by net score among posts created in the window (hour, day, week, month, year, all time). Maintain a sorted set per (community, window) for short windows, keyed by net score. Expiry is the problem: a post must leave "Top of today" 24 hours after creation. Options: periodically rebuild short-window sets from the posts table (cheap: a day's posts per community is small), or keep day-bucketed sets and union the last N buckets on read. "All time" and "year" change slowly and can be rebuilt hourly.

Rising answers "what is gaining momentum?", useful to find posts before they reach Hot. The exact production formula is not public; a reasonable design is the vote rate over the last 30–60 minutes for posts under a few hours old, normalised by the community's typical activity: rising = votes_last_hour / (1 + community_votes_per_post_per_hour). It needs windowed vote counts per post, which the aggregator already has. Rising is computed for young posts only and refreshed every minute or so.

Controversial answers "what is most divided?". Reddit's open-source code used:

def controversy(ups, downs):
    if ups <= 0 or downs <= 0:
        return 0
    magnitude = ups + downs
    balance = downs / ups if ups > downs else ups / downs   # 1.0 means evenly split
    return magnitude ** balance

An evenly split post with many votes scores high (500 up and 500 down gives 1000^1 = 1000); a lopsided one scores low even with many votes (900 up and 100 down gives 1000^0.11 ≈ 2.2).

Best (for comments) answers "which comments are most likely to be good, given limited evidence?". Sorting comments by net score favours early comments (they collect votes for longer); sorting by ratio (ups / total) lets a comment with 1 up and 0 down beat one with 90 up and 10 down. In 2009 Reddit introduced a Best sort, explained in a blog post by Randall Munroe, based on the lower bound of the Wilson score confidence interval for a Bernoulli parameter, the approach described in Evan Miller's essay "How Not To Sort By Average Rating" (2009). The idea: treat each vote as a sample of whether readers like the comment; estimate the true like-rate p̂ = ups / n, and rank by a pessimistic estimate that accounts for small samples:

n = ups + downs,  p = ups / n,  z = 1.28 (about 80% confidence; 1.96 gives 95%)
lower_bound = ( p + z²/(2n) − z · sqrt( p(1 − p)/n + z²/(4n²) ) ) / ( 1 + z²/n )

Worked example with z = 1.2816 (z² ≈ 1.6424):

Commentups / downspWilson lower bound
A1 / 01.00≈ 0.38
B90 / 100.90≈ 0.85
C9 / 10.90≈ 0.72

B ranks above C (same ratio, more evidence), and both rank above A (perfect ratio, almost no evidence). Best also helps fairness: a good late comment can rise above early comments once it has a modest number of votes, because the bound depends on the ratio, not the total. Like Hot, the key depends only on the item's votes, not on the current time.

Bayesian alternatives. A Bayesian average (adding a prior of, say, 5 imaginary up and 5 down votes) or a Beta posterior quantile behaves similarly and allows per-community priors. Wilson has the advantage of no tuning beyond z.

Other comment sorts. Top (net score), New (time), Old (time ascending), Controversial (as above), and Q&A (highlighting replies by the post's author) are all simple keys over the same tree.

Ranking quality versus manipulation. Logarithmic vote terms make early votes very influential for Hot, which is exactly what vote rings target (a dozen fake upvotes in the first minutes). That is why vote weighting by account trust (Deep Dive 10) matters most for young posts.

4. Comment tree storage#

Four classic ways to store a tree in a database, each with clear trade-offs:

ApproachHow it worksRead a whole threadInsert a replyMove or delete subtree
Adjacency listEach row stores parent_idRecursive query or fetch all by post IDO(1)Easy
Path enumeration (materialised path)Each row stores its ancestor path, e.g. 0001.0007.0003Range or prefix scan, naturally depth-firstO(1) given parent's pathRewrite paths of subtree
Nested setsEach node has left and right numbers from a depth-first walkRange query on leftO(n): renumber many nodesExpensive
Closure tableSeparate table of (ancestor, descendant, depth) pairsJoin on ancestorO(depth) rowsMany rows to update

Adjacency list plus partition by post is the best fit here, because we almost always read a whole thread or a large part of it, never "all descendants of an arbitrary comment across posts". All comments of a post live in one partition (Cassandra partition, or one shard in a sharded SQL database with (post_id, comment_id) as the key). One sequential read returns every row; the tree is then built in memory in O(n) with a hash map from parent ID to children. Inserting a reply is a single row write.

In PostgreSQL, a recursive query on an adjacency list can fetch a subtree directly, useful for "load more replies under comment X":

WITH RECURSIVE sub AS (
  SELECT comment_id, parent_id, depth, 0 AS rel_depth
  FROM comment WHERE post_id = $1 AND comment_id = $2
  UNION ALL
  SELECT c.comment_id, c.parent_id, c.depth, s.rel_depth + 1
  FROM comment c JOIN sub s ON c.parent_id = s.comment_id
  WHERE c.post_id = $1 AND s.rel_depth < 5           -- stop 5 levels below
)
SELECT * FROM sub;

PostgreSQL's ltree extension implements materialised paths with indexable prefix queries, an alternative when depth-first ordering by path is desired. See Database Indexing and PostgreSQL in Practice.

Why partition by post matters. Threads are read as units, so a single-partition read avoids scatter-gather. The risk is the giant partition: a 50,000-comment thread is about 35 MB in one partition. Cassandra handles partitions of tens of MB but performance degrades as they grow beyond roughly 100 MB, so very large threads (megathreads that run for days) may need sub-partitioning, for example (post_id, bucket) where the bucket is a time window or a hash of the top-level comment ID. See Apache Cassandra in Practice.

The precomputed tree structure. Rebuilding a sorted tree from 50,000 rows on every view would cost hundreds of milliseconds. Instead the tree builder maintains, per post, a compact structure in cache: for each comment ID, its children's IDs sorted by each sort order, plus per-node counts (number of descendants, used for "N more replies"). For 50,000 comments, the structure for one sort order is roughly 50,000 × (8-byte ID + sort key) ≈ 1 MB, small enough to keep in Redis or in memory on thread servers. Reddit's open-source code kept a similar precomputed "comment tree" per link, updated when comments were added; the design here follows the same idea.

Updates to the structure:

  • New comment: insert its ID into its parent's child list at the position given by its sort key (new comments start with one self-upvote, so their Best key is low).
  • Score change: a comment's Best or Top key changes, so it moves within its sibling list. Sorting is only among siblings, which are usually few, so repositioning is cheap. Batch score changes per post (once a second or so) to avoid constant rewrites on hot threads.
  • Removal or deletion: mark the node; keep it if it has children.
  • Rebuild from source: if the cached structure is lost, rebuild it from the partition in one pass. This is the cache's safety net.

5. Loading comment trees fast#

A thread page should show a useful first screen within about 300 ms, even for a 50,000-comment thread, then load more as the reader expands branches. Three ideas make that possible: select a budgeted subset, send stubs for the rest, and separate structure from content.

Selecting the first screen. Given the sorted tree structure, choose at most limit comments (for example 200) and at most depth levels (for example 10). A depth-first walk that takes every child would spend the entire budget on the first branch. A budgeted best-first walk spreads it sensibly:

select(tree, sort, limit=200, max_depth=10):
    heap = max-heap of (priority, comment) seeded with top-level comments
    chosen = []
    while heap not empty and len(chosen) < limit:
        p, c = heap.pop()
        chosen.append(c)
        if c.depth < max_depth:
            for rank, child in enumerate(sorted_children(c, sort)):
                # deeper and later-ranked children get lower priority
                heap.push((p * DECAY_DEPTH * DECAY_RANK ** rank, child))
    for each chosen node with unchosen children: emit a "more" stub listing those child IDs
    return chosen in tree order

With decay factors around 0.5–0.8, the first screen contains the best top-level comments, the best one or two replies under each, and the best reply to those, which matches what readers actually read. Low-ranked branches become "N more replies" links.

"More" stubs and continue-this-thread. Every omitted set of children becomes a stub carrying the omitted IDs (or a parent ID and an offset, for very large sets). Clicking it calls /comments/more with those IDs; the server runs the same selection on that subtree and returns another batch with new stubs. When a branch reaches the depth limit, the UI shows "continue this thread", which opens a page rooted at that comment. Both are ordinary reads of the same cached structure.

Structure versus content. The tree structure (IDs, parent links, sort keys, descendant counts) is small and changes with every vote; the content (body text, author, flags) is larger and changes rarely (edits). Keep them in separate caches: the thread service reads the structure (one key per post and sort), chooses IDs, then multi-gets bodies by ID from the content cache. This avoids re-serialising 35 MB whenever a vote arrives, and lets the same body cache serve every sort order.

Per-viewer adjustments. After selection, the service applies the viewer's context:

  • Mark the viewer's own votes on visible items (one read from the vote store partition for that user).
  • Hide or collapse comments from users the viewer has blocked.
  • Collapse comments below a score threshold (the viewer's preference), showing "comment score below threshold".
  • Show removed comments to moderators of the community, with the removal reason.

Doing these as a post-processing pass over a shared, cached selection keeps the expensive part (selection) shareable across viewers: the selection depends only on (post, sort, limit, depth), so it can itself be cached for a few seconds on hot threads.

Payload and rendering. 200 comments at 700 bytes ≈ 140 KB of JSON, about 30–40 KB compressed: fine for one response. Clients render the tree progressively and lazy-load images and embeds. Mobile clients may ask for a smaller first batch (50 comments) and fetch more as the user scrolls.

Live updates on hot threads. During live events (a sports match thread), readers want new comments without reloading. Options: poll a "comments since ID X" endpoint every 10–30 seconds (cheap with time-ordered IDs and the post partition), or push via WebSockets or SSE for active viewers. Polling is simpler and cache-friendly; push is better for very active threads. The separate case study Design Live Comments (Facebook Live) covers push fan-out in depth; see also Polling, Long Polling, SSE, WebSockets and Webhooks.

6. Community listings#

Each community has listings for each sort: Hot, New, Rising, Controversial, and Top by window. These are shared: every viewer of r/science sorted by Hot sees the same order (personal filters such as hidden posts are applied afterwards). So they are precomputed and cached, like the shared feeds in the separate case study Design a News Aggregator (Google News).

Representation. A Redis sorted set per (community, sort), members are post IDs and scores are the sort keys:

ZADD   listing:science:hot  4.8213471  t3_abc          # on post creation and on score change
ZREMRANGEBYRANK listing:science:hot 0 -1001            # keep only the top 1000
ZREVRANGE listing:science:hot 0 24                     # first page of 25
ZREVRANGEBYSCORE listing:science:hot (4.8213471 -inf LIMIT 0 25   # next page after a cursor

Each update is O(log n) on a set of at most about 1,000 members. The listing updater consumes post-created and score-changed events, recomputes the post's keys (hot, controversial, top) from its counters, and updates the sets of the post's community. Because the hot key only changes with votes (Deep Dive 3), no periodic rescoring is needed for Hot; Top windows and Rising have their own periodic jobs.

Why cap at 1,000? Almost nobody pages past the first few hundred posts of a sorted listing, and a cap bounds memory and update cost. Reddit's public API is known to return at most about 1,000 items for a listing for the same reason. Deeper history is available through search and "New" from the database (post_by_community_new index).

Pagination drift. Cursors are "after post ID X". Since sorted-set scores change as votes arrive, the server finds X's current score and continues below it. Items that moved above X since the previous page are skipped and items that fell below X may repeat. For a forum, mild drift is acceptable; clients dedupe by ID, and an alternative is to snapshot the listing per session when consistency matters more (as in the news aggregator design). If X has been removed from the set, fall back to the score stored in the cursor itself: encode both ID and score in the cursor.

Removed and filtered posts. Moderation removals delete the member from all sorted sets of that community immediately; the post card cache is invalidated too. Since removals and listing updates race (a late score-changed event could re-add a removed post), the updater checks the post's removed flag before adding.

Large and small communities. The 100 largest communities generate most traffic and most updates; the long tail of small communities rarely changes and is rarely viewed. Listings of inactive communities can be evicted from Redis and rebuilt on demand from the posts table (a few hundred recent posts, one query) on the next view. This keeps memory proportional to activity, not to the number of communities.

Sharding Redis. Shard by community name (all sort orders of one community on one shard, so a listing update touches one shard). The hottest communities' listings are read-heavy: replicas and a short in-process cache in the listing service (1–5 seconds) absorb reads. See Redis in Practice.

Sticky posts and announcements. Moderators can pin up to a couple of posts to the top. Store pins in community metadata and prepend them at read time rather than polluting the sorted sets.

Rebuilding. Redis is a cache here, not the source of truth. A full rebuild of one community's listings reads recent posts and their counters from the durable stores and recomputes keys. A cluster-wide rebuild (after a disaster) can run community by community in priority order of traffic, while the service serves the largest communities first.

Logged-in users land on a home feed built from the communities they joined. Logged-out users see Popular, a site-wide listing.

Fan-out on write or fan-in on read? The separate case study Design a News Feed (Facebook / Twitter) discusses both. Here the answer is clear: fan-in on read, from precomputed community listings.

  • Fan-out on write would copy each new post into the home feed of every subscriber. A large community has tens of millions of subscribers; one post would trigger tens of millions of writes, and Hot ordering changes with every vote, so the copies would constantly need re-sorting. Impractical.
  • Fan-in on read: each community already has a precomputed Hot listing. A home feed is a merge of a few hundred precomputed lists, and the community listings are shared by all members. The number of sources per user (joined communities, typically tens to a few hundred) is small compared with a social graph's followees, and each source is a hot, cached object.

The merge.

home_feed(user, limit=25, cursor):
    communities = subscriptions(user)                         # cached, tens to hundreds
    if len(communities) > MAX_SOURCES: communities = sample_by_activity(communities, MAX_SOURCES)
    lists = pipelined ZREVRANGE top 50 of listing:{c}:hot for each c   # grouped by Redis shard
    merged = k-way merge by normalised hot key, using a heap
    apply diversity: at most 3 posts per community in any 25
    drop hidden posts, posts from blocked users, already-seen posts if requested
    snapshot first 500 IDs in user feed cache for 5 minutes; return page and cursor

Cost: 200 communities × 50 IDs = 10,000 entries fetched with pipelined requests across shards (a few milliseconds), merged in under a millisecond. Cache the merged result per user for a few minutes as a snapshot, so pagination through the home feed is consistent and the merge runs once per session rather than per page.

Normalisation. Raw hot keys compare well within a community but favour large communities across communities (more voters means more votes). For a home feed, a post that is the top post of a 5,000-member hobby community today may matter more to its members than the 30th post of a giant community. Normalise by community activity, for example by subtracting log10 of the community's median votes per post from the vote term, or by using each post's rank-in-community as a feature, and enforce per-community caps so small communities are not drowned out.

Many subscriptions. Users who joined thousands of communities make the merge more expensive. A cap on the number of sources (sample by activity and the user's engagement with each community, rotating over time) bounds the cost. Reddit at one time reportedly drew the front page from a limited random subset of a user's subscriptions for the same reason.

Popular and All. "All" is a global listing: the union of all public communities' posts sorted by hot key. "Popular" is All with filters (excluding NSFW and communities that opt out, with regional variants). Maintain them as global sorted sets updated by the listing updater for posts above a minimum score (most posts never qualify, which keeps update rates low), capped at a few thousand entries. Since they are identical for all logged-out viewers in a region, the CDN caches the rendered pages.

Beyond subscriptions. Modern feeds blend in recommended posts from communities the user has not joined, chosen by a recommendation model. That changes the home feed into a candidate-generation plus ranking problem; the separate case study Design a Recommendation System (Twitter For You) covers it. The fan-in design remains the base layer.

8. Caching hot threads#

When a post reaches the top of Popular, its thread can receive hundreds of thousands of views in an hour, plus a stream of new comments and votes. The challenge is to serve it from cache while comments and scores keep changing.

Layer 1: the CDN for logged-out viewers. Much viral traffic arrives logged out, from search engines and shared links. Their pages are identical, so the CDN caches the rendered thread (or its API response) for 15–60 seconds, with stale-while-revalidate so expiry never causes a miss storm. At a 30-second TTL, each CDN point of presence asks the origin for the thread at most twice a minute, regardless of traffic. See Content Delivery Networks (CDN).

Layer 2: shared selection cache. Logged-in viewers need personal touches (their votes, blocks), but the expensive part, selecting which 200 comments appear (Deep Dive 5), is shared. Cache the selection per (post, sort) for 2–5 seconds on hot posts. Thousands of logged-in viewers per second then share one selection computation per few seconds.

Layer 3: content cache. Comment bodies and post cards are cached by ID in Memcached or Redis; they change only on edits, removals and deletions, which invalidate the single key. Scores are not in the body cache: they come from the counters cache (which updates constantly) and are merged at response time, so frequent votes never invalidate bodies.

Layer 4: in-process caches. For the very hottest keys (the top thread's structure and selection), each thread server keeps a local copy refreshed every second or two. This removes the network hop and protects the cache cluster from hot keys: a single Redis or Memcached key read 100,000 times per second would saturate one node. See Cache Failure Modes: Stampedes, Hot Keys and Penetration.

Stampede protection. When a hot key expires, many servers try to recompute it at once. Use single-flight (one recomputation per key per server), leases or locks in the shared cache (only one server recomputes, others wait briefly or serve stale), and early refresh before expiry. The "Scaling Memcache at Facebook" paper (Nishtala et al., NSDI 2013) describes leases, a cache-provided token that lets only one client fill a missing key and tells others to wait or use stale data; the same idea applies here.

Write amplification on hot threads. A thread receiving 50 comments and 1,000 votes per second would, with naïve invalidation, have its cached tree invalidated 1,050 times a second, which defeats the cache. Instead:

  • Votes update counters only; the tree structure's sort order is re-sorted in batches (once per second or a few seconds per post).
  • New comments are appended to the structure incrementally (not by rebuilding), and the selection cache is simply allowed to expire after a few seconds.
  • Displayed counts (score, comment count) on hot items are refreshed in batches too, and vote fuzzing makes slight staleness invisible.

Who sees a new comment when? The author sees it immediately (read-your-writes, Flow 3). Other logged-in viewers see it within a few seconds (selection cache TTL), logged-out viewers within the CDN TTL (up to a minute). That is an explicit, acceptable staleness budget.

Capacity sanity check. 100,000 views per hour of one thread is about 30 per second, which is easy. The real hot case is a megathread during a global event: perhaps 5,000 views per second plus 100 comments per second. With CDN, selection cache and in-process caches, origin work is a few selections per second and thousands of cheap per-viewer passes per second, well within a handful of servers.

9. Moderation#

Reddit's model is layered moderation: volunteer moderators run each community under its own rules; platform administrators enforce site-wide policy; and automated systems handle volume. The system design must give each layer the right tools and an audit trail.

Moderator roles and permissions. Each community has a moderator list with ordered seniority and fine-grained permissions (manage posts and comments, manage users, manage settings, manage wiki, full). Permission checks happen on every moderation API call: can(user, community, permission), served from a cached moderator table. Seniority prevents a newly added moderator from removing the community's founder.

Moderation actions.

  • Remove / approve a post or comment: sets a flag, removes it from listings (Deep Dive 6), and shows "[removed]" to normal users while moderators still see it with the reason.
  • Lock a thread (no new comments) or a comment (no replies). Enforced in the comment service.
  • Pin (sticky) a post or a moderator comment.
  • Ban a user from the community (temporary or permanent) and mute them from messaging moderators. Enforced at write time (post, comment, vote services consult a cached ban set per community).
  • Set rules and removal reasons, flair (labels), and settings like minimum account age to post.

Every action writes a row to the mod log (who, what, target, reason, time), visible to that community's moderators and summarised in transparency reporting. The mod log is append-only and is the evidence trail for appeals and for admins reviewing moderator abuse.

The mod queue. Items needing human attention arrive from: user reports (with a reason chosen from community or site rules), automatic filters (the rule engine holds an item for review instead of publishing or removing it), and spam classifier flags. The queue is a per-community list ordered by report count, recency and classifier confidence. Moderators process items with one-click approve or remove. Report counts are aggregated per item (many reports on one item do not create many queue entries).

Per-community rule engine (AutoModerator-style). Reddit's AutoModerator, originally built by a volunteer developer and later integrated into the site, lets moderators write rules in a YAML-based language that match conditions on content and authors and take actions. A sketch of the kind of rules such an engine supports:

---
# Remove links to a blocked domain, with a reason shown in the mod log
type: submission
domain: [spam-shop.example, fake-news.example]
action: remove
action_reason: "Blocked domain"
---
# Hold comments from brand-new, low-karma accounts for review
type: comment
author:
    account_age: "< 2 days"
    combined_karma: "< 10"
action: filter
---
# Auto-reply with rules when a post title asks a common question
type: submission
title (includes): ["what should I buy", "which one should I get"]
comment: "Please read the buying guide in the sidebar before posting."

Engine design: compile each community's rules into matchers (regular expressions with timeouts to avoid catastrophic backtracking, set lookups for domains and keywords); evaluate on every new post and comment synchronously for cheap rules (so removed content never appears) and asynchronously for expensive ones. Cache compiled rules per community, invalidated when moderators edit them. Rules see author attributes (account age, karma, previous removals) from a cached user profile.

Crowd control and brigading. When a thread is linked from a hostile community, outsiders flood in (brigading). Tools: collapse or filter comments from users who have not participated in the community before, raise minimum karma thresholds temporarily, lock the thread. The system detects inflow by referrer and by the fraction of first-time participants and can suggest these tools to moderators.

Admin layer. Platform admins enforce site-wide content policy: remove content anywhere, suspend accounts site-wide, quarantine or ban communities, act on legal requests. Admin actions override community settings and are logged separately. Admins also review moderator conduct (for example communities with no active moderators get new ones through a request process).

Appeals. Users can appeal suspensions; the appeal service shows reviewers the content, the action, the rule and the history. Accuracy of moderation decisions (overturn rates) is a quality metric for automated systems.

Data and performance. Moderation reads are low volume compared with feeds, but they must be strongly consistent for the moderator (after removing, the mod immediately sees it removed) and quickly propagated to readers (removed content disappears from listings within seconds, and from CDN-cached pages within the TTL or via purge for urgent cases). Removals are therefore written to the durable store first, then published as events that update listings, caches and search indexes.

10. Spam and vote manipulation#

Every popular forum is a target: commercial spam (links to shops, affiliate scams), karma farming (reposting popular content with bot accounts to build "aged, high-karma" accounts later sold to spammers), political or commercial manipulation (vote rings boosting or burying posts), and harassment. Defences are layered and mostly asynchronous.

Raising the cost of accounts. Sign-up friction for suspicious traffic (CAPTCHA, email or phone verification), limits on accounts per device or IP range, and reduced powers for new accounts: rate limits on posting and commenting (for example one post per 10 minutes until the account has some karma), votes weighted lower, links held for review in many communities. See Rate Limiting and Throttling.

Account trust score. A per-account score combining age, verified email, karma from diverse communities, history of removals and reports, device and network reputation, and behavioural signals. Trust drives vote weight (Deep Dive 2), rate limits and whether content goes to review. It is updated asynchronously as signals arrive and cached for the write services.

Content signals. Classifiers over post and comment text, link domains (domain reputation: spam reports, link-shortener chains, newly registered domains), and repost detection: link URL fingerprints and perceptual hashes of images let the system recognise a karma-farming bot reposting yesterday's top image. Near-duplicate text detection (SimHash or MinHash over comments) finds the same spam message posted across many threads. See Probabilistic Data Structures for Big Data.

Vote manipulation detection. Vote rings share patterns that are hard to hide at scale:

  • Co-voting: a set of accounts that repeatedly vote on the same items within short time windows. Build a graph where accounts are nodes and edges are weighted by co-votes on the same items within minutes; dense clusters of mostly low-trust accounts are rings. Graph algorithms (connected components over thresholded edges, community detection) run in batch over the last days of votes.
  • Timing: bursts of votes on one item from accounts that arrived via the same link or share network attributes, often immediately after submission (when the Hot formula is most sensitive).
  • Self-voting via alternate accounts: accounts voting for one author's content far more than chance, sharing devices or IPs.
  • Vote velocity anomalies for a community: an item gaining votes much faster than items with similar views (votes per view is a strong signal, since rings vote without real views).

Response: discount the votes (weight to zero) rather than delete them, recount affected items, and act on accounts. Acting quietly matters: a shadowban lets a bot keep posting into a void, so its operator does not immediately learn it was detected and does not just create a new account. Fuzzed vote displays (Deep Dive 2) serve the same purpose.

Feedback loop. Moderator removals and user reports are labels for training classifiers; admin decisions on appeals measure false positives. Track precision and recall per classifier and per language, and keep humans in the loop for borderline cases.

Pipeline shape. Inline checks are cheap and synchronous (rate limits, banned domains, known-bad hashes, account status). Everything else consumes the event log: classifiers in a streaming job (seconds), ring detection in batch (hours) with a streaming approximation for fast-moving cases. The write path never waits for expensive models; if the safety pipeline lags, content is still published (or held, for low-trust accounts) and cleaned up shortly after.

11. Storage at scale: sharding, the event log and consistency#

Sharding the relational core. Users, communities and posts start on one PostgreSQL primary with read replicas. Growth forces sharding:

  • Posts shard by post ID (hash), so writes spread evenly. "New posts in community C" needs a cross-shard query, which is avoided by keeping New listings in Redis (from events) and, for deep history, a secondary index table sharded by community: (community_id, created_at, post_id).
  • Users shard by user ID. Username lookups go through a small global uniqueness table (or a dedicated service), because uniqueness across shards cannot be enforced by a single index.
  • Communities are few (millions including inactive ones) and fit unsharded with replicas.

See Partitioning and Sharding.

Comments and votes in a wide-column store. Comments partition by post, votes by user. Both are append-heavy with simple key access, the sweet spot for Cassandra or ScyllaDB (or DynamoDB as a managed option): writes are cheap, replication factor 3 across racks or zones, tunable consistency. Use LOCAL_QUORUM writes and reads for votes (so a user's vote is durable and readable after acknowledgement in their region) and LOCAL_ONE reads for comment bodies where slight staleness is fine. Votes also need a second view, "votes on item X" for recounts and fraud analysis, which is served by the event log and the data warehouse rather than a second online table.

The event log is the backbone. Every write publishes an event to Kafka: post-created, comment-created, vote-changed, score-changed, mod-action. Derived systems (counters, listings, trees, search, notifications, safety, analytics) each consume at their own pace. Benefits: the write path is short; consumers can be rebuilt by replaying; adding a new derived view (a new sort, a recommendation feature) needs no change to writers. Partition keys are chosen per topic: votes by user for delta computation, deltas by item for aggregation, comments by post for tree building. See Event-Driven Architecture.

Writing to the store and the log consistently. If the comment service writes the comment and then crashes before publishing the event, the tree never shows the comment. Options: the transactional outbox (write the event into an outbox table in the same database transaction, then a relay publishes it), or change data capture from the database log. For the wide-column stores, the vote path above inverts the order: the log is written first (the command), and the vote store is a materialised view of it. See Change Data Capture and the Outbox Pattern and Delivery Guarantees: At-Most, At-Least and Exactly-Once.

Idempotent consumers. Kafka delivers at least once. Consumers must tolerate duplicates: the tree builder ignores a comment ID already in the tree; the listing updater's ZADD is naturally idempotent (it sets, not adds); the vote aggregator is the delicate one, because counters add. Make deltas idempotent by carrying an event ID and having the aggregator commit its Kafka offsets atomically with the counter writes (or by deduplicating recent event IDs per partition), and rely on periodic recount for residual drift.

Consistency summary.

DataGuaranteeMechanism
One vote per user per itemStrictPer-user serialisation, conditional writes
User sees own vote, comment, postRead-your-writesRead vote store and recent-writes cache, optimistic UI
Scores and countsEventual, secondsBatched aggregation, fuzzed display, periodic recount
ListingsEventual, seconds to a minuteEvent-driven updates, rebuildable
Moderator removalImmediate for mods, seconds for readersDurable write first, then events and purges
Comment trees for other readersEventual, secondsIncremental tree builder, short selection TTL

See Consistency Models.

Multi-region. Reads are served from several regions (CDN plus regional caches and replicas). Writes can be single-region (simplest: all writes go to the primary region, with a few tens of milliseconds of extra latency for distant users) or multi-region with per-user home regions. Given that votes and comments tolerate eventual consistency for others but need strictness per user, homing each user's writes in one region keeps the per-user serialisation simple while replicating results globally. See Multi-Region and Global Data.

12. Search, notifications and other derived features#

Search. Index posts (title, body, community, flair, author, score, time) and optionally comments in Elasticsearch or OpenSearch, fed by the event log. Queries combine text relevance with signals such as score and recency, and filters (community, time range, NSFW). Comments are much more numerous; index them separately with shorter retention or only above a score threshold, since comment search is used less and costs more. Removals and deletions must propagate to the index quickly (delete by ID from the event). See Elasticsearch and Search Systems.

Duplicate and "other discussions" detection. Link posts are normalised (strip tracking parameters, resolve canonical URLs) and hashed; a lookup by URL hash finds other posts of the same link across communities, shown as "other discussions" and used by repost rules.

Notifications. Replies to your post or comment, mentions (u/username), and moderator messages trigger notifications. A notification consumer reads comment-created events, finds the parent's author (and mentioned users), applies preferences and rate limits (no 500 notifications for one viral comment, batch them as "you have 500 new replies"), and sends to an inbox store and push providers. The separate case study Design a Notification System covers the delivery pipeline.

User profiles and history. "Posts by user U" and "comments by user U" need indexes by author: secondary tables (author_id, created_at, item_id) fed from events, sharded by author. These are read on profile views and by moderators checking a user's history.

Karma, trophies and flair. Derived asynchronously from score events (Deep Dive 2). Low urgency, high tolerance for delay.

Analytics. Every event also lands in a data lake (object storage in a columnar format) for community insights for moderators (views, subscribers over time), trust and safety analysis, and model training. See Data Pipelines, Warehouses and Lakes.

Bottlenecks and Failure Modes#

Failure / hotspotImpactMitigation
Viral post: hot counter rowLock contention, slow votesBatch deltas per item in the aggregator, Redis counters, periodic write-back, sharded counters if needed
Hot thread cache keyOne cache node saturatedIn-process caches, shared selection cache, CDN for logged-out views, key replication
Cache expiry on a hot threadStampede of recomputationSingle-flight, leases, stale-while-revalidate, early refresh
Concurrent votes from one userDouble-counted votesSerialise per user via partitioned log, conditional writes, recount job
Vote aggregator lagScores and Hot ordering staleAutoscale consumers on lag, batch harder, the voter still sees own vote; alert on consumer lag
Giant comment partition (megathread)Slow reads, compaction pressureBucketed partitions for huge threads, precomputed tree structure, archive old megathreads
Event published before or without the writeMissing or phantom comments in treesOutbox or CDC, idempotent consumers, tree rebuild from the partition
Redis listing lossEmpty or wrong listingsRebuild from durable posts and counters, prioritise biggest communities, serve stale CDN pages meanwhile
Home feed merge for users with thousands of subscriptionsSlow home pageCap and sample sources, per-user snapshot cache for minutes
Vote ring boosts a post in its first minutesManipulated rankingsTrust-weighted votes, co-vote graph detection, recount, shadowban
Brigading from another communityToxic flood, report stormsCrowd control filters, temporary karma thresholds, lock thread, referrer detection
Removal propagation lagRemoved content still visibleDurable write first, immediate listing removal, cache invalidation, CDN purge for urgent removals

What Interviewers Expect#

Mid-level. Model communities, posts, comments and votes; design APIs; store comments with a parent ID and votes as one row per (user, item). Explain Hot versus New versus Top and roughly why Hot needs both votes and time. Use a cache for popular pages and a CDN for media. Paginate listings with cursors.

Senior. Identify votes as the dominant write and design for it: idempotent vote API, delta computation, asynchronous batched aggregation, read-your-writes for the voter. Present the Hot formula's key property (static per item, changes only with votes) and why that enables sorted-set listings. Explain Wilson-score Best for comments. Store comment trees partitioned by post and load a bounded subset with "more" stubs. Choose fan-in on read for home feeds from precomputed community listings. Describe layered caching for hot threads and moderation tooling with a mod log.

Staff and above. Treat abuse resistance as a first-class requirement: trust-weighted votes, vote fuzzing and shadowbans as anti-feedback measures, co-vote graph detection, and recounts. Separate tree structure from content to avoid invalidation storms; quantify the hot thread case. Discuss the event log as the backbone with outbox or CDC, idempotent consumers and partition-key choices per topic. Make consistency explicit per data type. Address operational realities: giant partitions, listing rebuild order, archive policies, multi-region write homing, and the social system around the software (volunteer moderators, appeals, transparency).

Deep Dive: What is publicly known about Reddit's architectureShow

Reddit is a useful case because parts of its architecture have been described publicly over many years. Only well-documented points are summarised here, and the details may have changed since.

  • Language and code. Reddit was first written in Common Lisp and rewritten in Python in 2005. The Python codebase, "r2", was open-sourced in 2008 and archived in 2017. The open-source code is where the Hot, Controversial and Best (confidence) sort functions shown in Deep Dive 3 come from.
  • "Thing" storage. Talks and the r2 code describe storing each entity type in PostgreSQL as a narrow "thing" table plus a key-value "data" table, which let developers add attributes without schema migrations, while caches (Memcached) did most of the read work.
  • Precompute everything. A recurring lesson in early talks by Reddit's founders was to precompute listings and do expensive work offline through queues rather than in the request path, so pages are assembled from ready-made pieces. Listings and comment trees were kept precomputed and updated when votes or comments arrived; Cassandra was later used for some of these precomputed, cached structures.
  • Queues for votes. Vote processing was asynchronous through message queues in r2; heavy vote traffic and queue backlogs are a known operational theme, which is why this design batches deltas and keeps the voter's own view correct independently of the aggregate.
  • Cloud. Reddit moved to Amazon Web Services early, and it was among the sites affected by AWS's April 2011 EBS outage, an episode often cited as a lesson in not depending on a single storage system or availability zone.
  • Later evolution. Reddit's engineering blog has described, over the years, a gradual move from the Python monolith toward services, along with modern clients and APIs. The general shape (event-driven derived views, heavy caching, precomputed listings) remains a sensible model.

Lessons to carry into the interview. Precompute what everyone reads; keep the write path tiny and push work to queues; make caches rebuildable; and expect the hardest problems to be human: spam, manipulation and moderation.

Deep Dive: Sizing every tierShow

All figures follow the Capacity Estimation assumptions; they are for checking that the design hangs together, not Reddit's real numbers.

Edge and API. 150,000 page views per second at peak, perhaps half logged out. With a CDN hit ratio around 90% for logged-out pages, the origin receives about 7,500 logged-out and 75,000 logged-in page requests per second, each fanning out to a few internal calls. At a few thousand requests per second per API instance, that is roughly 50–100 instances per serving region with headroom.

Vote path. 20,000 votes per second at peak. Kafka handles this trivially (a few MB/s). Per-user serialisation with, say, 64 partitions means about 300 votes per second per partition worker, each doing one local-state read and one vote-store write: comfortable. The vote store takes 20,000 writes per second at replication factor 3 (60,000 replica writes per second), within reach of a modest Cassandra cluster (a well-sized node sustains tens of thousands of small writes per second). The aggregator batches per item: if votes spread over 200,000 active items per minute, it issues a few thousand counter increments per second to Redis.

Comment path. 1,000 comments per second at peak, each a single-partition write and an event. The tree builder updates per-post structures: on the hottest thread, perhaps 50–100 inserts per second plus batched re-sorts once a second. Small.

Redis memory. Listings about 10 GB; counters for active items (a few million items × about 50 bytes) a few hundred MB; tree structures for active threads (say 100,000 active threads × average 50 KB, with a long tail of large ones) about 5 GB; home feed snapshots for active sessions (5 million × 4 KB) about 20 GB. Roughly 40 GB per region, spread over a cluster with replicas.

Content cache. Hot post and comment bodies: tens of millions of items × about 700 bytes ≈ tens of GB in Memcached, with a high hit ratio because reads concentrate on recent threads.

Storage growth. About 6 TB a year of post and comment text, roughly 5–15 TB a year of votes with replication overhead excluded, and tens of TB of media a month. Votes on archived posts can move to cheaper, compacted storage; media dominates cost and benefits most from lifecycle tiering. See Data Lifecycle, Tiering and Retention.

Takeaway. No single tier is enormous; the difficulty is hot spots (viral threads, giant communities) and abuse, not raw volume. That is where interview time should go.

Deep Dive: The mathematics of the ranking formulasShow

Hot as a decay in disguise. Write the hot key as h = log10(s) + t/45000 for a positive net score s and submission time t. At a fixed current time T, compare two posts by subtracting T/45000 from both keys; the order is unchanged, and the key becomes log10(s) − age/45000, that is log10(s × 10^(−age/45000)). So Hot is equivalent to ranking by score multiplied by an exponential decay with a half-life of 45000 × log10(2) ≈ 13,550 seconds ≈ 3.8 hours. Every 3.8 hours of age halves a post's effective score. This shows Reddit's formula is the same family as exponential-decay rankings, implemented so the key is fixed at vote time.

How long does a post stay on top? Suppose the top post has 20,000 net votes and stops gaining. A new post submitted 6 hours later needs 20,000 / 10^(21600/45000) = 20,000 / 10^0.48 ≈ 20,000 / 3.02 ≈ 6,600 votes to pass it. After 12.5 hours, 2,000 votes are enough. This is why front pages turn over within a day.

Sensitivity to early votes. The derivative of log10(s) is 1/(s ln 10): at s = 1, one vote moves the key by about 0.43, equivalent to about 5.4 hours of newness (0.43 × 12.5). At s = 1,000, one vote moves it by 0.0004, about 20 seconds. Early votes are hugely influential, which is good for discovering new posts but is exactly what manipulators exploit; hence trust-weighting of early votes.

The sign discontinuity. A post at +1 has vote term 0 (log10 1 = 0) with sign +1; at 0 the term is 0; at −1 the term is 0 with sign −1, which is still 0. Only below −1 does the term become negative: at −10 it is −1, the equivalent of being submitted 12.5 hours earlier. Posts that are disliked sink fast, as intended.

Why the Wilson lower bound. If a comment's true approval rate is p, then after n votes the observed ratio p̂ is a noisy estimate. A confidence interval says "with probability 1−α, p lies between L and U". Sorting by p̂ ignores the noise; sorting by L (the pessimistic end) rewards comments for evidence as well as ratio. The Wilson interval (Edwin B. Wilson, 1927) is preferred to the simpler normal approximation p̂ ± z sqrt(p̂(1−p̂)/n) because the latter gives nonsense for small n or p̂ near 0 or 1 (an interval of zero width for 1 up, 0 down). The Wilson formula includes the z²/n corrections that pull small samples toward 0.5.

Choosing z. Larger z (95% confidence, z = 1.96) is more conservative: new comments need more votes to rise. Smaller z (80%, about 1.28) lets good new comments rise faster. It is a product dial, not a statistical truth.

Controversy shape. (ups + downs)^balance with balance in (0, 1] means volume matters only when the split is close: at balance 1 the score equals total votes, and at balance 0.1 even 10,000 votes give 10000^0.1 ≈ 2.5. A smoother alternative is total × (1 − |ups − downs| / total), which is linear in volume and penalises imbalance linearly.

Ranking comments by time and quality. Best is static per comment, so late comments on old threads rank fairly once they get votes, but they get few views. Some systems add a small "new comment boost" decaying over the first hour, or reserve a few slots in the selection for new comments, to give them a chance to collect votes (an exploration term, the same idea as in multi-armed bandits).

Deep Dive: Counting views with HyperLogLogShow

Posts often show a view count. Counting unique viewers exactly would mean storing every (post, viewer) pair: billions of pairs a day. Reddit's engineering blog described (in 2017) counting post views with HyperLogLog, a probabilistic structure that estimates the number of distinct items with a few KB of memory and about 1% error.

How it works, briefly. Hash each viewer ID; for each hash, look at the position of the first 1 bit. Seeing a hash with many leading zeros is evidence that many distinct items were hashed (like estimating how many coins were flipped from the longest run of heads). HyperLogLog splits hashes into many buckets (for example 16,384), keeps the maximum leading-zero count per bucket, and combines them with a harmonic mean. Redis implements this as PFADD and PFCOUNT with a 12 KB dense representation and a sparse encoding for small counts. See Probabilistic Data Structures for Big Data.

Pipeline. View events go to Kafka; a consumer filters bots and duplicate refreshes (for example, the same viewer within a short window), then PFADD view:{post} {viewer}. A periodic job persists HLL blobs for posts that changed to durable storage, so counts survive cache loss, and drops HLLs of posts that stopped getting views. Display rounds the count ("1.2k views").

Why not exact counts? A popular post with 10 million unique viewers would need a set of 10 million IDs (around 80 MB); an HLL needs 12 KB regardless. One percent error is invisible to users. Exact counts can still be computed offline in the warehouse when needed (for example for community analytics).

Deep Dive: Media posts and safety scanningShow

Image and video posts are a large share of engagement and almost all of the bytes. See Pattern: Handling Large Files and Blobs.

Upload. The client asks for an upload slot; the media service returns a presigned URL to object storage and a media ID. The client uploads directly (multipart for large videos), then submits the post with the media ID. The post stays in a "processing" state until media processing completes, typically seconds for images and up to a minute or two for video. See Object Storage and Blob Storage.

Processing. Images: decode safely, strip metadata such as GPS location (privacy), generate renditions (thumbnail, feed width, full) in WebP or AVIF with JPEG fallback. Video: transcode to adaptive bitrate renditions (HLS or DASH, several resolutions), extract a poster image, and generate a short preview. The separate case study Design a Video Streaming Platform (YouTube / Netflix) covers transcoding pipelines in depth.

Safety scanning before publication. Uploaded media is checked against hash lists of known illegal content (for example Microsoft's PhotoDNA perceptual hashing, widely used across the industry for child sexual abuse material), with matches blocked and reported as the law requires. Classifiers flag adult content (to enforce NSFW labelling where the community does not allow it) and graphic violence. These checks must finish before the post is visible, which is one reason media posts have a processing state.

Serving. Media is served from the CDN with immutable, content-addressed URLs and long cache lifetimes. Removal of a post must also make its media inaccessible: delete or revoke the object and purge the CDN for the affected URLs.

Link posts. For link posts, fetch the target page once to extract a preview (title, image), with the same protections as any server-side fetcher (block private network addresses to prevent SSRF, size and time limits), and store the preview image ourselves rather than hotlinking.

Deep Dive: Deletion, privacy and data retentionShow

What deletion means. When a user deletes a comment, the body and author are removed, but the node stays in the tree as "[deleted]" if it has replies. When a user deletes their account, their username is detached from content ("[deleted]" author), and depending on policy and law their content may also be removed. Moderator removal is different: the content is hidden from the public but retained for moderation and appeals for a defined period.

Propagation. A deletion is a durable write followed by events that update every derived copy: listings, tree structures, content caches, search indexes, notification inboxes, CDN caches (purge), and the analytics lake (deletion jobs or tombstones honoured downstream). A deletion request ID tracks completion across systems, since regulations such as the EU's GDPR give users rights to erasure with deadlines.

Backups. Backups contain deleted data. Common practice: keep backups for a limited window (for example 30–90 days) so deleted data ages out, or encrypt per-user data with keys that can be destroyed ("crypto-shredding"), making the backup copies unreadable. See Disaster Recovery and Backups.

Votes and privacy. Votes are private by default: only aggregates are shown. The vote store and logs are sensitive (they reveal views on politics, health, sexuality), so access is restricted and retention limited for raw logs; aggregate counts are kept.

Public data and the API. Public posts are visible to anyone and widely copied by third parties; deletion on the platform cannot remove copies elsewhere. Access to bulk data through the API is governed by terms and rate limits, which is both a business and a privacy question. See Security Fundamentals for System Design.

Deep Dive: Encoding and maintaining the comment tree structureShow

The tree structure cache (Deep Dives 4 and 5) is the most performance-sensitive object in the system. A few implementation details decide whether it stays fast under load.

Single writer per post. The tree builder consumes comment-created, comment-removed and comment-score-changed events partitioned by post ID, so one worker thread owns each post's structure. No locks are needed and updates apply in order. The worker keeps the structure for active posts in memory and writes a serialised copy to Redis for the thread servers to read.

Encoding. Options:

  • One Redis hash per post and sort, field = parent ID, value = packed array of child IDs in sorted order. Reading the top of the tree reads a few fields (the root's children, then the children of chosen nodes), each a small value. Updating one sibling list rewrites one field.
  • One blob per post and sort: the whole structure serialised (for example a compact binary of parent, child, key triples). Reading is one GET (about 1 MB for the largest threads, much less for typical ones); writing rewrites the whole blob. Fine for small and medium threads, wasteful for megathreads with frequent updates.

A hybrid works well: blob for threads under a few thousand comments (the vast majority), hash-per-parent for giant threads.

Versioning. Each write increments a version number stored with the structure. Thread servers cache the structure locally with its version and check the version cheaply (a tiny key) every second or two; they refetch only when it changed. Selections cached in the shared cache are keyed by (post, sort, version), so a stale selection is never mixed with a newer structure.

Batching re-sorts. Votes on comments arrive constantly on hot threads. The worker marks touched parents as dirty and every second re-sorts only the dirty sibling lists (each typically small: most comments have a handful of replies; a viral post's top level may have thousands of direct children, and sorting a few thousand keys takes well under a millisecond). It then writes one new version.

Multiple sort orders. Best, Top, New, Old and Controversial each need their own child ordering. New and Old are just ID order (free). Best, Top and Controversial are maintained eagerly only for active posts; for cold posts, the structure for a requested sort is built lazily from the partition on first request and cached.

Descendant counts. "12 more replies" needs subtree sizes. Maintain them incrementally: inserting a comment increments the count of every ancestor (depth is bounded, usually under 20, so this is cheap). Removals of leaf comments decrement; deleted nodes with children keep their counts.

Recovery. If a worker dies, another takes over the Kafka partition, loads the last structure version from Redis, and replays events since the offset stored with that version. If Redis lost the structure, rebuild from the comment partition. Either way the tree converges without manual intervention.

Deep Dive: Private, restricted and age-gated communitiesShow

Not all content is public, and access rules interact with caching in ways that are easy to get wrong.

Community types. Public (anyone reads, members post), restricted (anyone reads, approved users post), private (only approved members read). Some communities are marked NSFW (adult content; viewers must opt in and, in some jurisdictions, verify age) or quarantined by admins (shown with a warning, excluded from Popular and search, requiring an explicit opt-in).

Authorisation on every read. Listing, thread, comment-load, search and profile endpoints must check whether the viewer may see each item's community. A cached per-community access policy plus a per-user set of approved private communities makes this a fast in-memory check. Search results and user profile histories must also filter by access, which is easy to forget because they cut across communities. See Authentication and Authorization.

Caching pitfalls. The CDN may cache only responses that are identical for everyone allowed to see them and that everyone is allowed to see. Responses for private, NSFW or quarantined communities are therefore marked Cache-Control: private, no-store (or cached only with the viewer's entitlement as part of the key), never public. A single mistake here, such as a private thread cached publicly, is a data leak. Shared internal caches (selection, content) are fine because access is checked after the cache read, before the response is built.

Changing visibility. When a public community becomes private, cached public responses for it must be purged at the CDN, and listings for Popular and All must drop its posts. Treat the visibility change as an event that triggers purges, just like a removal.

Media. Media of private communities should be served through signed, expiring URLs rather than permanent public CDN URLs, so a leaked link stops working.

Deep Dive: Growing the design step by stepShow

Interviewers sometimes ask how the system would evolve from a small start. A plausible progression:

  1. One application server and one PostgreSQL database. Posts, comments (adjacency list), votes (unique index on user and item), with listings computed by SQL ORDER BY on a hot-score expression index. Works for thousands of users.
  2. Add caching and a CDN. Memcached for rendered listings and threads; CDN for static assets and logged-out pages. The database load drops by an order of magnitude. See Scaling from Zero to Millions of Users.
  3. Move work off the request path. Votes go through a queue; counters are updated by workers in batches; listings are precomputed into Redis sorted sets. This is the big step that decouples write volume from read latency.
  4. Read replicas and precomputed comment trees. Thread rendering no longer queries all comments; the tree builder maintains structures.
  5. Split storage by access pattern. Comments and votes move to a wide-column store partitioned by post and by user; the relational database keeps users, communities and posts, then gets sharded.
  6. Event log as backbone. Kafka replaces ad-hoc queues; search, notifications, safety and analytics become consumers.
  7. Multi-region serving and safety at scale. Regional caches and replicas, user-homed writes, ML-based spam and vote-ring detection, and mature moderation tooling.

Each step is triggered by a measured bottleneck: database CPU from listing queries, row contention from votes, slow thread pages, storage growth of votes, coupling between teams. Naming the trigger for each step is what makes the answer convincing. See Pattern: Scaling Reads.

Deep Dive: Measuring community health and testing changesShow

A forum's success is measured by more than page views. Changes to ranking, feeds and moderation tools should be judged against health metrics as well as engagement.

Metrics. Daily and weekly active users per community; posts and comments per active user; share of posts receiving at least one comment (a sign that new posts get seen); time to first comment; removal rates and report rates; moderator workload (queue size and time to action); share of content removed by automation versus humans; appeal overturn rates; new-user retention after their first post (did they get a reply or get removed?).

Experiments. Ranking and feed changes are tested with randomised experiments per user, but forum dynamics are networked: changing what one group sees changes what gets votes, which changes rankings for everyone. Cluster-randomised experiments (by community) or switchback designs reduce this interference. Guardrail metrics (removal rates, reports, diversity of communities in home feeds) must not regress.

Ranking parameter changes. For changes to Hot's time constant or Best's z, replay historical vote streams through the new formula offline to see how listings would have differed, before running a live test. Because these formulas are static per item, replay is cheap: recompute keys from stored counts and times.

Moderator tooling changes. Measure with moderators, not just users: time saved per action, accuracy of automated filters per community, and qualitative feedback. Volunteer moderators are a scarce resource; tools that waste their time harm the platform even if engagement metrics look fine.

Deep Dive: Surviving a mega-event threadShow

Some threads are planned spikes: an "Ask Me Anything" (AMA) with a celebrity, a live thread for an election or a sports final, a product launch. Others are unplanned: breaking news that sends millions to one megathread. They combine every hard part of the design at once.

What happens. Views jump to thousands per second on one thread; comments arrive at tens to hundreds per second; votes on top comments at hundreds per second; moderators face a flood of reports; spam bots target the most visible thread on the site.

Before the event (planned). Moderators create the thread in advance; operators pre-warm caches and the CDN for the thread URL, and scale out the thread servers and tree builder partitions. For AMAs, a Q&A sort highlights questions answered by the guest: the tree builder marks comments that have a reply from the post author (or a verified participant) and sorts those first. Moderators may enable stricter filters (minimum account age to comment) to cut spam.

During the event.

  • The thread's structure and selection live in in-process caches on every thread server, refreshed by version every second.
  • Comment writes go through the normal path, but the tree builder handles the hot post on a dedicated partition (or a dedicated worker) so it cannot delay other posts' updates.
  • The default sort may switch to New for live threads, which is cheaper (ID order) and matches what readers want.
  • Rate limits per user tighten for that thread to keep comment volume readable and protect the pipeline.
  • If load still exceeds capacity, degrade gracefully: serve slightly staler selections (5–10 seconds), defer descendant-count updates, pause expensive per-viewer features (for example score thresholds) before ever failing requests.

Megathread partitions. A thread that runs for days can reach hundreds of thousands of comments. Rather than one giant partition, bucket comments by time window under the post (Deep Dive 4), and consider "continuation" threads (moderators lock the old megathread and open a new one), which is both a product and a storage solution.

After the event. Let caches age out, compact the partition, and archive the thread once activity stops.

Deep Dive: The public API and third-party clientsShow

Reddit has long offered a public API used by bots, moderation tools and third-party apps. Designing for it is part of the system.

Authentication and scopes. OAuth 2.0 with scopes (read, vote, submit, moderate) lets users grant apps limited powers. Moderation bots use accounts with moderator permissions in specific communities. See Authentication and Authorization.

Rate limits and quotas. Per-client and per-user limits (requests per minute) protect the platform from scrapers and runaway bots, with clear headers telling clients their remaining quota. Heavy consumers (search engines, research datasets, commercial data users) get separate agreements and bulk access paths instead of hammering the live API.

Consistency with first-party clients. The API should use the same services as the website and apps, so rules (bans, rate limits, filters) apply equally. Bots are a major source of both useful automation (moderation helpers) and abuse (spam, vote manipulation), so API traffic feeds the same trust and safety pipeline.

Product decisions shape load. In 2023 Reddit introduced pricing for large-scale API access, which led many third-party apps to shut down and prompted widespread protests in which many communities went private for a period. Whatever one thinks of the decision, it illustrates that API access policy is both a business and an engineering decision: it determines how much load comes from outside clients, and changes to it can affect the community that runs the site's moderation.

Deep Dive: Which store for comments and votes?Show

The design uses a wide-column store for comments and votes, but other choices are defensible. The deciding factors are write volume, access patterns, operational skills and cost.

OptionStrengthsWeaknessesFits when
Sharded PostgreSQL (by post for comments, by user for votes)Transactions, unique constraints, rich queries, recursive CTEs, familiar toolingResharding is manual work; very high write rates need many shards; vacuum and index bloat on huge vote tablesTeam knows Postgres well; scale is up to tens of thousands of writes per second
Cassandra or ScyllaDBCheap high-volume writes, linear horizontal scaling, multi-datacenter replication, partition-per-post fits threadsNo joins, limited secondary indexes, lightweight transactions are slow, large partitions need careWrite-heavy, key-based access, multi-region needs
DynamoDBFully managed, scales automatically, conditional writes for one-vote rules, streams for eventsItem size limit (400 KB), cost at very high throughput, hot-partition limits per key, vendor lock-inSmall team, AWS-based, predictable key access

Vote uniqueness in each. Postgres: a primary key on (user, item) plus INSERT ... ON CONFLICT DO UPDATE returning the old value gives an atomic delta in one statement. DynamoDB: an UpdateItem with ReturnValues=ALL_OLD returns the previous direction atomically, from which the delta is computed. Cassandra: either a lightweight transaction or the per-user serialisation from Deep Dive 2, because plain writes are last-write-wins without returning the old value.

Comments in each. All three support "all comments of post P" as a single-partition or single-shard range read. Postgres adds the ability to run recursive subtree queries directly; Cassandra and DynamoDB rely on the precomputed tree structure.

Operational cost matters as much as features. A vote table growing by 150 billion rows a year stresses every option differently. In PostgreSQL, routine maintenance (vacuum, index rebuilds) and backups of multi-terabyte shards take careful scheduling, and adding shards means moving data with dual writes or logical replication. In Cassandra, compaction strategy choice (size-tiered for write-heavy tables, leveled for read-heavy ones, time-window for time-series-like data) determines disk headroom and read latency, and repairs must run regularly to keep replicas consistent. In DynamoDB, the main levers are capacity mode (on-demand versus provisioned with autoscaling) and key design to avoid hot partitions. A common pragmatic path is to start with sharded PostgreSQL, which keeps the data model simple, and move only the votes table to a wide-column or managed key-value store once its size and write rate dominate everything else.

There is no single right answer; an interviewer wants to hear the access patterns stated first and the store chosen to match them, with the trade-offs named. See Amazon DynamoDB in Practice and Choosing a Database: A Decision Guide.

Deep Dive: A 45-minute interview planShow
MinutesWhat to do
0–5Clarify scope: communities, posts, nested comments, votes, sorts, home feed, moderation. Confirm read-heavy, votes as the dominant write, eventual consistency for counts.
5–10Estimate: 70M DAU, 150k page views per second at peak, 20k votes per second, 1k comments per second; largest thread 50k comments; listings about 10 GB.
10–15Entities and APIs: idempotent vote PUT, bounded comment-tree endpoint with "more" stubs, cursor-paged listings.
15–25High-level design: write services plus event log; vote store and aggregator; listing updater and Redis sorted sets; comment store by post plus tree builder; home feed by fan-in; CDN and caches; safety pipeline.
25–40Deep dives (interviewer's choice): vote counting and races; Hot and Best formulas and why their keys are static; comment tree storage and budgeted loading; caching hot threads without invalidation storms; spam and vote rings.
40–45Failure modes, consistency per data type, moderation propagation, what you would build next (recommendations, search, live threads).

Common mistakes. Incrementing a counter row per vote; recomputing Hot for every post periodically without noticing the formula's static key; loading entire comment trees per page view; fan-out on write to tens of millions of subscribers; ignoring manipulation; treating moderation as an afterthought.

Deep Dive: Follow-up questions and strong answersShow

"Why not store scores only in Redis?" Redis is the fast path but not the source of truth. The vote store holds every vote; counters can be recomputed from it. Durable write-back of counters to post and comment rows also gives fast reads after a cache loss without a full recount.

"How would you show 'N new comments since your last visit'?" Store each user's last-visit time per thread (a small per-user key-value map with TTL). With time-ordered comment IDs, counting comments after that ID is a range count on the post's partition, or a lookup in the tree structure's per-post creation list.

"What happens if the tree cache for a megathread is lost?" The thread service rebuilds it from the post's comment partition (one sequential read, tens of MB for the largest threads, taking under a second or two), protected by single-flight so only one rebuild runs. Meanwhile the CDN and stale selections keep serving.

"How do you support 'Top of all time' across 15 years of posts?" It changes very slowly; compute it in a batch job from the posts table (or warehouse) hourly or daily per community and store the top 1,000. No live maintenance needed.

"Two moderators act on the same item at once." Moderation actions are idempotent state changes (removed or approved) with a version check; the last action wins and both are logged. The mod queue marks an item as being handled to reduce duplicate work, but correctness does not depend on it.

"How would you rank comments in a live sports thread?" Default the sort to New for live threads (a community or post setting), use push or short-interval polling for new comments, and keep the selection cache TTL to a second or two.

"Could you use a graph database for comments?" Comments are a tree read as a whole per post; a graph database adds little over adjacency lists partitioned by post, and graph databases are harder to scale for this write volume. Graph processing is useful for vote-ring detection (account co-vote graphs) in batch. See Graph Databases.

"How do you keep a removed post from reappearing via a late event?" Listing updaters and tree builders check the item's removed flag (from a fast cache) before inserting; removal events carry a version number and later events with older versions are ignored.

"How do you prevent a single giant community from dominating hardware?" Shard by community for listings, but replicate the hottest communities' listings and use in-process caches; for comment partitions, the post is the unit, so a giant community's load spreads across many posts.

"How would you add recommendations to the home feed?" Add a candidate source (posts from communities similar to the user's, using co-membership embeddings) and a ranking model blending them with the fan-in results, while keeping diversity caps and a share reserved for joined communities. See ML System Design and Feature Stores.

Key Takeaways#

  • Votes are the dominant write. Use an idempotent "set my vote" API, serialise per user to compute deltas safely, aggregate in batches per item, and keep the voter's own view correct through read-your-writes.
  • Choose ranking formulas whose keys are static per item. Reddit's Hot (log of net votes plus linear submission time) and Wilson-score Best change only when votes change, which makes sorted-set listings and sorted comment trees cheap to maintain.
  • Store comments as an adjacency list partitioned by post, precompute a sorted tree structure per post, and load a budgeted best-first subset with "more" stubs; separate structure from content.
  • Community listings are shared and precomputed in Redis sorted sets capped at about 1,000 items; home feeds are fan-in merges of those listings with normalisation, diversity and a per-user snapshot.
  • Hot threads need layered caching: CDN for logged-out views, shared selection cache, content cache by ID, in-process caches for hot keys, and batched updates to avoid invalidation storms.
  • Moderation is layered (community moderators, admins, automation) with a rule engine, mod queue, mod log and fast propagation of removals.
  • Abuse resistance is a core requirement: trust-weighted votes, vote fuzzing and shadowbans that deny feedback to manipulators, co-vote graph detection, and recounts.
  • An event log is the backbone: writes are short, every derived view is rebuildable, and consistency is chosen per data type.