Courses / System Design Interview / Chapter 27
Module 6 · Design Problems I: Video, Q&A and Location · Chapter 27 of 49
Design a Q&A Platform like Quora
Builds on Back-of-the-Envelope Estimates, Databases: Choosing, Replicating and Partitioning, Distributed Caches, Rate Limiters, Distributed Search, Sharded Counters and AI Building Blocks: Inference, Embeddings, Retrieval and Agents. Next up: Design a Maps and Navigation Service like Google Maps.
Part 1 · Requirements and estimates
What the site must do
A question-and-answer site holds millions of questions that people read far more often than they write. This chapter designs one, with the focus on serving pages quickly and ranking answers fairly.
The functional requirements are: a signed-in user posts a question and tags it with topics; other users post answers; users vote answers up or down; every question page lists its answers with the best first; and users find questions by topic or by search. Comments, notifications by email and payment features are left out of scope, so that the design stays about questions, answers and votes.
The non-functional requirements shape the rest. A question page should open in well under a second, even for a question that many people share at once. A vote should be recorded exactly once per user per answer. The page may show a vote count that is a few seconds old, but an answer must never disappear after a user posts it. The site should stay available for reading even when writing is degraded.
| Question to ask | Answer we assume |
|---|---|
| Who can answer? | Any signed-in user, one answer per user per question |
| Is a vote reversible? | Yes: a user can change or withdraw a vote |
| What order do answers appear in? | By quality, not by time |
| How are duplicates handled? | The site suggests similar questions while a user types |
| How is abuse handled? | Automatic checks first, then human moderators |
The third row is the most interesting design question of the chapter, and the fourth gets its own lesson. Both follow from the fact that a question site is only as good as the first answer a reader sees.
Estimating reads and writes
The first estimate is the ratio of reads to writes, because it decides where the design spends effort. All inputs below are assumptions for a mid-size site, chosen to give round numbers: two crore visitors a day, each reading five question pages, one lakh new questions, three lakh new answers and twenty lakh votes.
# All inputs are assumptions for a mid-size site. visitors = 2_00_00_000 # daily visitors pages_each = 5 # question pages read per visitor new_q = 1_00_000 # new questions a day new_a = 3_00_000 # new answers a day votes = 20_00_000 # votes cast a day DAY = 86_400 reads = visitors * pages_each writes = new_q + new_a + votes print(f"reads/day {reads:>12,}") print(f"writes/day {writes:>12,}") print(f"read:write {reads / writes:.0f} : 1") print(f"reads/s {reads / DAY:>9,.0f} average, " f"{3 * reads / DAY:,.0f} at 3x peak") print(f"writes/s {writes / DAY:>9,.0f} average, " f"{3 * writes / DAY:,.0f} at 3x peak") q_bytes, a_bytes, v_bytes = 1_000, 2_000, 40 per_day = new_q * q_bytes + new_a * a_bytes + votes * v_bytes print(f"new data/day {per_day / 1e9:.1f} GB, " f"5 years {per_day * 365 * 5 / 1e12:.1f} TB")
Python 3.12.10. Every input is an assumption.
reads/day 100,000,000 writes/day 2,400,000 read:write 42 : 1 reads/s 1,157 average, 3,472 at 3x peak writes/s 28 average, 83 at 3x peak new data/day 0.8 GB, 5 years 1.4 TB
Output of the estimate.
The site serves ten crore page reads a day against 24 lakh writes, a ratio of about 42 to 1. That is an average of 1,157 reads a second, or 3,472 at three times the average, against 28 writes a second on average. A write rate that low fits a single well-run database. The read rate is also not large, but each page is expensive to build, since it joins a question, its answers, their authors and vote counts, and the same pages are asked for again and again.
The last two lines size the data. With a question at about 1 KB, an answer at about 2 KB and a vote at about 40 bytes, the site adds 0.8 GB a day and 1.4 TB over five years. Even after indexes and copies, this is small next to the video platform in the previous chapter. Text is cheap, and the cost of this system is in reads.
What the numbers decide
Read to write ratio: ≈ 42 : 1 (serve pages from cache; keep writes simple)
Read it as steps
Reads outnumber writes about forty to one, so the design favours reads.
The scene shows the estimate in the order one would say it. The conclusion is not the number itself but the ratio: when reads dominate by this much, the best use of effort is to avoid doing the same read twice, which means caching whole pages. The next lessons build on that.
The estimate also tells us where not to worry. A write rate of about 28 a second does not need partitioned databases on day one. The vote rate, the biggest write source, could grow fast during a popular event, so votes must stay cheap, which is why the data model in the next lesson keeps a running count beside the individual votes.
Why does a 42 to 1 read-to-write ratio push the design toward caching pages?
- The same pages are rebuilt for many readers, and few writes change them. A cached page saves a costly build for each repeated read.
The assumption of five pages per visitor doubles to ten. What changes in the estimate?
- Reads double to 20 crore a day and the ratio doubles to about 83 to 1. Writes and storage are unchanged.
Part 2 · API and data model
The API
The API follows the nouns of the site: questions, answers and votes. Reads are the busy calls, so the page for a question is a single request that returns the question and the first page of its answers in rank order. Writes are small and each acts on one thing.
| Call | What it does | Notes |
|---|---|---|
POST /questions | Creates a question with a title and topics | Returns the new id |
GET /questions/{id} | Returns the question and its top answers | Cached; the hot path |
GET /questions/{id}/answers?after={cursor} | Returns the next page of answers | Cursor, not page number |
POST /questions/{id}/answers | Adds an answer | One per user per question |
PUT /answers/{id}/vote | Sets the caller's vote to 1, -1 or 0 | Repeating it changes nothing |
GET /topics/{name}/questions | Lists recent questions for a topic | A feed over many questions |
Two choices deserve a reason. Votes use PUT with the desired value and not POST to add one, because the request names the final state: sending it twice gives the same result as sending it once, so a retry after a timeout cannot double-count. And answers are paged with a cursor, an opaque token that says where the last page ended, because a page number shifts when new answers arrive and a reader would see repeats.
The tables
Five tables hold everything. A question has an author and a title. An answer belongs to a question. A vote records one user's opinion on one answer, and its primary key is the pair of answer and voter, so a second vote from the same user cannot exist as a separate row. Topics are many-to-many, so a link table connects them to questions.
id (pk)authortitlecreated_atanswer_countid (pk)question_idauthorbodyupdownanswer_id (pk)voter (pk)valueid (pk)namequestion_id (pk)topic_id (pk)- answer question_id → question
- vote answer_id → answer
- question_topic question_id → question
- question_topic topic_id → topic
import sqlite3 db = sqlite3.connect(":memory:") db.executescript(""" CREATE TABLE question ( id INTEGER PRIMARY KEY, author TEXT NOT NULL, title TEXT NOT NULL, created_at TEXT NOT NULL, answer_count INTEGER NOT NULL DEFAULT 0); CREATE TABLE answer ( id INTEGER PRIMARY KEY, question_id INTEGER NOT NULL REFERENCES question(id), author TEXT NOT NULL, body TEXT NOT NULL, up INTEGER NOT NULL DEFAULT 0, down INTEGER NOT NULL DEFAULT 0); CREATE INDEX answer_by_question ON answer (question_id); CREATE TABLE vote ( answer_id INTEGER NOT NULL REFERENCES answer(id), voter TEXT NOT NULL, value INTEGER NOT NULL CHECK (value IN (1, -1)), PRIMARY KEY (answer_id, voter)); CREATE TABLE topic (id INTEGER PRIMARY KEY, name TEXT UNIQUE NOT NULL); CREATE TABLE question_topic ( question_id INTEGER NOT NULL REFERENCES question(id), topic_id INTEGER NOT NULL REFERENCES topic(id), PRIMARY KEY (question_id, topic_id)); CREATE INDEX topic_questions ON question_topic (topic_id, question_id); """)
SQLite stands in for any relational database.
Recording a vote exactly once
The two writes that make a vote, the new vote row and the count update, must succeed or fail together, so the code wraps them in one transaction. The primary key on vote does the duplicate check: a second insert from the same voter raises an integrity error, the transaction rolls back and the count stays correct.
db.execute("INSERT INTO question VALUES" " (1, 'meera', 'How do I learn SQL?', '2026-11-01', 0)") db.execute("INSERT INTO answer (id, question_id, author, body)" " VALUES (10, 1, 'arun', 'Practise on a small database.')") def vote(answer, voter, value): try: with db: db.execute("INSERT INTO vote VALUES (?,?,?)", (answer, voter, value)) col = "up" if value == 1 else "down" db.execute(f"UPDATE answer SET {col} = {col} + 1" " WHERE id = ?", (answer,)) return "counted" except sqlite3.IntegrityError: return "rejected: already voted" print(vote(10, "kiran", 1)) print(vote(10, "kiran", 1)) print(vote(10, "lata", 1)) print(db.execute("SELECT id, up, down FROM answer").fetchall())
Kiran votes twice; the second is rejected.
counted rejected: already voted counted [(10, 2, 0)]
Output of the script.
The first vote by kiran was counted, the second was refused, and lata's vote was counted, so the answer shows two up votes, not three. A real handler would turn the second case into success, since the user's wish, one up vote, is already true. That is what makes the PUT call safe to retry.
Changing a vote from up to down adds one more step: the handler reads the old value, updates the row and adjusts both counters by the difference, still in one transaction.
Why is the vote call a PUT with the desired value and not a POST that adds a vote?
- A PUT names the final state, so repeating it is harmless. A POST that adds one could count twice after a retry.
What stops one user from voting twice on the same answer?
- The primary key on
voteis (answer_id, voter), so a second row for the same pair is rejected, and the transaction rolls back the count update.
Part 3 · High-level design with page caching
The components
The design has few parts because the problem is mostly reading. Web servers are stateless and build pages. A page cache, a shared in-memory store as in the cache chapter, keeps the finished page for each popular question. A primary database takes all writes, and read replicas serve reads that miss the cache. A search index answers topic and keyword queries, and a message queue carries slow work, such as moderation checks, off the request path.
Reads go to the cache first. On a hit, the web server returns the stored page without any query. On a miss, it builds the page from a replica, stores it and returns it. Because a few questions get most of the traffic, even a cache that holds a small share of all pages absorbs most reads, and the replicas see mainly the long tail.
Writes go to the primary. A new answer or vote changes what a page should show, so the write path must also deal with the cached copy. Deleting the cached page when its content changes is called invalidation, and there are two ways to do it: let entries expire on a timer, or delete them when a write happens. The last page of this lesson measures which works better.
One request and one vote
Watch for a popular page being served without touching the database
Read it as steps
A popular page is served from cache; a vote writes to the database and deletes the cached page.
The scene follows the second approach. A hit costs a few milliseconds. A vote reaches the database and deletes the cached page. The next reader pays for a rebuild, which takes tens of milliseconds, and stores the result for the readers after. The millisecond figures in the scene are illustrative, not measured.
Notice the order. The database write comes first and the delete second. If the delete came first, a reader could rebuild the page from the old data between the delete and the write, and the stale page would then be cached. Even with the right order, a reader that started building just before the write can still store an old page afterwards, so very strict freshness needs versions or short expiry as well, as the cache chapter explains.
Expire or invalidate
Which policy is better depends on the workload, so the next script measures it. It creates 2 lakh page views over 1,000 questions, where a few questions are far more popular than the rest, and a vote after every 40 views. A page is stale when it was built before the latest vote on its question. The script compares no cache, a 30 second expiry and invalidation on each vote. Time advances at 1,157 views a second, the average rate from the first lesson.
import random random.seed(7) QUESTIONS = 1000 # a few pages are hot: question r gets weight 1 / (r + 1) weights = [1 / (r + 1) for r in range(QUESTIONS)] VIEWS, VOTE_EVERY, RATE = 200_000, 40, 1157 # views per second events = [] for i in range(VIEWS): q = random.choices(range(QUESTIONS), weights)[0] events.append(("view", q, i / RATE)) if i % VOTE_EVERY == 0: v = random.choices(range(QUESTIONS), weights)[0] events.append(("vote", v, i / RATE))
Python 3.12.10. Seeded random numbers: the same events every run.
def simulate(policy, ttl=30): cache, renders, stale, version = {}, 0, 0, {} for kind, q, t in events: if kind == "vote": version[q] = version.get(q, 0) + 1 if policy == "invalidate": cache.pop(q, None) continue hit = cache.get(q) if policy == "none" or hit is None or ( policy == "ttl" and t - hit[1] >= ttl): renders += 1 cache[q] = (version.get(q, 0), t) elif hit[0] != version.get(q, 0): stale += 1 return renders, stale for p in ("none", "ttl", "invalidate"): r, s = simulate(p) print(f"{p:<10} page renders={r:>7,} stale views={s:>6,}")
Three cache policies over the same events.
none page renders=200,000 stale views= 0 ttl page renders= 5,641 stale views=127,415 invalidate page renders= 5,858 stale views= 0
Counts are exact for this seed.
Without a cache every one of the 2 lakh views builds a page. A 30 second expiry cuts the builds to 5,641 but serves a stale page on 1,27,415 views, about 64 percent, because the popular pages receive a vote every few seconds. Invalidation on each vote needs 5,858 builds, only about 4 percent more, and serves no stale page.
For this workload, invalidation gives freshness at nearly the cost of expiry. The weak spot is a page that is voted on faster than it is read: invalidation then discards pages that nobody asked for. A common remedy is to cache the page body and fetch the vote counts separately, so a vote touches only a small counter.
Part 4 · Deep dive: ranking answers fairly
Why simple scores fail
The order of answers decides what most readers see. Two obvious scores go wrong in opposite directions. Net score, up votes minus down votes, favours answers with many votes even when many of those are against. An answer with 550 up and 450 down, a net of 100, beats one with 90 up and 10 down, a net of 80, although only 55 percent of voters liked the first and 90 percent liked the second.
Average rating, the share of votes that are up, ignores how many votes there are. An answer with two up votes and no down votes has a perfect share of 1.0 and beats an answer with 90 up and 10 down, whose share is 0.9. Two votes say very little about what the next hundred people will think.
What the site needs is a score that is high when the evidence of quality is strong. Evan Miller's article on sorting by average rating makes the case for one tool: the Wilson score interval, a confidence interval for the true share of positive votes. Ranking by its lower end asks, given the votes so far, what is the least the true approval could plausibly be. An answer with few votes has a wide interval and a low bound. One with many votes narrows, and its lower bound rises toward its observed share.
The Wilson lower bound in code
The formula takes the number of up votes, the total, and a value z that sets the confidence. The value 1.96 gives a 95 percent interval. The article shows the formula as an image, so the code below is written out from the standard definition and then checked a second way. The answers are made up: A has two fans, B is well tested, C is popular and divisive, D is small and good, and E has no votes.
from math import sqrt Z = 1.96 # standard normal quantile for a 95% interval def wilson_lower(up, down, z=Z): n = up + down if n == 0: return 0.0 p = up / n centre = p + z * z / (2 * n) spread = z * sqrt(p * (1 - p) / n + z * z / (4 * n * n)) return (centre - spread) / (1 + z * z / n) answers = { # name: (up, down) "A: two fans": (2, 0), "B: well tested": (90, 10), "C: popular, divisive": (550, 450), "D: small and good": (9, 1), "E: unvoted": (0, 0), } print(f"{'answer':<22}{'net':>5}{'share':>8}{'wilson':>8}") for name, (u, d) in answers.items(): share = u / (u + d) if u + d else 0 w = wilson_lower(u, d) print(f"{name:<22}{u - d:>5}{share:>8.2f}{w:>8.3f}")
wilson_lower is the whole algorithm.
answer net share wilson A: two fans 2 1.00 0.342 B: well tested 80 0.90 0.826 C: popular, divisive 100 0.55 0.519 D: small and good 8 0.90 0.596 E: unvoted 0 0.00 0.000
Output, first part: the scores.
for key, label in (("net", "by net"), ("share", "by share"), ("wilson", "by wilson")): f = {"net": lambda u, d: u - d, "share": lambda u, d: u / (u + d) if u + d else 0, "wilson": wilson_lower}[key] order = sorted(answers, key=lambda a: f(*answers[a]), reverse=True) print(f"{label:<10}", [a[0] for a in order])
Sort the same answers by each score.
by net ['C', 'B', 'D', 'A', 'E'] by share ['A', 'B', 'D', 'C', 'E'] by wilson ['B', 'D', 'C', 'A', 'E']
Output, second part: the three orders.
Net score puts C first and A fourth, and share puts A first. The Wilson bound puts B first, because it has both a high share and many votes, then D, whose 9 up and 1 down are enough to be trusted a little, then C, and only then A. Answer A's two up votes earn a bound of 0.342, below D's 0.596, which is how the score punishes thin evidence. An unvoted answer gets 0 and sits last.
Checking the maths and serving the order
A formula copied from an image deserves a check. The Wilson lower bound is the share p at which the observed share just falls inside the 95 percent band, so it solves one equation: the squared gap between the observed share and p equals z squared times p(1-p)/n. The script finds that p by bisection, a method that halves a search range each step, and compares it with the closed form.
# The lower bound is the share p at which the observed share just # falls inside the 95% band: (phat - p)^2 = z^2 * p(1-p)/n. Bisect it. def by_search(up, down): n = up + down phat = up / n lo, hi = 0.0, phat for _ in range(60): mid = (lo + hi) / 2 if (phat - mid) ** 2 > Z * Z * mid * (1 - mid) / n: lo = mid else: hi = mid return lo for u, d in ((2, 0), (90, 10), (9, 1), (550, 450)): print(u, d, f"{wilson_lower(u, d):.6f}", f"{by_search(u, d):.6f}")
Add to the end of the previous script. A search that uses no closed form.
2 0 0.342372 0.342372 90 10 0.825633 0.825633 9 1 0.595844 0.595844 550 450 0.519032 0.519032
The two columns are the formula and the search.
The columns agree to six places for four cases, so the code implements the definition. For serving, the score is computed when a vote arrives and stored in a rank_score column with an index, so a page read only needs the top rows in order.
Ranking by quality alone has a gap: a new answer starts with no votes and sits at the bottom, so no one sees it and it never gets votes. Sites often add a time-decay term or a small boost for new items. An archived Reddit source file shows both ideas: a confidence function that is a Wilson-style lower bound at 80 percent confidence, and a hot function that adds the base-10 log of the score, with its sign, to the post's age in seconds since a fixed date divided by 45,000, so newer posts count for more. It is cited here only as an example of mixing score and time.
Net score ranks an answer with 550 up and 450 down above one with 90 up and 10 down. What is wrong?
- Net score counts volume, not agreement. Only 55 percent of voters liked the first, and 90 percent liked the second.
Why does an answer with 2 up votes and 0 down votes get a low Wilson bound?
Part 5 · Deep dive: duplicate questions
Why duplicates matter
People ask the same thing in different words. If each version collects its own answers, readers see thin pages and good answers are scattered. The site wants to catch duplicates in two places: while the user is typing, to suggest an existing question, and later in the background, so that moderators can merge questions that slipped through.
The task is to measure how similar two questions are. A classic method turns each text into a set of shingles, small overlapping pieces, and compares the sets. A word shingle of size 2 is a pair of neighbouring words. The measure is the Jaccard similarity: the size of the overlap divided by the size of the union. Two identical sets score 1.0 and two disjoint sets score 0.
Before shingling, the text is normalised: lower-cased, stripped of punctuation, and cleaned of very common words such as how and the, which add noise. The code below does this for 20 made-up questions, of which six pairs are intended to be duplicates, and ranks every pair by similarity.
Shingles and Jaccard in code
import re from itertools import combinations QUESTIONS = [ "How do I learn SQL quickly?", "What is the fastest way to learn SQL?", "How can I prepare for a bank clerk exam?", "Which books are good for learning Python?", "What are good books to learn Python?", "How do I lose weight without a gym?", "How to reduce weight at home without going to a gym?", "What is the capital of Australia?", "Why is the sky blue?", "How do I start investing in mutual funds?", "How should I begin investing in mutual funds?", "Which city is best for a software job in India?", "How do I make soft chapatis?", "What makes chapatis soft?", "Can I learn guitar on my own?", "How long does a passport take to arrive?", "How do I change my name on a passport?", "What is a good phone for coding?", "Which phone should I buy for programming?", "How many hours should I study each day?", ]
Twenty invented questions, Q1 to Q20 in order.
STOP = {"a", "the", "is", "of", "to", "do", "i", "how", "what", "can"}
def shingles(text, k=2):
words = [w for w in re.findall(r"[a-z]+", text.lower())
if w not in STOP]
return {" ".join(words[i:i + k]) for i in range(len(words) - k + 1)}
def jaccard(a, b):
return len(a & b) / len(a | b) if a | b else 0.0
sets = [shingles(q) for q in QUESTIONS]
scored = sorted(((jaccard(sets[i], sets[j]), i, j)
for i, j in combinations(range(len(sets)), 2)),
reverse=True)
print("pairs compared:", len(scored))
for s, i, j in scored[:8]:
print(f"{s:.2f} Q{i + 1} and Q{j + 1}")Python 3.12.10. Normalise, shingle, compare all pairs.
pairs compared: 190 0.50 Q10 and Q11 0.25 Q1 and Q2 0.11 Q4 and Q5 0.00 Q19 and Q20 0.00 Q18 and Q20 0.00 Q18 and Q19 0.00 Q17 and Q20 0.00 Q17 and Q19
The eight highest-scoring pairs of 190.
The program compared 190 pairs, which is 20 choose 2. Only one real duplicate scored well: Q10 and Q11, the two questions about starting to invest in mutual funds, with a similarity of 0.50. The pair Q1 and Q2 about learning SQL quickly scored 0.25, and the two questions on books for learning Python scored 0.11. The three intended pairs about weight loss, chapatis and phones scored 0.00, the same as unrelated questions.
All six are true duplicates, and the method found three. Shingles measure shared words, and people who ask the same thing often choose different words. After the top three, every pair scores 0.00, so no threshold can separate the other three duplicates from unrelated questions.
What shingles catch and what they miss
Shingles are good at copies with small changes, such as typos, reordering and extra words. To show that, the next script compares a question with a misspelled copy of itself. The word shingles share nothing, since each pair of neighbouring words contains a misspelled word, but character shingles of size 3 still overlap. The lines are added to the end of the previous script.
def char_grams(text, k=3): s = re.sub(r"[^a-z ]", "", text.lower()) return {s[i:i + k] for i in range(len(s) - k + 1)} a = "How do I learn SQL quickly?" b = "how do i lern sql quikly??" print("word pairs :", round(jaccard(shingles(a), shingles(b)), 2)) print("char 3-gram:", round(jaccard(char_grams(a), char_grams(b)), 2))
Word pairs against character 3-grams.
word pairs : 0.0 char 3-gram: 0.64
Character pieces survive the typos. Only the two new lines are shown.
Word shingles scored 0.0 and character 3-grams 0.64, so the choice of shingle should match the kind of duplicate. Paraphrases are harder: no amount of shingling connects reduce weight at home to lose weight without a gym. For those the site needs embeddings, vectors from a model in which texts with similar meaning lie close together, with a nearest-neighbour search, as described in the ai building blocks chapter.
Scale is the other limit. Comparing all pairs grows with the square of the number of questions, so crores of questions cannot be compared that way. A site narrows the work first: only compare questions that share a topic or a rare term from the search index (the search chapter), or use hashing schemes such as MinHash with locality-sensitive hashing, which put similar sets in the same bucket. Neither is built here. The suggestion box at typing time can use the search index directly and the embedding method only for the closest few hits.
Whatever finds the pair, the merge itself is a data change worth planning. The duplicate is turned into a redirect to the question that is kept, its answers move across, and its votes move with them. The vote table's primary key then needs care: a voter who voted on answers in both questions must not end up with two rows for the same answer, so the merge keeps one row per pair.
In the run, which genuine duplicate pair scored highest and what was its similarity?
Part 6 · Moderation, scaling the database and failures
Moderation
Any site where strangers post will receive spam and abuse, so a moderation path is part of the design. The rule that keeps it cheap is to check content asynchronously: the write is accepted and stored in a pending state, a job goes to the message queue, and workers run automatic checks, such as links to known bad domains, repeated text and abuse words. Content that passes becomes visible. Content that fails is hidden, and content in the grey zone goes to a human queue.
| State | Visible to readers | How it is reached |
|---|---|---|
| pending | Only to its author | A new post, before any check |
| visible | Everyone | Automatic checks passed, or a moderator approved |
| hidden | No one but moderators | Automatic checks failed or a moderator removed it |
| under review | Only to its author | A check was unsure and a person must decide |
Two more controls limit abuse at the edge. A rate limiter, covered in the rate limiter chapter, caps how many questions, answers and votes one account can post per minute. And new accounts can start with tighter limits that relax as the account earns a record. Voting needs extra care, because a ring of accounts voting for each other would distort the ranking from the ranking lesson. Counting only votes from accounts with some history, and watching for sudden bursts on one answer, are typical defences.
Scaling the database
At the estimated 28 writes a second one primary is enough, and the first scaling step is read replicas behind the cache, as in the high-level design. Replicas lag a little behind the primary, so a user who has just posted an answer should read their own answer from the primary, or the page should add it from the response, to avoid the answer seeming to vanish.
When one primary can no longer take the writes or hold the data, the next step is sharding, splitting the rows across several databases. The natural key is the question id, because everything a question page needs, its answers and their votes, can then live in one shard, and a page read touches one database. The script shows how evenly a hash of the question id spreads 1 lakh questions and 3 lakh answers over four shards.
import random, zlib from collections import Counter random.seed(3) SHARDS = 4 def shard_of(question_id): return zlib.crc32(str(question_id).encode()) % SHARDS questions = range(1, 100_001) # each answer belongs to a question id answers = [random.randrange(1, 100_001) for _ in range(300_000)] print("questions per shard:", sorted(Counter(shard_of(q) for q in questions).items())) print("answers per shard: ", sorted(Counter(shard_of(q) for q in answers).items())) # One question page: its question, answers and votes share one shard. print("page for question 42 reads shard", shard_of(42)) # A topic feed lists questions from many ids, so it asks every shard. topic_questions = random.sample(list(questions), 20) print("topic feed of 20 questions touches shards", sorted({shard_of(q) for q in topic_questions}))
A stable hash (CRC-32) of the question id picks the shard.
questions per shard: [(0, 24999), (1, 25000), (2, 24999), (3, 25002)] answers per shard: [(0, 75171), (1, 74920), (2, 75051), (3, 74858)] page for question 42 reads shard 0 topic feed of 20 questions touches shards [0, 1, 2, 3]
Seeded, so the counts repeat.
Each shard holds about 25,000 questions and about 75,000 answers, so hashing spreads the load evenly. A question page reads one shard. A topic feed lists questions with unrelated ids and so touches all four, and that is the cost of the choice. The usual answer is to serve topic feeds from the search index or from a separate store built for lists, and keep the shards for the question pages themselves.
Failures and extensions
| Failure | Effect | Response |
|---|---|---|
| A cache node is lost | Many pages miss at once | Replicas absorb the load; a stampede guard lets only one request rebuild each page |
| A replica lags | A recent answer is missing | The author reads from the primary |
| The primary fails | Writes stop | Promote a replica; reads continue from cache |
| The moderation queue backs up | New posts stay pending | Show them to their author and add workers |
| A question goes viral | One page gets all the traffic | The page cache serves it; the vote counter can be sharded, as in the sharded counter chapter |
The system degrades gracefully because reading is separate from writing. If writes fail, the site can still serve every cached page and show a notice. If the cache is lost, the replicas can carry the traffic for a short time, as long as rebuilds are limited to one per page at a time.
The same design extends in a few directions. Notifications to the author when an answer arrives are another consumer of the queue. Following topics is a feed built from the topic table. Better duplicate detection swaps the similarity function. Paid or expert answers add a state and a payment step, which is outside this chapter.
Why are posts checked after they are accepted and not before?
- Checking in the request would slow every write and fail when a checker is down. Storing as pending and checking via a queue keeps writes fast.
All chapters · Previous: Design a Video Platform like YouTube