Design the database for a Q&A site like Quora

Questions, answers, votes, follows and topics. Relational core for writes, a precomputed feed, a search index, and vote counters that may lag.

More on Database design case studies

Keep learning

Overview

Ask a question Title up to 300 characters, optional body, 1 to 5 topics. questions, question_topics Answer a question Comment on an answer Short text, one level of replies. Up or down on an answer, change or remove it. The page shows your own vote and the score. votes, answers.score Users, topics and single questions. follows, followers_of Read a question Question, then the best answers first, then more on scroll. questions, answers Home feed New answers and questions from what you follow, newest and best first. By words in titles and answers, with typos tolerated. search index 100 million users × 2 KB 10 million questions × 1 KB 50 million answers × 2 KB 500 million votes × 0.5 KB 10 million images × 500 KB 5 TB (this one is right) A person. Profile, login, counters. Root of everything a person writes. A subject such as "Databases". Many-to-many with questions. Title, body, author. Belongs to one user, has many answers and topics. Link between a question and a topic. Long text, author, score. Belongs to one question and one user. Its own row, not embedded. Short text under an answer. Who voted what on which target. An edge from a user to a user, topic or question. Self-referencing when the target is a user. Question page with the top 10 answers very high answers (question_id, score DESC, answer_id DESC) Home feed, 20 items, next page by cursor feed_items partition user_id, clustered by rank_ts DESC Vote or un-vote high, bursty votes PK (user_id, target_type, target_id) Topic page, newest questions question_topics (topic_id, created_at DESC, question_id DESC) inverted index in the search engine A user’s answers on their profile answers_by_author (author_id, created_at DESC) Post a question or answer PK insert + UNIQUE (question_id, author_id) Who follows X (for fan-out) internal, high followers_of PK (followee_type, followee_id, follower_id) Users, questions, answers, comments, votes, follows Relational database (PostgreSQL or MySQL) Unique constraints for idempotent votes and one answer per person, transactions for an answer plus its outbox event, secondary indexes for every listed query. The data is a few TB, not hundreds. Full-text search Search engine (Elasticsearch or OpenSearch) Wide-column or key-value store (Cassandra, or Redis for the newest entries) One partition per user, sorted by time, capped at 500 entries, rebuilt from the source tables if lost. Hot pages and counters Cache (Redis or Memcached) Object storage (S3 or similar) behind a CDN Bytes that are written once and never queried. The row stores only the object key. Events between them Log (Kafka) fed by an outbox table The answer row and its event commit in one transaction, so the search index and feed never miss a post. questions, answers, comments, question_topics A user’s answers across questions: kept as answers_by_author on the user shard. votes, follows, feed_items, users "Did I vote?", "who do I follow?" and "my feed" each hit one shard. The score of an answer: summed by the aggregator and written to the question shard. (followee_type, followee_id) Fan-out reads all followers of one account or topic from one shard. A celebrity is a big partition: paged reads, and the hybrid feed avoids reading it per answer. topic_questions (copy of question_topics) The topic page reads one shard. A huge topic is a hot partition: cache its first page. Your own answer after posting Read the author’s requests from the primary for a few seconds, or pass the commit position and wait for a replica that has it. One answer per person per question Strong, enforced by UNIQUE A retried POST hits the constraint and returns the existing answer. Your own vote (the highlighted arrow) Read from votes on your user shard, not from the counter. Score of an answer Eventual, seconds Answer order on the page Eventual, seconds to minutes Search results Indexing consumes the change stream. user_id BIGINT, handle VARCHAR(30), name VARCHAR(100), email VARCHAR(254), password_hash VARCHAR(100), bio TEXT, avatar_key VARCHAR(200), follower_count INT, created_at TIMESTAMP UNIQUE (handle), UNIQUE (email) topic_id BIGINT, slug VARCHAR(80), name VARCHAR(100), follower_count INT, question_count INT UNIQUE (slug) question_id BIGINT, author_id BIGINT, title VARCHAR(300), body TEXT, answer_count INT, status SMALLINT, created_at, updated_at TIMESTAMP (author_id, created_at DESC) question_id BIGINT, topic_id BIGINT, created_at TIMESTAMP (question_id, topic_id) (topic_id, created_at DESC, question_id DESC), copied to topic_questions answer_id BIGINT, question_id BIGINT, author_id BIGINT, body TEXT, score INT, up_count INT, down_count INT, status SMALLINT, created_at, updated_at TIMESTAMP author_id BIGINT, created_at TIMESTAMP, answer_id BIGINT, question_id BIGINT (author_id, created_at DESC, answer_id) comment_id BIGINT, answer_id BIGINT, author_id BIGINT, parent_id BIGINT NULL, body VARCHAR(2000), created_at TIMESTAMP (answer_id, created_at, comment_id) user_id BIGINT, target_type SMALLINT, target_id BIGINT, value SMALLINT (-1, 0, 1), updated_at TIMESTAMP (user_id, target_type, target_id) none on the request path follower_id BIGINT, followee_type SMALLINT, followee_id BIGINT, created_at TIMESTAMP (follower_id, followee_type, followee_id) followee_type SMALLINT, followee_id BIGINT, follower_id BIGINT, created_at TIMESTAMP (followee_type, followee_id, follower_id) feed_items (wide-column) user_id BIGINT, rank_ts TIMESTAMP, item_id BIGINT, item_type, reason capped at 500 per user, TTL 30 days event_id BIGINT, aggregate_id BIGINT, event_type VARCHAR(40), payload JSON, created_at TIMESTAMP deleted after the relay publishes A celebrity answers Hybrid feed: push below a follower threshold, pull above it. Separate queue for big accounts. An answer goes viral Client retries a vote or a post Author reloads right after posting Cache entry of a hot question expires Hundreds of identical queries hit the database at once. Event consumer falls behind Counter drifts from the truth A lost or replayed event leaves score off by a few. A question is deleted Answers, votes, feed rows and index entries live on different shards and stores. One shard gets the big topics Uneven load from a few popular keys. chapters · database design case studies Design the database for a Q&A site like Quora People ask questions, others write long answers, everybody votes, and each person gets a feed built from the topics and people they follow. This chapter designs the data layer for that site with the seven steps from the design framework: what to build, how big it gets, which tables, which queries, which store for which data, how to split it, and how fresh each number must be. Keep questions, answers, votes and follows in a relational database with unique keys that make retries harmless. Treat the score as a derived, batched counter, precompute feeds for most authors and pull them for celebrities, and feed search from an outbox. Shard content by question_id and personal data by user_id. few TB of text, once the units are right 1 row per vote: (user, target) primary key feed entries kept per user shard keys: question_id and user_id One score column that every vote updates, and a feed computed by joining follows on every page load. A celebrity with millions of followers posts an answer. What happens to everyone else’s feed?

