Reddit Clone Database Schema database schema
The Reddit Clone Database Schema database schema by Colton Bristow has 108 tables (users, user_profiles, user_preferences, user_sessions and 104 more), 890 columns and 201 relationships, documented column by column.
- Tables
- 108
- Columns
- 890
- Relationships
- 201
- Enums
- 61
Tables (108)
| Table | Columns | Description |
|---|---|---|
| users | 20 | The auth row. The four karma columns are rebuildable caches over karma_events, split the way Reddit splits them because post, comment, given-award and received-award karma are earned under different rules. email is nullable because a throwaway account is a first-class citizen. deleted_at keeps the row so old posts still resolve an author id even after the person leaves. |
| user_profiles | 12 | Split one-to-one from users because a profile is read on every hover card and written far more often than credentials. profile_subreddit_id is the trick that makes u/name work: a profile IS a subreddit with is_profile_subreddit set, so profile posts reuse the whole posting and moderation stack rather than needing a parallel one. |
| user_preferences | 13 | default_sort is why sort_order is an enum rather than a query string constant: the chosen listing order is persisted state, not a UI detail. Every column here is read on the first render of every page, which is why it is a narrow table split away from the profile. |
| user_sessions | 9 | Only the hash of the token is stored. Revocation is a timestamp rather than a delete, so a forced logout leaves evidence and the session list can show what was ended and when. |
| user_devices | 8 | A device outlives a session, which is why push tokens hang here and not on user_sessions. Logging out must not silently stop notifications on a device the person still owns. |
| push_subscriptions | 4 | Push preference is per device per type, because a person reasonably wants reply pings on their phone and nothing on their desktop. |
| user_blocks | 3 | A block hides content in both directions at read time. It is deliberately NOT a mute and NOT a ban: it is personal, reversible, and never removes anything from the database. |
| user_follows | 3 | Profile follows. Critically this does NOT drive the home feed - it only surfaces a persons profile posts. Wiring the home listing to this table is how a Reddit clone accidentally turns into Twitter. |
| mfa_devices | 8 | confirmed_at null means enrolment started but was never completed, so it must not be accepted at login. That distinction is what stops a half-finished setup locking someone out. |
| recovery_codes | 4 | One row per single-use code. Used is a timestamp, never a delete, so support can see that a code was burned rather than guess. |
| password_resets | 7 | |
| email_change_requests | 6 | The new address lives here until it is confirmed and only then moves to users.email. Writing it straight onto the account is how people lock themselves out with a typo. |
| username_history | 6 | Indexed on old_username so an abandoned handle cannot be re-registered and used to impersonate its previous owner. |
| oauth_applications | 10 | client_secret_hash is nullable because an installed app cannot keep a secret and must use PKCE instead. Modelling that as a nullable column rather than pretending every client is confidential is the whole point of app_type. |
| oauth_access_tokens | 9 | user_id null is an application-only token with no human behind it, which is exactly the case rate limiting has to treat differently. |
| trophies | 6 | The catalog of awardable trophies. Criteria live in application code; this table only names the award and says whether a human grants it. |
| user_trophies | 5 | subreddit_id is part of the key because a community trophy can be earned once per community, while a site trophy is earned once overall with a null there. |
| avatar_assets | 8 | The avatar wardrobe. slot is what stops two hats being worn at once, and it is an enum because the render pipeline has a fixed layer order. |
| user_avatar_items | 4 | Ownership and outfit in one row. Uniqueness of the equipped item per slot is enforced by a partial index in the real deployment, not by a column here. |
| subreddits | 36 | name is the string after r/ and is unique site-wide, which is why it is the natural key humans quote while the uuid is what foreign keys use. is_profile_subreddit is the column that lets u/name reuse the entire post, comment and moderation stack instead of duplicating it. comment_score_hide_minutes is a real anti-pile-on tool: it hides scores for the first N minutes so early votes cannot anchor later ones. |
| subreddit_subscriptions | 4 | THE feed table. Home is a ranked union over the subreddits in this table, computed at read time. There is no feed_entries fan-out anywhere in this schema, and that is the deliberate difference from a follow-graph social network. |
| subreddit_moderators | 14 | Permissions are columns, not an enum, because a moderator holds a SET of them. accepted_at null means the invite is still pending, so an invite and an appointment are the same row at two points in its life. position drives mod list order and therefore seniority in every escalation rule. |
| subreddit_rules | 8 | Rules are rows so a report can cite one by id. reports.rule_id pointing here is what makes a subreddit report queue different from a site-wide one. |
| subreddit_bans | 12 | A ban is a row with an expiry, never a boolean. expires_at null is permanent, lifted_at records an early unban, and both together mean the sanction history survives an appeal. mod_note is private to moderators; message_to_user is what the person actually receives. |
| subreddit_mutes | 7 | A mute stops modmail only and leaves posting alone, which is why it cannot be a flag on the ban row. Conflating the two is how mod teams accidentally silence someone they only meant to stop arguing with. |
| subreddit_approved_users | 4 | The allow-list that makes a restricted or private community usable. It is also the AutoMod escape hatch: approved users bypass the age and karma gates. |
| flairs | 11 | Flair is a row scoped to one subreddit, not free text on the post. That is what lets a community offer a fixed set, mark some mod-only, and rename one everywhere at once. |
| user_flairs | 6 | Flair is per community: the same person is a different thing in r/rust and r/cooking. text_override exists because many subs let a member edit the label while keeping the template styling. |
| subreddit_emojis | 7 | |
| subreddit_widgets | 7 | Sidebar widgets are rows with a JSON body rather than a table per widget type. The shape varies per kind and is validated in application code, which is the honest trade when the catalog of kinds changes faster than migrations ship. |
| subreddit_styles | 7 | |
| topics | 5 | The site-wide interest taxonomy behind discovery and ad targeting. Self-referencing so Gaming can hold Strategy Games without a second table. |
| subreddit_topics | 3 | |
| related_subreddits | 5 | Both moderator-curated and algorithmic neighbours in one table, distinguished by source, so the sidebar and the recommender can read the same rows without arguing about precedence. |
| multireddits | 8 | The feature every Reddit clone forgets. A multireddit is a named bag of subreddits that produces its own listing, which is trivial to model precisely because the feed is computed rather than materialised. |
| multireddit_subreddits | 3 | |
| wiki_pages | 9 | Wiki content is versioned through content_revisions like every other body of text in this schema, rather than getting a bespoke history table of its own. |
| wiki_page_editors | 4 | Per-page editor grants, which is what wiki_permission alone cannot express: a sub can lock the wiki generally and still open one page to two people. |
| subreddit_traffic_daily | 8 | Pre-aggregated per community per day. The mod traffic page is a range scan over this, never a count over posts and comments. |
| posts | 41 | The five score columns are the whole ranking design: each Reddit sort is a DIFFERENT function of the same votes, so each gets its own indexed column written when a vote lands. (subreddit_id, is_stickied, hot_score) IS the front page query. removed_at is a moderator and deleted_at is the author, which is exactly the difference between [removed] and [deleted] - collapsing them is the most common mistake in a Reddit clone. is_contest_mode randomises comment order and hides scores, which is why it belongs on the post rather than in a setting. author_id is nullable so a deleted account leaves the post standing. |
| post_media | 6 | One row per gallery item, pointing at a reusable asset rather than a URL, so the same upload can be crossposted without being re-encoded. |
| media_assets | 14 | The upload registry, deliberately separate from anything that references it. checksum is indexed so an identical re-upload deduplicates, and status exists because a video is referenced by a post long before transcoding finishes. |
| link_previews | 10 | The oEmbed and OpenGraph cache, keyed by a hash of the URL because the URL itself is too long to index. Two thousand posts linking the same article fetch it once. |
| comments | 24 | tree_path is the materialised ancestry, so an entire thread is ONE prefix range query on (post_id, tree_path) rather than a recursive CTE per expand. parent_id is kept alongside it because the path alone cannot be enforced by a foreign key. best_score is the Wilson lower bound, which is why a comment with 9 of 10 upvotes outranks one with 1 of 1. is_collapsed is written by crowd control rather than recomputed per viewer. |
| content_revisions | 8 | Append-only edit history shared by posts, comments and wiki pages. The polymorphic pair is deliberate: three near-identical history tables would be worse, and nothing cascades from here anyway. |
| drafts | 12 | A draft is not an unpublished post. It carries no scores, no counters and no subreddit requirement, which is why it is its own table rather than a status on posts. |
| scheduled_posts | 10 | The index on (status, scheduled_for) IS the scheduler: one range scan finds everything due. recurrence lets a mod team post a weekly thread without a cron job per community. |
| collections | 8 | A moderator-curated series, which is how an event or an AMA week is presented as one thing. Posts keep their own identity and simply carry collection_id. |
| collection_posts | 3 | |
| polls | 5 | Keyed by post_id because a poll is not a separate object, it is a property of one post. ends_at is the only state a poll needs - open versus closed is a comparison, not a status column that can drift out of sync with the clock. |
| poll_options | 5 | |
| poll_votes | 3 | Separate from post_votes because a poll choice is not an upvote and must never touch karma. vote_count on poll_options is the cache over this table. |
| mentions | 6 | Mentions are extracted once at write time, so the mentions tab is an index lookup instead of a text scan across every comment ever written. |
| saved_items | 5 | A join table rather than a flag, so saving survives the post being removed and the saved tab can still show that something was there. |
| hidden_posts | 3 | Hide is per user and filters at read time during feed assembly. It is the cheapest personalisation signal in the product and costs one anti-join. |
| post_votes | 5 | value is +1 or -1 under a check constraint. The composite key makes a vote idempotent, so changing your mind is an UPDATE and un-voting is a DELETE rather than an accumulating pile of rows. Every count on posts is rebuildable from here. |
| comment_votes | 5 | Kept separate from post_votes rather than unified behind a content_type column, because these two are the hottest write path in the product and each deserves its own index and its own partitioning story. |
| karma_events | 8 | The append-only ledger behind every karma column on users. Keeping the subreddit on each row is what makes per-community karma and karma-gated posting possible without a second aggregation. Nothing here is ever updated. |
| subreddit_karma | 5 | A rollup of karma_events per community, kept because AutoMod checks it on every single submission and a live aggregate there would be the slowest thing on the site. |
| post_rankings | 6 | Precomputed listing slices for the expensive combinations - top of the year, all time, and r/all - refreshed on a schedule. subreddit_id null IS the site-wide front page. Cheap sorts read the score columns on posts directly and never touch this table. |
| trending_subreddits | 5 | A daily snapshot rather than a live computation, so the trending list is stable for everyone who loads the page on the same day. |
| post_views | 4 | Pre-aggregated per post per day, not one row per hit. Raw impression logs belong in an analytics pipeline, never in the table the site reads on every page load. |
| post_insights_daily | 7 | What the author sees on their own post. Kept apart from post_views because these are product analytics with a retention policy, while view counts are a permanent display number. |
| vote_anomalies | 8 | Vote manipulation detection output. It is a table and not a boolean because the interesting question is always WHICH signal fired and how strongly, and because a false positive has to be reviewable. |
| awards | 11 | The catalog of purchasable awards. subreddit_id set means a community award, null means site-wide. is_active retires an award without deleting it, so old gifts still render. |
| award_gifts | 10 | One row per gift, never a counter on the post, so the award strip can be rebuilt and a refund is one delete. is_anonymous is a display flag - the giver is still recorded, because an abusive award message has to be traceable. |
| coin_balances | 6 | A cached running total. The truth is coin_transactions, and this row can always be rebuilt by summing it. users.coin_balance mirrors this again for the header badge, because that number is read on literally every page. |
| coin_transactions | 8 | The append-only coin ledger with a signed delta, the same shape as karma_events and stock movements. balance_after is stored so a statement can be rendered without re-summing the whole history, and a mismatch between it and the running sum is the alarm that something wrote out of band. |
| premium_subscriptions | 10 | source records whether premium was bought, gifted or granted by an award, which matters because only a purchased subscription can be refunded and only a recurring one can be cancelled. |
| orders | 11 | Money in minor units as an integer beside an explicit currency. Never floats. A refund is a new row referencing the original, never a mutation of it. |
| order_items | 6 | sku and description are copied rather than joined live, so renaming a coin pack next year cannot rewrite what an old receipt says was bought. |
| payment_methods | 10 | Display fragments only. The card itself lives with the processor and this row holds a token, which is the difference between a schema you can run and one that drags PCI scope across the whole database. |
| reports | 14 | rule_id set means the report cites a subreddit rule and lands in that communitys queue; null with a site reason means it escalates to admins. That one nullable column is the entire two-tier moderation model. (subreddit_id, status, created_at) IS the mod queue. |
| report_reasons | 6 | Custom report reasons per community, sitting alongside the fixed report_reason enum. The enum is the site vocabulary that admins depend on; these rows are what a community writes for itself. |
| removal_reasons | 5 | Canned removal messages. posts.removal_reason_id points here rather than storing free text, so a community can fix the wording of a rule explanation once and every past removal reads correctly. |
| mod_actions | 12 | The public moderation log, append-only. is_automated with a null moderator_id and an automod_rule_id is how a machine action is recorded, so a community can see exactly how much of its moderation is automated and which rule did it. Every removal, lock, sticky, ban and flair change lands here, which means moderator activity is itself reviewable. |
| mod_notes | 9 | Private per-user notes a mod team keeps on someone, with an optional label that shows as a badge next to their name. This is the institutional memory that stops a team re-litigating the same person every six months, and it is deliberately invisible to the user. |
| automod_rules | 15 | AutoMod rules are DATA, not code. A community changes its own filtering without a deploy, rules evaluate in priority order, and match_count tells moderators which rule is actually doing the work and which one has never fired once. |
| automod_matches | 7 | Every firing, kept so a rule can be tuned against real traffic instead of guesses. matched_value is what actually tripped it, which is the single most useful thing when a rule is catching the wrong thing. |
| crowd_control_settings | 9 | Crowd control collapses rather than removes, which is why comments.is_collapsed exists as stored state. The whole point is to dampen a brigade without giving a moderator a thousand things to review. |
| banned_domains | 6 | subreddit_id null is a site-wide domain ban. posts.domain is denormalised precisely so this check is an index lookup rather than a URL parse on every submission. |
| site_suspensions | 10 | Site-wide sanction, deliberately a different table from subreddit_bans: they are issued by different people, appealed to different people, and have different consequences. is_shadowban means the account still posts and simply is not shown to anyone else, which cannot be modelled as a status alone because the user must not be told. |
| ban_appeals | 10 | Exactly one of the two sanction columns is set, enforced by a check. Keeping appeals in their own table is what lets an overturned ban leave both the original row and the reversal in the record. |
| admin_actions | 7 | Site staff actions, kept apart from mod_actions because quarantining a community or removing a moderator is not a moderation event inside that community and must not appear in its public log. |
| notifications | 10 | The orange envelope. Replies, mentions, award receipts, mod invites and ban notices all land here so the inbox is one query. read_at null IS the unread count, which is why it is indexed rather than being a boolean. |
| notification_settings | 5 | One row per user per notification type with a column per channel. A missing row means the product default, which is what stops adding a new notification type requiring a backfill across every account. |
| messages | 9 | Private messages between two people, threaded by parent_id. Kept apart from modmail because a message to a person and a message to a moderator team are different objects with different read semantics. |
| modmail_conversations | 10 | Modmail is a conversation addressed to a TEAM, which is why it has its own table with an assignee and a state rather than being a message with many recipients. is_internal marks a mod-only discussion thread the participant never sees. |
| modmail_messages | 7 | is_private_note is a mod-only annotation inside an otherwise visible thread, and is_author_hidden is how a team replies as the subreddit rather than as a named person. Both are visibility rules that must live on the message, not the conversation. |
| chat_channels | 10 | One table for direct chats, group chats, community channels and mod team rooms, distinguished by kind. They differ only in who may join, which is membership, not structure. |
| chat_channel_members | 6 | last_read_message_id is a high-water mark, not a row per message read. Unread count is a cheap range query above it, which is the only way a chat badge stays fast. |
| chat_messages | 9 | |
| chat_reactions | 4 | |
| live_threads | 9 | A running event feed that is deliberately not a post: updates arrive faster than voting makes sense, so there are no scores here at all. |
| live_thread_updates | 6 | is_stricken rather than a delete, because retracting an update during a breaking event must leave the correction visible. |
| live_thread_contributors | 5 | |
| search_queries | 8 | clicked_position is the relevance feedback signal: a search with results and no click is the one worth investigating. |
| saved_searches | 8 | |
| advertisers | 7 | |
| ad_campaigns | 12 | Budget and bid in minor units as integers. The pacing job reads (status, starts_at) and nothing else, which is why that index exists. |
| ads | 9 | A promoted post is a real posts row with is_promoted set, which is what lets it be voted on, commented on and reported through exactly the same machinery as organic content. |
| ad_targeting_rules | 5 | Include and exclude rules in one table with an operator, because targeting is always a set expression and splitting it into two tables makes evaluation order ambiguous. |
| ad_metrics_daily | 6 | Pre-aggregated daily, like every other counting table here. Per-impression rows belong in the event pipeline, not in the database the dashboard queries. |
| experiments | 7 | |
| experiment_assignments | 4 | Assignment is stored rather than hashed on the fly, so a rollout change mid-experiment cannot silently move somebody between variants and poison the result. |
| feature_flags | 7 | |
| audit_logs | 10 | Append-only and write-once, capturing before and after values. This is the table an auditor actually asks for, and it is deliberately separate from mod_actions and admin_actions, which are product surfaces rather than a compliance record. |
| api_rate_limits | 6 | A fixed-window counter keyed by whoever is being limited - a user, an OAuth application or a bare IP. principal_id is a varchar rather than a uuid precisely because an IP is a legitimate principal. |
Enums (61)
- account_status
- active, suspended, shadowbanned, deactivated, deleted
- theme_preference
- system, light, dark
- device_platform
- ios, android, web, desktop
- mfa_kind
- totp, sms, webauthn
- oauth_app_type
- web, installed, script
- avatar_slot
- body, hair, face, top, bottom, shoes, hat, accessory, background
- avatar_rarity
- common, uncommon, rare, epic, legendary
- subreddit_type
- public, restricted, private, gold_only, employees_only
- submission_type
- any, links_only, text_only
- wiki_permission
- disabled, mods_only, approved_contributors, anyone
- rule_scope
- posts_and_comments, posts_only, comments_only
- flair_type
- post, user
- flair_content
- text_only, emoji_only, text_and_emoji
- widget_kind
- text_area, image, button, calendar, rules, community_list, moderator_list, subscribe, post_flair_filter, custom
- relation_source
- algorithmic, moderator_curated
- post_kind
- link, self, image, video, gallery, poll, crosspost
- media_kind
- image, gif, video, audio, embed
- media_status
- uploading, processing, ready, failed, quarantined
- content_type
- post, comment, wiki_page, message, chat_message, live_update
- distinguish_kind
- moderator, admin, special
- collection_layout
- timeline, gallery
- recurrence_kind
- none, daily, weekly, monthly
- schedule_status
- scheduled, published, failed, canceled
- sort_order
- hot, new, top, best, rising, controversial, qa
- time_window
- hour, day, week, month, year, all
- karma_source
- post_vote, comment_vote, award_received, award_given, manual_adjustment
- trending_source
- algorithmic, editorial
- vote_signal
- rapid_voting, brigade_pattern, new_account_cluster, ip_overlap, reciprocal_voting
- award_tier
- silver, gold, platinum, community, premium
- coin_transaction_kind
- purchase, award_given, award_received, premium_grant, promotional_grant, refund, adjustment
- premium_plan
- monthly, annual, lifetime
- premium_source
- purchased, gifted, award_grant, employee
- subscription_status
- active, past_due, canceled, expired
- order_kind
- coins, premium, premium_gift, avatar_item
- order_status
- pending, paid, failed, refunded, disputed
- report_reason
- spam, harassment, hate, violence, sexualisation_of_minors, misinformation, copyright, personal_information, self_harm, impersonation, vote_manipulation, breaks_subreddit_rule, other
- report_status
- open, reviewing, actioned, dismissed, escalated
- mod_action_type
- remove_content, approve_content, spam_content, lock_content, unlock_content, sticky_content, unsticky_content, distinguish_content, mark_nsfw, mark_spoiler, set_flair, ban_user, unban_user, mute_user, unmute_user, add_approved_user, remove_approved_user, invite_moderator, accept_moderator_invite, remove_moderator, edit_rules, edit_automod, edit_settings, edit_wiki
- mod_note_label
- bot_ban, permanent_ban, ban, abuse_warning, spam_warning, spam_watch, solid_contributor, good_contributor, helpful_user
- automod_field
- post_title, post_body, post_url, post_domain, post_flair, comment_body, author_name, author_account_age, author_total_karma, author_subreddit_karma
- automod_operator
- contains, not_contains, matches_regex, equals, starts_with, less_than, greater_than
- automod_action
- remove, filter, report, approve, set_flair, reply_with_comment, lock
- crowd_control_level
- off, lenient, moderate, strict
- suspension_type
- temporary, permanent
- appeal_status
- submitted, reviewing, upheld, overturned, expired
- admin_action_type
- quarantine_subreddit, unquarantine_subreddit, ban_subreddit, suspend_user, unsuspend_user, remove_moderator, grant_subreddit, takedown_content, restore_content
- actor_type
- user, moderator, admin, automod, system
- notification_type
- post_reply, comment_reply, username_mention, post_upvote_milestone, award_received, new_follower, mod_invite, ban_notice, modmail_reply, chat_message, scheduled_post_published, trending_post
- modmail_state
- new, in_progress, archived, filtered, appeal
- chat_channel_kind
- direct, group, subreddit, mod_team
- chat_member_role
- owner, moderator, member
- live_thread_state
- live, complete, archived
- search_scope
- site, subreddit, user, comments
- advertiser_status
- pending, active, suspended, closed
- ad_objective
- impressions, clicks, conversions, video_views
- ad_bid_type
- cpm, cpc, cpv
- ad_status
- draft, pending_review, approved, running, paused, rejected, completed
- targeting_dimension
- subreddit, topic, location, device, language, custom_audience
- targeting_operator
- include, exclude
- experiment_status
- draft, running, paused, completed, abandoned
- principal_type
- user, oauth_application, ip_address
Document your own schema
This page is published from DB Planner, a collaborative ER diagram tool. Write the schema in the DBML editor or import it from SQL, then publish docs like these from the project's sharing settings.