Where each kind of data lives

Web / app question page, vote, feed hot question pages, counts Relational DB questions, answers, votes, follows + outbox change events from the outbox Search + feeds OpenSearch, wide-column feed_items outbox relay

1. Requirements: what the database has to do

Functional requirements and the data they need Detail that changes the design Availability over freshness for counts. A score that is 5 seconds old is fine. A lost answer is not. Out of scope here: notifications, messaging, ads, moderation queues, ranking models. They read the same data but add their own stores.

2. Estimation: size and traffic, with the arithmetic shown

The unit slip is easy to make and changes the whole design, so check it on the numbers that commonly appear in write-ups of this problem. Every line is off by a factor of 1,000 except the images: Often written as

4. Access patterns, keys and indexes

List every query with its frequency and latency target, then give each one a path that is a primary-key lookup or an index range that stops at the page size. If a query has no such path, the schema is not done. Access patterns Pick a pattern to see which tables it touches and how many rows it reads. Then remove its key index and compare.

5. A store for each kind of data

One database for everything is the right start. Move a kind of data out only when its access pattern is one the relational store does badly. Data and store

The feed: compute it when writing or when reading?

Fan-out on write copies each new answer into the feed partition of every follower, so reading a feed is one partition scan. Fan-out on read stores nothing extra and, on each feed open, queries the recent items of every account and topic the reader follows, then merges them. Move the follower count up to a celebrity and compare.

6. Partition keys

When one primary is no longer enough, split by the key that keeps each hot query on one shard. There are two families of query here, so there are two keys: content is read by question, personal data is read by user. Shard keys Shard key Cross-shard query and fix

7. Consistency: how fresh each number must be

Consistency per feature The vote counter is where this pays off. Updating answers.score inside every vote request is exact, and it serialises every voter of a popular answer on one row lock. Storing one vote row per user and adding the deltas in batches gives up a few seconds of freshness and removes the contention.

Schema reference

Tables, columns, primary keys and secondary indexes Primary key Secondary indexes

What can go wrong

Failure cases Design answer The score is derived: batch deltas from the event stream, recount nightly to repair drift. Hybrid feed: push to followers below a threshold, pull for big accounts. Consistency per feature: UNIQUE for one answer per person, read-your-writes for the author, seconds behind for counts, feeds and search.

Recap

Answers, comments and votes are rows, not arrays inside a question document. Every access pattern gets a PK lookup or an index range that stops at the page size: (question_id, score DESC, answer_id DESC) for the question page. Feeds are precomputed for most authors and pulled for celebrities. Choose consistency per feature: exact for uniqueness, read-your-writes for the person who acted, seconds behind for counts, feeds and search.

More courses

  • Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
  • Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
  • React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
  • System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
  • NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
  • Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
  • Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
  • AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
  • Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
  • TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
  • CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
  • Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
  • Docker — What an image is, why layers cache, and how containers find each other on a network.
  • Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
  • Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
  • AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
  • Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.