The Problem#
Design a question-and-answer site like Stack Overflow. Users ask questions with a title, a body and tags (python, sql, regex). Other users write answers, and anyone can add short comments to either. Users vote questions and answers up or down; the asker can accept one answer. Votes earn reputation, which unlocks privileges (voting down, editing others' posts, closing questions). Badges reward behaviour. The community, with elected moderators, closes off-topic questions and marks duplicates. Most visitors arrive from a web search, read one question page, and leave.
Stack Overflow was launched in 2008 by Jeff Atwood and Joel Spolsky and grew into the Stack Exchange network of Q&A sites. It is famous in system design circles for an unusual reason: for many years it served one of the busiest websites in the world from a small number of large, well-tuned servers running a monolithic application, rather than hundreds of microservices. Its engineers (notably Nick Craver, in a 2016 blog series on the site's architecture and hardware) published details, so this case study can discuss a real, documented example of scaling up alongside the usual scale-out options.
What makes the problem interesting:
- Extremely read-heavy, mostly anonymous traffic. The great majority of page views are logged-out readers from search engines. Their pages are the same for everyone and can be cached aggressively.
- Long-lived content. Unlike a news feed, a question from 2010 can still be one of the most-read pages today. The archive is the product, which affects storage, caching and search.
- Reputation is a ledger. Votes, accepts, bounties and reversals change reputation, which gates permissions; it must be correct and auditable, and resist fraud.
- Tags are the navigation system. Users browse, filter, watch and ignore by tags, with queries like "questions tagged
javabut notandroid, sorted by newest". - Duplicates are a quality problem. The same question is asked thousands of times; the site wants one canonical answer and quick detection of duplicates, ideally before the question is posted.
- Community moderation at scale. Privileged users, review queues, flags and elected moderators keep quality high.
Analogy. Stack Overflow is like a huge public library of solved problems with a help desk attached. Visitors (readers) walk in, look up the problem they have, read the answer card, and leave; the library keeps copies of the most-requested cards at the front desk (caching). Some visitors bring a new problem to the help desk (asking), and volunteer experts write answer cards (answering). Readers put gold stars on the best cards (votes), and experts earn library standing (reputation) that lets them reshelve, relabel and repair cards (privileges). Librarians label each card with topic stickers (tags) and staple duplicate requests to the original card (duplicate closing). A few head librarians (moderators), elected by the regulars, handle disputes.
Background: a few terms used in this design#
- Post: a question or an answer. Both have a body, a score, an author and an edit history.
- Comment: a short remark on a post, with limited formatting and lighter voting (upvotes only).
- Accepted answer: the answer the asker marked as solving their problem.
- Reputation (rep): points earned from votes and accepts; it unlocks privileges.
- Privilege: an action allowed at a reputation threshold (for example comment everywhere, downvote, edit, vote to close).
- Tag: a keyword label on a question; questions have one to five tags. Tag synonyms map alternative names to a master tag.
- Close / duplicate: a question can be closed (no new answers) as off-topic, unclear, or as a duplicate of an existing question, which then links readers to the canonical one.
- Bounty: reputation offered by a user to attract answers to a question.
- Badge: an award for specific behaviour (bronze, silver, gold).
- Review queue: a list of items (first posts, suggested edits, close votes) for privileged users to review.
- Scale up vs scale out: making one machine bigger versus adding more machines. See Vertical vs Horizontal Scaling and Stateless Design.
Clarifying Questions#
| Question | Assumption for this design |
|---|---|
| Which features are in scope? | Questions, answers, comments, votes, accept, reputation and privileges, tags, search, duplicate detection, badges, moderation. |
| Out of scope? | Jobs, ads, teams/private instances, chat, AI answer features (mentioned only as extensions). |
| Scale? | About 100 million monthly visitors, tens of millions of questions in the archive, a few thousand new questions a day. |
| Traffic mix? | The large majority of page views are anonymous readers from search engines; a small fraction of users write. |
| Latency target? | Question pages render on the server in tens of milliseconds; full page under 1 second for readers worldwide. |
| How fresh must votes and new answers appear? | Seconds for the author and active viewers; minutes is acceptable for anonymous cached pages. |
| How accurate must reputation be? | Exactly correct eventually and auditable; short delays acceptable. |
| Single site or a network of sites? | Design for one large site, noting how a network of sites (Stack Exchange) shares infrastructure. |
| Search requirements? | Full-text plus structured filters (tags, score, user, answered or not), results in under a few hundred milliseconds. |
| Duplicate detection? | Suggest similar questions while the user types a title; let the community close duplicates. |
| Content license? | User content is publicly licensed (Stack Overflow uses Creative Commons BY-SA) and periodically dumped. |
| Infrastructure preference? | Open; we will compare a scale-up design (few large servers) with a scale-out design. |
Requirements#
Functional requirements#
- Users can ask questions with a title, body (Markdown) and 1–5 tags; edit them; and see revision history.
- Users can answer questions and comment on questions and answers.
- Users can upvote and downvote questions and answers (and upvote comments); askers can accept an answer.
- Reputation is computed from votes, accepts and bounties and unlocks privileges at thresholds.
- Users can browse questions by tag, sort (newest, active, votes, unanswered), and watch or ignore tags.
- Users can search questions with full-text and structured filters.
- The system suggests possible duplicates while asking; privileged users can close questions as duplicates.
- Badges are awarded automatically for defined behaviours.
- Users can flag content; review queues and moderators handle flags, close votes and edits.
Non-functional requirements#
- High availability for reads. Readers must always be able to view questions, even during write outages or deploys.
- Low latency. Server render time for question pages in tens of milliseconds; cached anonymous pages served in single-digit milliseconds from caches.
- Read-heavy scale. Thousands of page views per second at peak, mostly anonymous.
- Durability and correctness. Posts, edits and votes never lost; reputation exactly derivable from the vote and event history.
- SEO friendliness. Fast, stable, crawlable URLs (
/questions/{id}/{slug}); search engines are the main traffic source. - Abuse resistance. Spam, vote fraud and sock-puppet accounts must be detected.
Capacity Estimation#
These are design targets of a plausible size; real Stack Overflow figures quoted in the deep dives are labelled as such. See Back-of-the-Envelope Estimation.
Reads.
- 100 million monthly visitors, about 1.5 billion page views per month ≈ 50 million page views per day ≈ 600 per second on average.
- Peak (weekday working hours across the US and Europe) about 2–3× average: 1,500–2,000 page views per second. Each page view triggers a handful of other requests (assets, API calls for votes and comments, ads), so the load balancers see several thousand HTTP requests per second, most for static assets served from a CDN.
- About 80–90% of page views are anonymous question pages arriving from search engines.
That is far smaller than social networks in requests per second. A question page view is cheap if the page is cached, and the content is not personalised for anonymous readers. This is why a scale-up design is even possible.
Writes.
- New questions: about 5,000 per day (a few per minute). New answers: about 7,000 per day. Comments: about 20,000 per day. Edits: about 10,000 per day.
- Votes: perhaps 200,000 per day ≈ 2–3 per second on average, tens per second at peak.
- Total writes are on the order of 10 per second, peaking at perhaps 50–100. Reads outnumber writes by more than 100 to 1 by requests, and by far more in bytes.
Storage.
- Archive: about 25 million questions and 35 million answers. A post averages about 2–3 KB of Markdown plus rendered HTML (stored to avoid re-rendering): 60 million × 5 KB ≈ 300 GB. Comments (80 million × 300 bytes) ≈ 25 GB. Edit history adds a few times the post size: say 500 GB–1 TB. Votes (hundreds of millions of rows × 30 bytes) ≈ tens of GB.
- In total around 1–2 TB of primary relational data including indexes, which fits in the RAM of a single large database server (servers with 1–2 TB of memory are commodity hardware in the 2020s).
- Images uploaded into posts live in an external image host or object storage, served by a CDN.
Hot set. Question views follow a long-tail distribution: a few hundred thousand questions get most views on a given day, while millions get an occasional visit. With caching of rendered pages for the hot set and the database in RAM for the tail, nearly every read avoids disk.
| Quantity | Estimate |
|---|---|
| Page views | ~600/s average, ~2,000/s peak |
| Anonymous share | ~80–90% |
| Writes (posts, comments, edits, votes) | ~10/s average, ~100/s peak |
| Questions plus answers | ~60 million |
| Primary relational data | ~1–2 TB with indexes |
| New questions | ~5,000/day |
| Read:write ratio | >100:1 |
Core Entities#
- User: ID, display name, reputation, creation date, last access, location, about, flags (suspended), privileges derived from reputation.
- Post: ID, type (question or answer), parent (for answers: the question), author, title (questions), body (Markdown) and rendered HTML, score, creation and last-activity times, accepted answer ID (questions), closed state and reason, duplicate target, view count, answer count, tags (questions), community wiki flag.
- Comment: ID, post, author, text, score, creation time.
- Vote: user, post, type (upvote, downvote, accept, bounty start or award, favourite or bookmark, close, reopen, spam or offensive flag), creation time.
- Reputation event: user, amount, reason (upvote on answer, accept, bounty, reversal), source post and vote, time; the ledger behind reputation.
- Tag: name, question count, wiki excerpt and body, synonyms.
- Post history: post, revision number, type (initial body, edit title, edit tags, rollback), text, editor, time, comment.
- Badge: user, badge type, class (bronze, silver, gold), date, optional post.
- Flag and review task: item, flag type, flagger, state; review queue, reviewer, outcome.
API Design#
The site is mostly server-rendered HTML for SEO; logged-in interactions call a JSON API, and there is a public read API. See API Design Best Practices.
# Reading (HTML pages; JSON equivalents for apps and the public API)
GET /questions/{id}/{slug} → question page: question, answers sorted, comments
GET /questions?tab=newest|active|votes|unanswered&tagged=java+-android&page=2&pagesize=50
GET /search?q=[python] dict comprehension score:5 is:question
GET /tags?sort=popular GET /users/{id}
# Writing (JSON, authenticated, CSRF-protected)
POST /api/questions { title, body, tags[] } → 201 { id, url }
POST /api/questions/{id}/answers { body } → 201 { id }
POST /api/posts/{id}/comments { text } → 201 { id }
POST /api/posts/{id}/edit { title?, body?, tags?, comment, baseRevision }
PUT /api/posts/{id}/vote { type: up | down | none } → { score, myVote }
POST /api/questions/{id}/accept { answerId }
POST /api/questions/{id}/close { reason, duplicateOf? }
POST /api/posts/{id}/flags { type, text? }
GET /api/questions/similar?title=How+to+merge+two+dicts → possible duplicates while typingDesign notes:
- Canonical URLs include the ID and a slug of the title; the slug is cosmetic, and requests with a wrong slug redirect (301) to the canonical one so search engines see one URL per question.
- Votes are idempotent state changes (
PUTwith the desired state), so retries and double-clicks do not double count. See Idempotency and Safe Retries. - Edits carry the base revision: if someone else edited in the meantime, the server rejects or asks the user to merge, rather than silently overwriting (optimistic concurrency).
- The similar-questions endpoint is called as the user types the title (debounced), and must answer in under about 200 ms.
- Anonymous pages are served with caching headers and from server-side output caches; logged-in pages add personal elements (your votes, your reputation, notifications) and are rendered per user.
- Rate limits apply per user and per IP to posting, voting and the public API, with stricter limits for new accounts. See Rate Limiting and Throttling.
High-Level Design#
We build up the design requirement by requirement. The architecture deliberately starts as a well-structured monolith on a few strong machines, because the workload (mostly cached reads, low write rate, a dataset that fits in RAM) allows it. Deep Dive 8 explains when and why that works, and what a scale-out version would look like.
1) Serve question pages fast#
Readers hit a CDN for static assets (CSS, JavaScript, images) and, optionally, for whole anonymous pages. Page requests go through load balancers (for example HAProxy) to a pool of stateless web servers running the application. The application renders the question page from a local in-memory cache (per server), then a shared cache (Redis), then the relational database (SQL Server or PostgreSQL), whose working set sits in RAM.
2) Write questions, answers, comments and votes#
Writes are handled by the same web servers: validate, check privileges and rate limits, write in a database transaction (post plus tags plus history row; or vote plus score update plus reputation event), then invalidate affected cache entries and publish a message (via Redis pub/sub) so every web server drops its local copy. Slower side effects (search indexing, badge checks, notifications, spam scoring) are queued for background workers.
3) Reputation, privileges and badges#
Each reputation-affecting action writes a reputation event in the same transaction as the vote or accept, and updates the user's cached reputation total. Privileges are computed from reputation on each request (a lookup table of thresholds). Badge jobs run on events (immediate badges like "first answer accepted") and on schedules (badges that need aggregates over time, like visiting on many consecutive days).
4) Tags and browsing#
Question lists by tag (/questions/tagged/java, newest or votes, with excluded tags) are served by a tag engine: an in-memory index from tags to sorted question ID lists, able to intersect and subtract tag sets quickly. It loads from the database and receives updates as questions are created, edited, retagged, closed or deleted.
5) Search and duplicate detection#
A search cluster (Elasticsearch or OpenSearch) indexes question titles, bodies, answers and tags, fed by background indexers. It serves full-text search with filters, and the similar questions lookup used while asking. Duplicate closures by the community feed back as labelled data.
6) Moderation#
Flags, close votes, first posts and suggested edits create review tasks in queues; privileged users and moderators process them. Automated spam and vote-fraud detectors run as background jobs and can delete spam, suspend accounts or reverse votes.
The full high-level design#
Components:
- CDN: static assets, user images, optionally cached anonymous HTML.
- Load balancers: TLS termination, health checks, routing, request logging and coarse rate limiting.
- Web servers: the monolithic application rendering pages and handling writes; stateless, so any server can serve any request.
- WebSocket servers: push live updates (new answers, comments, inbox, reputation changes) to open pages.
- Background job servers: indexing, badges, notifications, spam and fraud detection, data dumps.
- Tag engine: in-memory tag-set queries for browsing and filtering.
- Search cluster and similar-questions service: full-text search and duplicate suggestions.
- Redis: shared L2 cache, pub/sub for cache invalidation and live updates, counters such as view counts.
- Relational database: the source of truth for everything, with a synchronous replica for failover and an asynchronous replica in a second data centre.
Key Flows#
Flow 1: an anonymous reader opens a question from a search result#
This is the flow that matters most, because it is most of the traffic. The reader clicks a search result such as /questions/231767/what-does-the-yield-keyword-do. The browser fetches the HTML from the site, then CSS, JavaScript and images from the CDN.
Step by step:
- Routing and canonical URL. The load balancer picks a healthy web server. The application parses the ID (231767). If the slug in the URL does not match the current title's slug, it returns a 301 redirect to the canonical URL. Search engines then keep one URL per question, which concentrates ranking signals.
- The question model. The page needs the question, its answers in the chosen order (by score by default, with the accepted answer pinned or not depending on the site's setting), the first few comments on each post, and the author cards (name, reputation, badges). The application assembles this into one question model, and caches the model rather than individual rows.
- Cache lookup. The local in-process cache (L1) is checked first. It costs a memory lookup, well under a millisecond. On a miss, the shared Redis cache (L2) is checked (about 0.2–0.5 ms on a local network). On a miss there too, the database is queried. Because the database's working set is in RAM, the queries take a few milliseconds.
- View count. The view is counted in Redis, deduplicated by IP or user within a time window so that refreshes do not inflate the count. A background job periodically flushes counts to the database.
- Render. The server renders HTML from the model. For an anonymous reader nothing on the page is personal, so the response can also be cached in an output cache keyed by URL for a short time, and served with
Cache-Controlheaders.
Latency budget. On an L1 hit, the render dominates: a few milliseconds of template work. On a full miss, perhaps 5–15 ms of database work. Stack Overflow's engineers have reported average server render times for question pages in the region of 20 ms, which is what this budget aims for. The rest of the page load time is network and browser work, which the CDN reduces.
Flow 2: a logged-in user posts an answer#
Step by step:
- Checks. Authentication and a CSRF token are verified. Rate limits apply (new users can post only so often). The user must not be blocked from answering (there are automatic answer bans for accounts with a history of poorly received posts). A cheap spam pre-check looks at links, known spam phrases and the account's age.
- Rendering. The Markdown body is converted to HTML on the server and sanitized against a whitelist of tags and attributes, so no script can be injected. Both the Markdown (for editing) and the HTML (for display) are stored, so pages never render Markdown at read time.
- Transaction. In one database transaction: insert the answer row, insert the first revision into post history, and update the question's
answer_countandlast_activity_date. If any step fails, none happens. - Invalidation. The question model key is deleted from Redis, and an invalidation message is published on a Redis pub/sub channel. Each web server subscribes and drops its L1 copy of that question. The next reader rebuilds the model.
- Side effects. The answer is queued for search indexing, a notification is sent to the asker's inbox, badge rules are checked (first answer, for example), and an asynchronous spam classifier scores it. None of these block the response.
- Live update. Readers who have the question open receive a "1 new answer" banner through a WebSocket, so they do not post a duplicate answer.
Flow 3: a user upvotes an answer#
The vote endpoint takes the desired state (up, down or none) rather than "toggle". The server reads the existing vote by the same user on the same post and computes the delta: from none to up is +1 score and +10 reputation; from down to up is +2 score and the author regains the 2 they lost plus gains 10; from up to none reverses the original. Because the request states the final state, a retried or double-clicked request computes a zero delta the second time. Deep Dive 2 covers the reputation rules and the daily cap.
The score update is UPDATE posts SET score = score + @delta WHERE id = @id, which is atomic in the database. Two users voting at the same moment both succeed without a lost update. The write rate on any single post is tiny (a viral answer might receive a few votes per second at most), so there is no hot-row problem here, unlike a ticket-booking or flash-sale system.
Data Model#
The data is relational and small enough to fit on one server, so a relational database is the natural store: posts, users, votes and tags have clear relationships, and the most important operations (cast a vote and change reputation, post an answer and update the question) need multi-row transactions. Stack Overflow itself runs on Microsoft SQL Server; PostgreSQL would serve equally well. See Relational Databases and SQL and Data Modeling.
A notable modelling choice, visible in Stack Overflow's public data dump, is a single Posts table for both questions and answers, with a PostTypeId column (1 = question, 2 = answer, plus a few rarer types such as tag wiki). Questions and answers share most columns (body, score, author, dates, edit history), so one table means one set of indexes, one history mechanism, one voting mechanism and one search indexer. Columns that apply only to questions (title, tags, accepted answer, answer count) are null for answers. The alternative, separate questions and answers tables, is cleaner in theory but duplicates every mechanism that applies to "a post".
Answers point to their question through parent_id (a reference from the posts table to itself), which the diagrams show as plain columns. The core tables:
The reputation ledger, badges and edit history:
Tags and moderation have their own tables:
Key SQL, with the indexes that make the hot queries cheap:
CREATE TABLE posts (
id BIGINT PRIMARY KEY,
post_type SMALLINT NOT NULL, -- 1 question, 2 answer
parent_id BIGINT REFERENCES posts(id),-- answers point to their question
owner_id BIGINT REFERENCES users(id),
accepted_answer_id BIGINT,
title VARCHAR(300),
tags VARCHAR(250), -- denormalised '<python><dict>'
body_markdown TEXT NOT NULL,
body_html TEXT NOT NULL, -- sanitized, rendered once
score INT NOT NULL DEFAULT 0,
answer_count INT, view_count INT,
closed_at TIMESTAMP, duplicate_of BIGINT,
created_at TIMESTAMP NOT NULL,
last_activity TIMESTAMP NOT NULL,
deleted_at TIMESTAMP
);
CREATE INDEX posts_answers ON posts (parent_id, score DESC) WHERE post_type = 2;
CREATE INDEX posts_active ON posts (last_activity DESC) WHERE post_type = 1;
CREATE INDEX posts_owner ON posts (owner_id, created_at DESC);
CREATE TABLE votes (
post_id BIGINT NOT NULL, user_id BIGINT NOT NULL,
vote_type SMALLINT NOT NULL, -- 2 up, 3 down, 1 accept, 8 bounty...
created_at TIMESTAMP NOT NULL,
PRIMARY KEY (post_id, user_id, vote_type)
);
CREATE INDEX votes_by_user ON votes (user_id, created_at); -- fraud checks, "my votes"
CREATE TABLE reputation_events (
id BIGSERIAL PRIMARY KEY, user_id BIGINT NOT NULL,
amount INT NOT NULL, reason SMALLINT NOT NULL,
post_id BIGINT, vote_user_id BIGINT, created_at TIMESTAMP NOT NULL
);
CREATE INDEX rep_by_user_day ON reputation_events (user_id, created_at);Notes on the model:
- Denormalised tags string. The
tagscolumn holds the tags as one string (Stack Overflow's dump uses the form<python><dictionary>), so the question page and lists render tags without a join. The normalisedpost_tagstable is the source for tag queries and counts. Both are written in the same transaction on every retag. - Denormalised counters.
score,answer_count,view_count, and the user'sreputationare stored totals of data that also exists in detail (votes, answers, view logs, reputation events). They make reads cheap. A periodic reconciliation job recomputes them from detail rows and fixes drift. - The answers index
(parent_id, score DESC)returns a question's answers in display order with one index range scan. Theposts_activeindex serves the "active questions" page. - The vote primary key
(post_id, user_id, vote_type)enforces "one upvote per user per post" in the database itself, so a race between two requests cannot double count. - Soft deletes. Deleted posts keep their rows with
deleted_atset: users with enough reputation can see and vote to undelete them, moderators can restore them, and reputation from deleted posts is handled by rules (Deep Dive 2). - Body size. Bodies are limited (Stack Overflow's limit is 30,000 characters), which bounds row size and page size.
| Data | Store | Why |
|---|---|---|
| Posts, users, votes, comments, tags, history, badges, flags | Relational database (SQL Server or PostgreSQL), primary plus replicas | Transactions across rows, joins, about 1–2 TB fits in RAM |
| Question models, user cards, rendered fragments | L1 in-process cache plus Redis | Read-heavy, rebuilt from the database on a miss |
| View counts, rate-limit counters, recent activity | Redis | High-rate increments, periodically flushed |
| Tag posting lists | Tag engine memory | Fast set intersection for browsing and filters |
| Search index | Elasticsearch or OpenSearch | Full-text ranking, filters, similar questions |
| Question title embeddings | Vector index (in the search cluster or a dedicated store) | Semantic duplicate detection |
| Images in posts | Object storage plus CDN | Large immutable blobs |
| Access logs, analytics | Columnar warehouse or log store | Large append-only data for analysis |
See Choosing a Database: A Decision Guide.
Deep Dives#
1. Questions, answers and comments#
The three content types look similar but behave differently, and the differences drive the design.
Questions are the unit of navigation and of search. A question has a title (15–150 characters on Stack Overflow), a body, one to five tags, an owner, a score, an optional accepted answer, a closed state, a view count and a "last activity" time. Its URL is the address search engines index, so it must be stable for decades: the numeric ID never changes, and the slug follows the current title with redirects from old slugs.
Answers belong to exactly one question. A question may have zero to dozens of answers, though most have one to three. Answers carry their own score and their own comments, and one of them may be accepted. Answers are ranked on the page: by default by score, with the accepted answer historically pinned to the top. Stack Overflow changed this in 2021 so that the accepted answer is no longer pinned and is ranked by score like the others (it still shows a marker). The reason is instructive: on old questions the accepted answer is often outdated, while a newer answer with a higher score reflects current practice. Other sort options are "trending" (recent votes weighted more), "modified" and "created".
Comments are short (up to 600 characters on Stack Overflow) and are meant for clarification, not discussion: "can you show the error message?" They support only a small Markdown subset, can only be upvoted (no downvotes, no reputation), and only the top few by score are shown, with "show N more comments" to load the rest. This bounds the page: a question with 80 comments still renders fast. Comments that turn into long discussions are moved to a chat room by moderators.
Why one posts table works. Questions and answers share the rendering pipeline, edit history, voting, flagging, deletion and search indexing. Making them one table with a type column means every mechanism is written once. Comments are kept separate because they are different in every way: no history, no downvotes, no reputation, a small text limit.
Rendering once. Markdown is converted to HTML at write time and both are stored. Rendering on every read would waste CPU on a read-heavy site, and storing HTML guarantees that all readers see the same output even if the Markdown library changes. When the renderer does change (a new syntax feature, a security fix in the sanitizer), a background job re-renders affected posts. The sanitizer is critical for security: user HTML is parsed and filtered against a whitelist of tags (p, pre, code, a with safe href, img with safe src) to stop stored cross-site scripting. See Security Fundamentals for System Design.
Edit history and revisions. Every change to a post creates a row in post_history: initial title, initial body, initial tags, then each edit of title, body or tags, plus events such as closed, reopened, locked, rollback and community wiki. The history page shows each revision with a side-by-side or inline diff. Storing the full text of each revision is simple and fast to display; at the sizes here (a post averages a few KB and has a few revisions), the history table is under a terabyte. A more compact scheme would store diffs and periodic full snapshots, at the cost of reconstructing old versions, which is not worth it at this size.
Concurrent edits. Two editors may open the same post. When the second saves, the server compares the revision they started from (baseRevision in the API) with the current revision. If they differ, the save is rejected and the editor is shown the newer version, so no edit is silently lost. This is optimistic concurrency control: no locks are held while someone types, and conflicts are detected at save time. Edits are rare, so conflicts are rarer still. See Concurrency Control and Database Locking.
Suggested edits. Users below the edit privilege (2,000 reputation on Stack Overflow) can suggest edits. A suggestion is stored as a pending revision and goes into a review queue; two approvals apply it (and give the suggester +2 reputation, up to a lifetime limit of 1,000), while rejections discard it. The post owner can approve or reject their own post's suggestion directly. This is a small workflow engine: a state machine with states pending, approved, rejected, and a rule that a later edit to the post invalidates pending suggestions.
Grace period. Edits within the first five minutes after posting by the author do not create a separate visible revision. This keeps history readable when authors fix typos right after posting.
Activity bumping. Answering, editing or commenting (in some cases) updates the question's last_activity time, which moves it to the top of the "active" list. This is how old questions resurface. Because it is a visible ranking signal, it is also a spam vector (trivial edits to bump a question), which is why tiny edits are discouraged by the review rules and suggested edits must change a minimum number of characters.
Locking and protection. Moderators can lock a post (no edits, votes or comments) during edit wars. High-reputation users can protect a question, which blocks answers from very new accounts; this is used on popular questions that attract "thanks" answers and spam.
The question lifecycle above is a state machine, stored as columns (closed_at, protected_at, locked_at, deleted_at) plus post history rows. Each transition records who did it and why, so that every moderation decision is auditable.
2. Voting and reputation#
Why votes exist. Votes do two jobs: they rank answers, putting the best one on top for the next reader, and they reward authors with reputation, which motivates experts to keep answering. A downvote both pushes poor content down and costs the voter a little reputation on answers, so downvoting is a deliberate act.
The reputation rules (Stack Overflow's current values):
| Event | Effect on reputation |
|---|---|
| Your question is upvoted | +10 (raised from +5 in 2019) |
| Your answer is upvoted | +10 |
| Your answer is accepted | +15 (the asker gets +2) |
| Your post is downvoted | −2 |
| You downvote an answer | −1 to you |
| Your suggested edit is approved | +2 (up to 1,000 total) |
| You award a bounty | −bounty amount (50 to 500) |
| You receive a bounty | +bounty amount |
| Your post is flagged as spam or offensive and removed | −100 |
On top of these, a user can earn at most 200 reputation per day from votes. Accepts and bounties do not count toward this cap. The cap limits the damage of vote rings and stops a single viral answer from creating a wildly unrepresentative reputation. Community wiki posts earn no reputation at all.
Reputation as a ledger. The user's reputation column is a cached total. The truth is the list of reputation events: each vote, accept, bounty, reversal and removal produces a row with an amount and a reason. This gives three properties:
- Explainability. Users can see a "reputation" tab listing what earned or lost them points, day by day.
- Reversibility. When fraud is detected (Deep Dive 10), or a post is deleted, the system writes compensating events instead of editing history.
- Recomputability. The total can be recomputed from events at any time. Stack Overflow exposes a "recalculate" action for this. A nightly job can recompute everyone and compare, catching drift from bugs.
The daily cap makes recomputation subtle: the effect of a vote depends on what else happened that day. So the recomputation algorithm processes each user's events in time order, per UTC day, applying the cap. When an old vote is reversed, the day it belonged to is recomputed, which may "unlock" points that were capped that day. The ledger approach is a small, practical form of event sourcing: the events are the source of truth and the total is a projection. See Event Sourcing and CQRS.
The vote transaction. For a vote by user U on post P owned by author A:
BEGIN;
-- 1. Previous state (lock the row so concurrent votes by U on P serialize)
SELECT vote_type FROM votes WHERE post_id = @P AND user_id = @U
AND vote_type IN (2, 3) FOR UPDATE;
-- 2. Apply desired state: delete old vote row, insert new one (or none)
DELETE FROM votes WHERE post_id = @P AND user_id = @U AND vote_type IN (2, 3);
INSERT INTO votes (post_id, user_id, vote_type, created_at) VALUES (@P, @U, 2, now());
-- 3. Score delta computed in the application from old and new state
UPDATE posts SET score = score + @delta WHERE id = @P;
-- 4. Ledger rows for author (and voter, for answer downvotes)
INSERT INTO reputation_events (user_id, amount, reason, post_id, vote_user_id, created_at)
VALUES (@A, @rep_delta, @reason, @P, @U, now());
-- 5. Cached total, respecting the daily cap computed from today's events
UPDATE users SET reputation = reputation + @capped_delta WHERE id = @A;
COMMIT;All five steps commit together, so the score, the vote and the reputation never disagree. The transaction touches four rows in four tables and takes well under a millisecond of database time with data in memory. At tens of votes per second at peak, this is nothing for a single database.
Vote rules enforced on the server:
- Users cannot vote on their own posts.
- Upvoting needs 15 reputation; downvoting needs 125.
- There is a daily vote limit (40 votes per day on Stack Overflow, with extra votes on questions).
- A vote is locked in after a few minutes, unless the post is edited afterwards. This stops users from flipping votes back and forth to game the system, and it lets a voter change their mind if the author improves the post.
- Votes on very old or closed posts follow the same rules, but deleted posts cannot be voted on except by users who can see them.
Privileges from reputation. Privileges are a table of thresholds, evaluated on each request from the user's cached reputation:
| Reputation | Privilege (Stack Overflow) |
|---|---|
| 1 | Ask and answer |
| 15 | Vote up, flag posts |
| 50 | Comment everywhere |
| 125 | Vote down |
| 500 | Access some review queues |
| 1,500 | Create new tags |
| 2,000 | Edit any post directly |
| 3,000 | Cast close and reopen votes |
| 10,000 | Access moderation tools, see deleted posts |
| 20,000 | Trusted user: delete questions and more |
Beta and smaller Stack Exchange sites use lower thresholds. Because privileges are pure functions of reputation (plus suspensions and per-site settings), there is no separate permissions table to keep in sync: when reputation changes, privileges change immediately. This is a nice design point to mention in an interview: derive, do not store whenever the derivation is cheap.
Why scores are shown exactly. Unlike Reddit, Stack Overflow shows exact scores, and users with 1,000 reputation can see the up and down split. That is possible because vote manipulation is handled by fraud detection and reversal rather than by hiding information. It also means displayed scores must be consistent with the vote table; the counters are denormalised but transactional.
Hot posts and counters. Even the most popular questions get only a few votes per second in a burst. So the score lives directly on the post row and is updated in the vote transaction. A site with far higher vote rates (a social network reacting to a viral post) would instead shard counters or batch updates; see Pattern: Dealing with Contention. Recognising that this is not needed here is part of the point of this case study.
3. Tags#
Why tags instead of categories. A question about reading a CSV file in Python with pandas belongs in several places at once. A category tree forces one location; tags allow python, pandas and csv together. Tags are also created by the community (users with enough reputation can create new tags), so the vocabulary grows with technology: new frameworks get tags the week they launch. On Stack Overflow there are tens of thousands of tags, with a long-tail distribution: a handful (javascript, python, java) cover millions of questions, while most cover a few hundred or fewer.
What tags are used for:
- Browsing:
/questions/tagged/python?tab=newest, or "unanswered questions in my tags". - Filtering: combinations such as
python and pandas, orjava and not android. - Personalisation: watched tags highlight questions, ignored tags hide or grey them out, on every list a user sees.
- Expertise: tag scores (total answer score in a tag) drive tag badges and the "top users" per tag.
- Search:
[python] [regex]in a search query restricts to those tags. - Routing: new questions in a tag are pushed to watchers, and notification digests are built per tag.
The tag query problem. "Questions tagged java but not android, sorted by newest, page 3" looks simple in SQL:
SELECT p.id FROM posts p
JOIN post_tags t ON t.post_id = p.id AND t.tag_id = @java
WHERE p.post_type = 1 AND p.deleted_at IS NULL
AND NOT EXISTS (SELECT 1 FROM post_tags x
WHERE x.post_id = p.id AND x.tag_id = @android)
ORDER BY p.created_at DESC
OFFSET 100 ROWS FETCH NEXT 50 ROWS ONLY;With java on about 1.9 million questions, the database must walk the java list in date order and probe the android exclusion for each row. Combinations of several included and excluded tags, plus a user's long list of ignored tags, make it worse. Deep pages make offset costs grow. It works, but each query costs milliseconds to hundreds of milliseconds, and these pages are hit often.
The tag engine. Stack Overflow built a dedicated in-memory service for this, called the tag engine (described in its engineers' blog posts, originally implemented as a .NET service and later moved to its own servers). The idea is a classic inverted index kept in memory:
- For each tag, keep an array of question IDs sorted by each supported sort key (creation date, activity date, score). An array of 2 million 4-byte or 8-byte integers is 8–16 MB, and all tags together are a few GB at most.
- Keep a compact array of per-question attributes (date, score, answer count, closed, deleted) indexed by internal question number, so filters can be checked without the database.
- To answer "java and not android, newest": walk the
javalist from the newest end; for each ID, test membership in theandroidset (a bitmap or hash set), skip if present, and stop after collecting offset plus page-size results.
Set operations. For intersections of two large tags (python and pandas), the engine uses the smaller list and probes the larger one, or walks both sorted lists together (a merge intersection). For exclusions with many ignored tags, it builds a bitmap of excluded question numbers once per query (or caches it per user). Bitmaps over 25 million questions are 3 MB each uncompressed, and compressed formats such as Roaring bitmaps make sparse sets far smaller and AND/ANDNOT operations very fast. The same technique powers search engines' posting lists. See Probabilistic Data Structures for Big Data for the related family of compact set structures.
Worked example. java has about 1.9 million questions, android about 1.4 million, with perhaps 300,000 tagged with both. For "newest java not android" page 1 (50 results), the engine walks from the newest java question; about 16% of recent java questions are also android, so it inspects about 60 IDs to collect 50. Each probe is a bitmap lookup, a few nanoseconds. Total: microseconds. In SQL the same query took a few milliseconds at best, more with ignored tags. Deep pages (page 2,000) are slower, because the engine must skip 100,000 qualifying items; it can bound this, or keep skip pointers every thousand entries.
Keeping the engine fresh. The tag engine is a read model built from the database. On startup it loads all questions' tags and attributes (a few minutes). Then it applies changes: the application publishes events (question created, retagged, closed, deleted, scored, activity) and the engine applies them in memory; it also polls the database for rows changed since its last high-water mark (a "rowversion" or updated_at column) to catch anything missed. Lists sorted by activity or score need re-positioning on each change, which is a delete and insert in a sorted structure; with a few hundred changes per minute, this is trivial. Several engine replicas run for capacity and failover, each building its own copy.
Tag synonyms and merges. Users create near-duplicate tags (js and javascript, postgres and postgresql). A tag synonym maps a source to a master tag: new questions tagged with the source are automatically retagged to the master, and browsing the source redirects. Synonyms are proposed and voted on by users with a high score in the tag, then approved. A merge additionally retags all existing questions from the source to the master, which is a background job touching many rows: it updates post_tags, the denormalised tags string, post history (recording a system retag) and the tag engine, in chunks, so that it does not lock tables for a long time.
Tag counts. The question count per tag appears everywhere. It is a denormalised counter, updated in the same transaction as tag changes, and recomputed nightly. Exact counts are not critical; a count off by a few for a minute is harmless.
Tag cleanup. Tags with very few questions and no wiki are removed automatically after a while. "Meta tags" (tags that describe the question rather than its subject, such as beginner) are discouraged and burninated through a community process that is, mechanically, a mass retag.
Watched and ignored tags. Each user has a small list (tens of tags). Lists render with watched tags highlighted and ignored tags hidden or dimmed. Applying the user's ignored tags is a per-request exclusion; the tag engine handles it with the bitmap approach, caching the user's exclusion bitmap for the session.
4. Search#
What users search for. Most searches start on a web search engine, not on the site; the site's own search is used by logged-in users looking for something specific ("my old answer about regex lookbehind", "questions tagged [sql-server] about deadlocks with score at least 10"). The search has two parts:
- Full-text over titles, bodies, answers and code blocks, with relevance ranking.
- Structured operators:
[tag],user:1234,score:10,is:question,is:answer,answers:0,isaccepted:yes,closed:no,created:2023..2024, quoted phrases, and excluded words.
Why a search cluster. The relational database's built-in full-text search works for small sites; Stack Overflow used SQL Server full-text search in its early years and later moved to Elasticsearch, which handles relevance scoring, stemming, phrase queries, highlighting, and the mix of text and filters better, and scales independently of the primary database. See Elasticsearch and Search Systems.
Index design. Each question becomes one document containing:
title(boosted heavily: a match in the title is a much stronger signal than in a body),bodytext with HTML removed, and code blocks as a separate field (code) with a tokenizer that keeps symbols such as->,::,__init__andstd::vectorintact,tagsas keyword fields (exact match, used for filters and boosts),- numbers for filtering and ranking:
score,answer_count,view_count,accepted,closed,created,last_activity,owner_id, - the text of answers, either nested in the question document (so "question with an answer mentioning X" matches) or as separate answer documents joined at query time.
Nesting answers into the question document makes question-level ranking easy and is the usual choice, at the cost of reindexing the whole question document when any answer changes. Since changes are rare per question, this is fine.
Ranking. The score combines text relevance (BM25 on title, body, code, with field boosts) with quality signals: the question score, whether it has an accepted or highly voted answer, views, and closed or duplicate status (duplicates point to their target and are demoted). A function score of the form bm25 × (1 + log(1 + score)) × (accepted ? 1.2 : 1) × (closed ? 0.5 : 1) illustrates the shape; the exact weights are tuned with click data. Recency matters for some queries (a new library version), so a mild date decay can be applied for queries that mention versions.
Indexing pipeline. Writes are already in the database; a background indexer consumes change events (or polls the posts table by change version), builds the document, and writes it to the search cluster. Indexing delay is seconds. Bulk reindexing (for a mapping change or a new analyser) builds a new index alongside the old one from a full scan of the database, then switches an alias atomically, so there is never a period with a half-built index.
Sizing. 25 million question documents with nested answers average perhaps 8 KB of text each: about 200 GB of source text, which becomes a similar-sized index. Search QPS is modest (tens to low hundreds per second). A cluster of three to a handful of nodes with plenty of RAM handles it; Stack Overflow ran its search on a small number of servers. Replicas give availability; a few shards per index keep each shard at a healthy size of tens of GB.
Operator parsing. The search box parses operators into a structured query: [python] score:5 "list comprehension" -lambda becomes a filter on tag python, a range filter score >= 5, a phrase query on "list comprehension" and an excluded term lambda. Filters use the index's cached filter bitsets and are cheap; full-text scoring runs only over documents that pass the filters.
Search as a defence. Before asking, the site encourages search (the ask page runs a search on the title, Deep Dive 5). Good search reduces duplicates, which is one of the site's biggest quality problems.
5. Duplicate detection#
Why duplicates matter. The same question (how to merge two dictionaries in Python; why is my floating-point arithmetic wrong) is asked again and again. Duplicates waste answerers' time, scatter good answers across many pages, and dilute search results. The site wants every recurring question to point to one canonical question with the best answers. Duplicates are handled at three moments: before asking, after asking, and in search.
Stage 1: while the user types the title. The ask page calls the similar-questions endpoint as the user types (debounced to about every 500 ms after typing stops). It returns perhaps ten candidates, which the user sees as "Questions that may already have your answer". If the user finds their answer, a duplicate never gets created, which is the cheapest outcome.
The lookup must answer in under about 200 ms and work with only a title, which is short (5–15 words) and often vague. Two retrieval methods are combined:
- Lexical retrieval: a search over titles (and optionally bodies) with BM25, using the title text as a query, with stop words removed and important terms (library names, error codes, function names) boosted. It is excellent when the user uses the same words as the canonical question, and when errors are pasted verbatim ("TypeError: 'NoneType' object is not subscriptable").
- Semantic retrieval: an embedding model maps each title (or title plus the start of the body) to a vector. Questions with nearby vectors are similar in meaning even with different words ("combine two dicts" versus "merge dictionaries"). An approximate nearest-neighbour index (HNSW) over 25 million vectors of, say, 384 dimensions at 4 bytes per dimension is about 38 GB raw, which fits in memory on one or two machines, or less with quantisation. See Vector Databases and Similarity Search.
Results from both are merged (for example with reciprocal rank fusion), then re-ranked with quality signals: prefer questions with a high score, an accepted or highly voted answer, many views, and those that are themselves canonical (other questions are closed as duplicates of them). Questions already closed as duplicates are replaced by their targets.
Stage 2: after asking. Once the body and tags are known, the system can do better: compare the full text against candidates, and include the tags as a filter. The related sidebar on every question page shows the same kind of results, computed in the background and cached per question.
Stage 3: community closure. Users with the close-vote privilege can vote to close a question as a duplicate of a specific target. When enough votes agree (historically five on Stack Overflow, reduced to three in 2021), the question is closed and shows a banner linking to the target. Users with a gold tag badge in one of the question's tags can close a duplicate single-handedly (nicknamed the "dupe hammer"), because they are proven experts in that tag. The closed duplicate is not deleted: it becomes a signpost, an extra way to reach the canonical question from search, because it uses different words. This is a valuable insight: duplicates with different wording improve findability.
Learning from closures. Every duplicate closure is a labelled pair (new question, canonical question) chosen by experts. Millions of these labels train and evaluate the similarity model: given a new question, did the model rank its eventual duplicate target in the top ten? This recall at ten is the main offline metric. Online, the metric is the fraction of ask-page sessions where the user clicks a suggestion and does not post (abandonment because the answer was found), balanced against users who give up because the suggestions were bad.
Canonical questions. Some topics deserve one comprehensive question that duplicates are closed against. The community writes these deliberately, and the system can identify them as questions with many inbound duplicate links. In the similarity ranking, a question's inbound duplicate count is a strong quality signal.
Near-exact duplicates and spam. Separately from semantic duplicates, copy-paste duplicates (the same user posting the same question twice, or spam campaigns posting the same text) are detected with fingerprints: a hash of the normalised text, or MinHash signatures over word shingles to catch near copies. A new post whose MinHash matches an existing post with high Jaccard similarity (above about 0.8) is blocked or flagged. MinHash with locality-sensitive hashing finds such pairs in near-constant time per post. See Probabilistic Data Structures for Big Data.
Failure modes. False positives annoy askers ("my question is not a duplicate"), so closure always remains a human decision; the model only suggests. A new question about a library version released last week will not match well against old answers, and recency signals help there. Embedding models drift as language and technology change, so the index is rebuilt periodically with a refreshed model, which means re-embedding all titles (25 million short texts, a few GPU-hours) and building a new ANN index alongside the old one.
6. Read-heavy caching#
The read:write ratio is over 100:1, most readers are anonymous, and the hot set is small compared with the archive. Caching is the main lever, and it is layered. See Caching Fundamentals and Pattern: Scaling Reads.
Layer 0: CDN. Static assets (CSS, JavaScript, sprites, fonts) are fingerprinted with a content hash in the file name and cached forever at the CDN and in browsers. Images uploaded into posts live on an image host behind a CDN. Whole anonymous HTML pages can also be cached at the CDN for 30–60 seconds; this protects the origin during traffic spikes (a question linked from a popular news site), at the price of slightly stale vote counts for anonymous readers. See Content Delivery Networks (CDN).
Layer 1: output cache for anonymous pages. The application can cache the fully rendered HTML of an anonymous question page per URL for a short time (a minute, for example). Since anonymous pages are identical for everyone, a hot question rendered once serves every anonymous reader until it expires or is invalidated.
Layer 2: in-process cache (L1). Each web server keeps the question models, user cards, tag metadata and other hot objects in its own memory. A lookup costs nanoseconds to microseconds and needs no network. The cost is coherence: nine servers holding their own copies must all drop a copy when it changes. Stack Overflow's approach (described by its engineers) is to publish invalidation messages over Redis pub/sub: after a write, the server that did the write publishes "question 231767 changed", and every server removes its L1 entry.
Layer 3: shared Redis cache (L2). A cache miss in L1 checks Redis, which holds the same objects for all servers, so that a newly started server or a server that just dropped a key can fill from Redis rather than the database. Redis is also used for counters (views), rate limits and the pub/sub bus. See Redis in Practice.
Layer 4: the database buffer pool. The database keeps its working set, and in practice the whole database, in RAM. Even a "cache miss" costs a few milliseconds, not disk seeks.
What to cache, and at what granularity. Caching the whole question model (question, answers, comment previews, author cards) means one lookup per page, but any change to any answer invalidates the whole model. Caching each post separately means more lookups but finer invalidation. For a Q&A site, changes per question are rare (a popular question might get a few edits or answers a day), so whole-model caching wins. Per-user data (my votes on this page, my reputation, my inbox count) is never in the shared model: it is fetched separately and merged at render time, so personalisation does not fragment the cache. See Caching Strategies: Cache-Aside, Read-Through, Write-Through, Write-Behind.
Invalidation and its races. With cache-aside, the classic race is: reader A misses and reads the old row; writer B updates the row and deletes the cache key; reader A writes the old value into the cache. The stale value then lives until TTL. Defences:
- Short TTLs on hot objects (minutes), so staleness is bounded.
- Version stamps: store the post's
last_editor row version in the cached value, and in the invalidation message, so a cache fill with an older version than the latest invalidation is rejected. - Delete-after-write with a short delay (a second delete a few hundred milliseconds later), which closes most of the race window.
See Cache Eviction and Invalidation.
Stampedes. When a very hot question's model expires, many requests on many servers may try to rebuild it at once. Single-flight per server (one rebuild per key per process; other requests wait for it), plus early probabilistic refresh before the TTL ends, keep the rebuild rate to roughly one per server per expiry. With nine web servers that is nine database queries, which is harmless. See Cache Failure Modes: Stampedes, Hot Keys and Penetration.
Logged-in users. The 10–20% of logged-in page views cannot use the anonymous output cache, but they still benefit from L1 and L2: the question model is shared, and only a small per-user overlay is fetched (votes by this user on these posts, a single indexed query, cached for the session). This keeps logged-in render times close to anonymous ones.
Hit rates in practice. With the hot set in L1 and everything else in RAM in the database, the database sees only misses and writes. Stack Overflow's engineers have described database CPU usage staying low even at peak; the cache hierarchy, not the database, carries the read load.
7. Why a few large servers can work (scale up)#
This is the headline lesson of the case study. Most interview answers reach for sharded databases, dozens of microservices and Kafka by reflex. Stack Overflow is a real, documented counterexample: for many years it served a top-100 website from a small fleet in its own data centres. See Vertical vs Horizontal Scaling and Stateless Design and Monolith vs Microservices.
What was published. Nick Craver's 2016 blog series "Stack Overflow: The Architecture" and the "Stack Exchange by the numbers" posts described roughly this setup (exact counts changed over the years, so treat the numbers as approximate):
- About 9 web servers running the ASP.NET application (one monolith serving Stack Overflow and the other Stack Exchange sites), at low CPU utilisation.
- Two SQL Server clusters: one for Stack Overflow and one for the rest of the network, each a primary with replicas, on machines with hundreds of GB of RAM (later upgraded beyond a terabyte), with all data in memory.
- Two Redis servers (primary and replica) for the shared cache and pub/sub.
- Three tag engine servers and three Elasticsearch servers.
- HAProxy load balancers in front, and a CDN for static assets.
- A second data centre for disaster recovery.
- Billions of page views per month and peaks of thousands of HTTP requests per second, with question pages rendered in tens of milliseconds.
The team also built and open-sourced tools that came out of this approach: Dapper (a lightweight .NET object mapper, used to keep database access fast and close to SQL), StackExchange.Redis (a Redis client), MiniProfiler (shows the time spent in each SQL query and step on every page, for developers), and Opserver (a monitoring dashboard).
Why it works here: the workload. Every property of the workload points to scale-up:
- The dataset fits in RAM. About 1–2 TB of hot relational data fits in a single large server's memory. No disk reads means latency is CPU-bound and predictable.
- Writes are few. Tens per second at peak is far below what one relational database handles (tens of thousands of simple transactions per second on modern hardware). There is no write-scaling problem to solve.
- Reads are cacheable. Most traffic is anonymous and identical per URL; the cache layers absorb it.
- There are no hot fan-out paths. A new answer notifies one asker and a few watchers, not millions of followers. Compare a news feed, where one post may fan out to millions of timelines.
- Relationships are rich and transactional. Votes, reputation and posts benefit from joins and transactions across tables. Sharding would turn them into distributed transactions or eventual consistency.
The arithmetic. Suppose peak is 2,000 page views per second, 85% served from the output cache or the CDN without application work, leaving 300 page renders per second. Each render costs about 20 ms of CPU on a web server. That is 300 × 0.02 = 6 CPU-seconds per second, so 6 cores busy. A modern web server has 32–64 cores. Even with room for spikes, logged-in pages and API calls, a handful of servers suffice; nine leaves a large margin and allows rolling deploys and failures. On the database: suppose 10% of renders miss both cache layers and run 10 queries at 1 ms each: 30 misses × 10 ms = 0.3 CPU-seconds per second, plus writes. The database is nearly idle.
What scale-up buys:
- Simplicity. One codebase, one deploy, one database schema, no network calls between services for a page render, no distributed transactions, no eventual consistency between services. A small team can understand the whole system.
- Latency. In-process function calls instead of network hops; one database round trip instead of fan-out to five services.
- Cost. A few powerful servers, bought and run for years, can be cheaper than hundreds of cloud instances (though it requires operations staff who manage hardware).
- Debuggability. MiniProfiler on every page and a small fleet make performance problems visible and easy to fix.
What it costs:
- A large blast radius. If the primary database fails, writes stop until failover. The mitigation is a synchronous replica (automatic failover in seconds) and a second data centre (manual failover in minutes). Reads can continue from caches and replicas.
- A hard ceiling. There is a largest server you can buy. If the data grew to 50 TB or writes grew 1,000×, scale-up would stop working. For Stack Overflow, growth has been slow enough that hardware got bigger faster than the data did.
- Hardware operations. Running your own data centres means buying, racking, networking and replacing machines. The company later moved products to public cloud in the 2020s; the architectural lessons, however, do not depend on owning hardware: a few large cloud instances behave the same way.
- Team scaling. A monolith is easiest with a small team. With hundreds of engineers, deploy contention and code ownership become problems that microservices partly address.
The scale-out version, for comparison. If the requirements changed (ten times the content, many independent teams, global write traffic), a scale-out design would look like this:
- Shard posts by question ID (answers co-located with their question), users by user ID, and votes by post ID. The vote transaction now spans the post's shard (score) and the author's shard (reputation), so it becomes a local write of the vote and score, plus an asynchronous reputation event via a durable queue, with idempotent consumers. Reputation becomes eventually consistent, typically by seconds.
- Split services along domain boundaries: posts, votes and reputation, search, tags, notifications, moderation.
- Replace the in-memory tag engine with a sharded search index (tag filters are just filters in Elasticsearch).
- Keep the cache layers, which matter even more.
See Partitioning and Sharding.
The interview lesson. Do the arithmetic first. If the numbers show that a single database with replicas and good caching handles the load with a large margin, say so, and design the simple system. Then explain the limits (when would it stop working?) and what you would change. Interviewers reward this judgement more than a reflexive microservice diagram. The same reasoning appears in Real-World Architecture Lessons.
Reads during write outages. Since reads are mostly served from caches and replicas, the site can keep serving pages while the primary database is down or in maintenance, in a read-only mode: writes are disabled with a banner, and everything else works. Stack Overflow has used read-only mode during data-centre failovers. Designing for this explicitly is cheap and gives high read availability with a single write primary. See Designing for High Availability.
8. Badges#
Why badges. Badges reward behaviours that reputation does not capture: editing, voting, reviewing, visiting regularly, answering old questions, and recognition for very good content. They come in three classes: bronze (common, teaches site mechanics), silver (needs sustained effort), gold (rare). On Stack Overflow, examples include:
| Badge | Class | Rule (approximate) |
|---|---|---|
| Student | Bronze | First question with score of 1 or more |
| Teacher | Bronze | Answer a question with score of 1 or more |
| Nice Answer / Good Answer / Great Answer | Bronze / Silver / Gold | Answer score of 10 / 25 / 100 |
| Famous Question | Gold | Question with 10,000 views |
| Enthusiast / Fanatic | Silver / Gold | Visit the site on 30 / 100 consecutive days |
| Necromancer | Silver | Answer a question more than 60 days later, with score 5 or more |
| Electorate | Gold | Vote on 600 questions and 25% or more of total votes on questions |
| Tag badges | Bronze / Silver / Gold | Total answer score of 100 / 400 / 1,000 in a tag, with 20 / 80 / 200 answers |
Two kinds of evaluation.
- Event-driven badges depend on a single event: "first accepted answer", "answer reached score 10". They are checked when the event happens, by a background consumer of the vote or post event, and awarded within seconds.
- Aggregate badges depend on totals or streaks: consecutive visit days, total votes, tag scores. They are computed by scheduled jobs that run SQL over the relevant tables (for example every few minutes for some, daily for others) and award any badges whose condition is now true.
Each badge is a rule with a condition and an evaluation trigger. A simple implementation stores rules in code (each is a SQL query or a function), and a scheduler runs them. Rules must be idempotent: a user who already holds a once-only badge must not get it again. Badges awarded multiple times (Nice Answer for each qualifying answer) are keyed by (user, badge, post), with a unique constraint.
-- Event-driven example: Nice Answer when an answer reaches score 10
INSERT INTO badges (user_id, badge_type, badge_class, post_id, awarded_at)
SELECT p.owner_id, @NICE_ANSWER, 3, p.id, now()
FROM posts p
WHERE p.id = @answer_id AND p.post_type = 2 AND p.score >= 10
AND NOT EXISTS (SELECT 1 FROM badges b
WHERE b.user_id = p.owner_id AND b.badge_type = @NICE_ANSWER
AND b.post_id = p.id);Visit streaks. "Consecutive days visited" needs a record of which UTC days each user was active. Store a per-user "last visit day" and "current streak" (updated at most once a day on the first request of the day) rather than a row per visit. The streak update is a tiny write: if today is last day plus one, increment; if today equals last day, do nothing; otherwise reset to 1.
Tag score badges. Total answer score per user per tag is the heaviest aggregate. It can be maintained incrementally (each answer vote adds to the score of the answer's question tags for the answer's author) or recomputed daily. Incremental maintenance is cheap: a vote on an answer in a question with three tags updates three counters.
Badges are not reversed lightly. If a post's score later drops below the threshold, the badge stays; if the badge was earned by fraud, moderators remove it with the fraud reversal. This keeps the system simple and avoids taking away awards for normal score changes.
Notifications. A badge award creates an achievement notification, delivered to the user's achievements list and over WebSocket if they are online. The badge job writes the badge and the notification in one transaction, so a crash between them cannot lose one.
9. Moderation: flags, review queues and moderators#
The model: community first, moderators as exception handlers. Most moderation is done by ordinary users with privileges earned through reputation: editing, close votes, reviewing. A small number of elected moderators (Stack Overflow holds regular elections, and the sites have a few dozen moderators each at most) handle what the community cannot: abuse, disputes, account suspensions, and content requiring judgement or private information. Staff handle legal and policy issues. This scales moderation with the community instead of with payroll.
Flags. Any user with 15 reputation can flag a post or comment: spam, rude or abusive, needs moderator attention (free text), very low quality, not an answer, or a close-reason flag (which becomes a close vote suggestion). Flags carry the flagger, type and state. Some flags are handled by the community (spam and rude flags from several users automatically delete a post: six such flags on Stack Overflow), others go to the moderator queue.
Flag weight. A user whose flags are usually marked helpful earns more trust; flags from users with a poor record are deprioritised. This is a simple reputation system for flaggers, computed from historical flag outcomes, and it orders the moderator queue so that the most reliable flags are seen first.
Review queues. Work items flow into queues, each with its own reputation threshold and number of required reviews:
- First questions and first answers: posts by new users, reviewed to guide newcomers and catch spam early.
- Late answers: answers to old questions by new users (often "thanks" or "me too").
- Close votes and reopen votes: questions with pending votes.
- Suggested edits: edits by users below the edit privilege (Deep Dive 1).
- Low quality posts: posts flagged by users or by an automatic quality score.
Each queue is a table of review tasks with states (pending, completed, invalidated) and a list of reviews. When a task receives enough agreeing reviews, it completes and applies its outcome (close, delete, approve the edit). If the post changes in a way that makes the task moot (the post was deleted by its author), the task is invalidated.
Serving the queues. A reviewer opens a queue and gets the next task they have not reviewed, have not skipped, and are eligible for (not their own post, matching their tag filters if any). This is a classic work queue with per-reviewer exclusion. At Stack Overflow's scale (thousands of tasks per day per queue), a SQL query over the pending tasks with an index on (queue, state, created_at) and a "not reviewed by me" anti-join is enough. A brief claim (the task is reserved for this reviewer for a few minutes) avoids two reviewers doing the same work when only one more review is needed.
Audits. To detect robo-reviewers (users who click "looks OK" on everything to earn review badges), queues insert audit items: known-good or known-bad posts with a known answer. A reviewer who fails audits is temporarily banned from reviewing. This is an elegant quality-control device: it measures reviewers against ground truth without trusting them.
Closing questions. Close reasons include duplicate, needs details or clarity, needs more focus, opinion-based, and off-topic (with site-specific sub-reasons). A closed question accepts no new answers but can be edited and reopened. Questions closed for a while with a negative score and no answers are deleted automatically by a cleanup job (the "roomba" in community slang), which keeps the archive's quality up without manual work.
Moderator tools. Moderators can suspend users for a fixed period, merge accounts, delete or undelete anything, lock posts, convert answers to comments, view the history of a user's flags and votes, and investigate voting patterns (Deep Dive 10). Each action writes to a moderator audit log. Moderator messages to users are private and logged.
Automatic quality and spam signals. A background classifier scores each new post using text features (all caps, very short, link-only, no code, known spam phrases), the account (age, reputation, previous deletions) and network signals (IP reputation, many accounts from one IP). High spam scores hold the post for review or delete it outright. Volunteer communities have also built external spam detection bots that watch the public feed of new posts and raise flags, which the site's API supports.
Rate limits and automatic bans. Users whose questions are repeatedly closed, downvoted or deleted hit a question ban: they cannot ask for a period, and the system tells them how to improve. New users can post only a limited number of questions per day and must wait between posts. These limits are enforced with counters in Redis and rules evaluated at post time.
10. Vote fraud and serial voting#
The threats.
- Sock puppets: one person creates several accounts to upvote their own posts.
- Vote rings: a group of users systematically upvote each other.
- Serial voting: a user upvotes (or downvotes) many posts by one target user in a short time, out of friendship or revenge, rather than judging each post.
- Reputation farming: low-quality self-answer pairs, or posting copied answers to collect votes.
Serial voting detection. A scheduled job (Stack Overflow runs a script daily) scans recent votes grouped by (voter, target author). If one voter cast many votes on one author's posts within a short period, beyond what normal reading explains, the votes are reversed: the vote rows are marked invalidated and compensating reputation events are written, which the user sees as "voting corrected" in their reputation history. The query is cheap with the votes_by_user index:
SELECT v.user_id AS voter, p.owner_id AS target, v.vote_type, COUNT(*) AS n
FROM votes v JOIN posts p ON p.id = v.post_id
WHERE v.created_at >= now() - INTERVAL '1 day'
AND v.vote_type IN (2, 3)
GROUP BY v.user_id, p.owner_id, v.vote_type
HAVING COUNT(*) >= @threshold;The real algorithm uses more than a count threshold (the fraction of the voter's votes that go to one target, whether the voter visited the posts, how fast votes came), and its exact rules are deliberately not published, because publishing them would teach fraudsters to stay just under them. That is a general principle for abuse systems: keep detection thresholds private.
Sock-puppet detection. Accounts are linked by shared signals: IP addresses, browser fingerprints, cookies, email patterns, and behaviour (they only vote for one user, they log in one after another). These signals are stored in an access log and an account-linking graph; moderators can see suspected links and investigate. When accounts are confirmed as sock puppets, their votes are invalidated, the puppets are deleted or merged, and the main account may be suspended. Vote invalidation uses the same ledger mechanism as serial voting reversal. Graph techniques help here: connected components of accounts linked by shared signals, and voting graphs where a tight cluster of mutual upvotes stands out from normal behaviour. The separate case study Design a Social Graph and Shortest-Path Search covers graph storage and traversal at scale.
Why the ledger design matters. Fraud is detected after the fact, sometimes weeks later. Because reputation is a sum of events, reversing fraud is a matter of inserting compensating events and recomputing the affected days, not of guessing what totals should have been. Without the ledger, fixing fraud would require recomputing everything from the votes table anyway.
Rate limits as fraud prevention. The daily vote limit (40), the reputation cap (200 per day from votes) and the reputation needed to vote (15 for up, 125 for down) all limit what a new account or a ring can do. A sock puppet needs to earn 15 reputation before it can upvote at all, which takes real participation that moderators can see.
Metrics. Track invalidated votes per day, reversed reputation, accounts suspended for voting fraud, and the time between fraud and detection. Spikes indicate a new campaign. Alerts on a sudden jump in votes to one user help catch problems within hours instead of days.
11. View counts, hot questions and live updates#
View counting. Each question shows a view count, which also drives badges (Famous Question at 10,000 views) and ranking signals. Counting naively (increment on every request) has two problems: refreshes and bots inflate counts, and 2,000 database writes per second for views alone would be the largest write load on the system by far.
The fix is to deduplicate and batch:
- On each question view, the web server checks whether this viewer (user ID, or IP for anonymous readers) has viewed this question recently, using a Redis key such as
viewed:{question}:{viewer}with a TTL of, say, 15 minutes, set withSET NX. Only if the key did not exist does the view count. - Counted views increment a Redis counter per question (
INCR views:{question}), or are appended to an in-memory buffer on the web server. - A background job every minute or so takes the accumulated increments and applies them to the database in one batch:
UPDATE posts SET view_count = view_count + @n WHERE id = @idfor each question with new views. A few thousand updates per minute is trivial. - Known bots and crawlers (by user agent, and by request-rate heuristics) are excluded.
Memory for dedup keys: if 600 views per second each create a key for 15 minutes, that is 540,000 keys at about 100 bytes, roughly 54 MB of Redis memory. A HyperLogLog per question per day would estimate unique viewers in 12 KB each, but exact dedup with short-lived keys is cheaper here because most questions see few views per window.
Hot Network Questions. Stack Exchange shows a sidebar of trending questions from across its sites. The "hotness" formula, published in a meta post and adjusted over time, combines the number of answers, the question score, the sum of answer scores, and the question's age, with an exponent that decays older questions. Its shape is the same as any "hot" ranking: engagement divided by a power of age. A per-site cap stops one site from dominating, and moderators can remove questions from the list. Computation is a periodic job (every few minutes) over recently active questions, storing the top few hundred in a cache. Because the list sends large traffic to small sites, it also exposes questions to many new voters, which can produce unrepresentative votes; per-question opt-outs exist for that reason. The separate case study Design a Community Forum (Reddit) discusses hot ranking formulas in depth.
Live updates. While a reader has a question open, new answers, new comments, edits and vote count changes can arrive. A WebSocket connection per open page subscribes to channels for that question (and the user's inbox and reputation). When a write happens, the web server publishes an event to Redis pub/sub on the question's channel; the WebSocket servers, subscribed to the channels their clients care about, push the event to those browsers. The client then shows "1 new answer, click to load" rather than inserting it immediately, so the reader's place on the page is not disturbed.
Sizing: with perhaps 500,000 concurrent open pages at peak, each WebSocket costs a few KB of memory on the server: about 2–5 GB across the WebSocket tier, which a couple of servers handle. Most pages are anonymous and do not need inbox or reputation channels; they can use the question channel only, or skip live updates entirely, which reduces fan-out. See Polling, Long Polling, SSE, WebSockets and Webhooks and Pattern: Pushing Realtime Updates.
Inbox and notifications. Answers to your question, comments on your posts, @-mentions in comments, and badge awards go to your inbox, a per-user list in the database (small rows: user, type, source post, read flag, time). The unread count is cached per user in Redis and shown on every page; the WebSocket pushes increments. Email digests for watched tags and inbox items are generated by background jobs on schedules the user chooses.
12. Many sites on one platform, the public API and the data dump#
One codebase, many sites. Stack Overflow is one of about 180 sites in the Stack Exchange network (Super User, Server Fault, Mathematics, Ask Ubuntu, and many smaller ones). They share one application, one deploy and one set of web servers. Each site has its own database with the same schema; a request's host name selects the site and its connection string. This is the "database per tenant" form of multi-tenancy, and it fits well:
- Sites are strongly isolated: no query can mix data from two sites by accident.
- Each site's database is small (most are a few GB), so a single SQL Server instance can host many of them, while Stack Overflow, by far the largest, gets its own cluster.
- Schema migrations run per database, in a loop, and must be backward compatible while they roll through.
- Shared data (the global network account, which links a person's profiles across sites, and network-wide features like Hot Network Questions) lives in a separate shared database.
See Multi-Tenant SaaS Architecture.
Per-site settings. Reputation thresholds, close reasons, tag rules, and whether the site is in beta are per-site configuration, read at request time from a cached settings table. The code path is the same; only data differs. This is how a new site can launch without new infrastructure.
The public API. The Stack Exchange API (version 2.x) exposes read access to questions, answers, users, tags and more, and write access (with OAuth) for voting, commenting and posting from apps. Requests are throttled per key and per IP with daily quotas (on the order of 10,000 requests per day for registered applications), and responses include a backoff field when the server wants clients to slow down. The API runs on the same application servers and caches as the website, with extra rate limits, so a misbehaving client cannot hurt the site. See Rate Limiting and Throttling.
The data dump and Data Explorer. All user contributions are licensed under Creative Commons (CC BY-SA), and the company has published periodic anonymised data dumps of every site: XML files per table (Posts, Users, Votes, Comments, PostHistory, Badges, Tags, PostLinks). The dump schema mirrors the production model in this case study, including the single Posts table with PostTypeId. The company has changed the dump's distribution terms over time, so check current terms before relying on it. Stack Exchange Data Explorer lets anyone run SQL queries against a copy of the data that is refreshed regularly (weekly), on separate servers so that heavy analytical queries never touch production.
Producing a dump is a batch job: for each site, read each table from a replica or snapshot, remove private fields (emails, IP addresses, vote voter IDs except for bounties and favourites), write compressed XML, and publish. Using a replica or snapshot keeps the primary unaffected. See Data Pipelines, Warehouses and Lakes.
Analytics and data products. Page views, searches and ask-page behaviour feed a warehouse used for product decisions, the duplicate model's training data, and the annual developer survey's companion statistics. This data never flows back into the live database; it is a separate pipeline from logs.
Scale of the network. Stack Overflow generates most of the traffic; the remaining sites together are a fraction of it. The per-tenant database design means the network as a whole is a few big databases plus many small ones, all of which fit on a small number of SQL servers.
Bottlenecks and Failure Modes#
| Failure / hotspot | Impact | Mitigation |
|---|---|---|
| Primary database failure | Writes stop; uncached reads slow down | Synchronous replica with automatic failover in seconds; read-only mode keeps pages serving from caches and replicas; second data centre for disasters |
| A question goes viral from a news site | Sudden traffic spike on one URL | CDN and output cache for anonymous pages; single-flight rebuilds; stale-while-revalidate so expiry never causes a stampede |
| Redis outage | L2 misses, no pub/sub invalidation, no view counts | L1 caches keep serving; fall back to the database (which has the data in RAM); shorten L1 TTLs while pub/sub is down so stale entries expire |
| Lost invalidation message | A web server shows a stale answer or score | Short L1 TTLs bound staleness; version stamps in cached values; periodic full L1 flush on deploy |
| Tag engine down or lagging | Tag lists slow or slightly stale | Several replicas; fall back to SQL queries for simple tag lists; catch up from the change-version poll |
| Search cluster degraded | Site search and similar-questions slow or failing | Replicas; serve the ask page without suggestions rather than blocking asking; lexical-only fallback if the vector index is down |
| Spam wave from many new accounts | Front page and new-question lists flooded | Rate limits for new accounts; spam classifier holding posts; community spam flags auto-delete at threshold; IP and network blocks |
| Vote ring or sock puppets | Unearned reputation and privileges | Daily serial-voting job, account linking, reputation ledger with compensating events, vote and reputation caps |
| Mass retag or tag merge | Long-running updates lock rows or tables | Run in small chunks in background jobs, off-peak; update the tag engine incrementally |
| Schema migration on a large table | Long locks during deploys | Online, backward-compatible migrations (add columns, backfill in batches, then switch code); test on a production-sized copy |
| Robo-reviewers in review queues | Bad edits approved, bad closures | Audit items with known answers; review bans; minimum review counts |
| Crawler overload | Bots consume capacity meant for users | Separate rate limits for crawlers; sitemap files; serve crawlers from cached pages; block abusive IP ranges |
What Interviewers Expect#
Mid-level. Model users, questions, answers, comments, votes and tags with sensible tables and indexes. Design the APIs with idempotent votes. Show a read path with a CDN, a cache and a relational database with replicas. Explain reputation from votes and a simple privilege table. Use a search engine for full-text search and suggest similar questions while asking.
Senior. Do the capacity arithmetic and notice that writes are tiny, reads are cacheable and the data fits in RAM. Design a layered cache (CDN, output cache, in-process plus shared cache) with an explicit invalidation scheme and its races. Make reputation a ledger of events with a daily cap and reversals, updated transactionally with the vote. Explain the tag engine or an equivalent inverted index with set operations for include and exclude filters. Combine lexical and semantic retrieval for duplicate suggestions and explain duplicates as signposts. Cover review queues, flags and automatic spam handling.
Staff and above. Argue the scale-up versus scale-out decision with numbers, cite the documented Stack Overflow architecture accurately, and say exactly when the design would stop working and what changes then (sharding by question and user, asynchronous reputation, services by domain). Treat read availability as a design goal (read-only mode during write outages). Discuss multi-tenancy across a network of sites with a database per site. Cover abuse as an adversarial system: private detection thresholds, account linking graphs, audits for reviewers. Address operations: online schema migrations, deploys of a monolith several times a day, observability with per-request profiling, and the long-term life of a 15-year archive (re-rendering, re-indexing, re-embedding).
Deep Dive: Sizing every tierShow
All figures follow the Capacity Estimation assumptions (2,000 page views per second at peak, about 100 writes per second at peak, 1–2 TB of relational data). They check that the design hangs together; they are not Stack Overflow's internal numbers.
CDN and edge. Each page view loads perhaps 20–40 static assets on a cold visit, but returning visitors have them cached, and fingerprinted assets never revalidate. The CDN handles tens of thousands of asset requests per second at peak, at a hit ratio above 99%. The origin sees the 2,000 page views per second plus a few thousand API and WebSocket requests per second. Two load balancers (active and standby, or active-active) handle this comfortably; HAProxy on one modern server can handle well over 100,000 requests per second.
Web servers. 85% of anonymous page views served from the output cache or CDN leaves about 300 full renders per second at roughly 20 ms of CPU each, about 6 cores, plus logged-in overlays, API calls and writes. Budget 20–30 cores busy at peak. With nine servers of 32 cores each (288 cores), utilisation stays below about 10–15%, leaving room to lose several servers, deploy in rolling batches, and absorb a 5× spike. Each server's L1 cache uses perhaps 10–30 GB of RAM for question models and other hot objects.
Redis. The shared cache holds the hot set: say 2 million question models at about 20 KB serialised each is 40 GB, plus user cards, tag data and counters. A single Redis primary with 64–128 GB of RAM, plus a replica, handles it; operations per second (tens of thousands, mostly L2 lookups on L1 misses, plus pub/sub and counters) are a fraction of one Redis instance's capacity of over 100,000 operations per second per core.
Database. About 1–2 TB of data and indexes in RAM on a server with 1.5–2 TB of memory. Read queries arrive only on cache misses: perhaps a few hundred to a few thousand simple queries per second. Writes: about 100 transactions per second at peak, each touching a few rows. The write-ahead log grows by perhaps a few MB per second at most. A synchronous replica in the same data centre for failover, an asynchronous replica in another data centre, and one or more read replicas for reporting and the data explorer's refreshes.
Tag engine. Posting lists for all tags: 25 million questions with an average of three tags gives 75 million entries. Stored as 4-byte internal IDs in arrays for three sort orders, that is 75 million × 4 bytes × 3 ≈ 900 MB, plus attribute arrays (25 million × about 32 bytes ≈ 800 MB) and cached exclusion bitmaps. About 2–4 GB of RAM per replica; three replicas.
Search. About 200 GB of index for questions with nested answers, with one replica per shard: about 400 GB across the cluster. Query rate tens to low hundreds per second, plus the similar-questions endpoint, which is called once per debounced title change by the 5,000 or so askers per day (a few calls per second at most). Three to five nodes.
Vector index. 25 million title embeddings at 384 dimensions × 4 bytes ≈ 38 GB raw, or about 10 GB with 8-bit quantisation, plus the HNSW graph (about 25 million × 32 neighbours × 4 bytes ≈ 3 GB). One or two machines, or a vector field inside the search cluster.
WebSockets. 500,000 concurrent connections at peak at 3–10 KB each: 2–5 GB. Two or three servers, with the event rate (writes per second fanned out to the viewers of one question) being low.
Storage growth. 5,000 questions and 7,000 answers per day at about 5 KB including rendered HTML is 60 MB a day, about 22 GB a year of posts, plus a few times that for history, comments and votes: under 100 GB a year. At that growth rate, hardware gets bigger faster than the data grows, which is exactly why scale-up remains viable year after year.
Takeaway. Every tier fits on a few machines with large margins. The architecture's complexity budget is spent on caching, correctness (reputation ledger), search quality and moderation, not on scaling machinery.
Deep Dive: Real-world Q&A systems comparedShow
Stack Overflow and Stack Exchange. As described throughout: a .NET monolith on a small number of large servers, SQL Server with the data in RAM, Redis for caching and pub/sub, a custom in-memory tag engine, Elasticsearch for search, HAProxy load balancing, and a database per site across the network. Its distinctive choices are reputation-gated privileges, community moderation with elected moderators, and a strict focus on answerable questions (closing opinion-based and broad questions) to keep the archive useful. It is the canonical example of a scale-up architecture that worked for a top website.
Quora. A Q&A site that is more social and more personalised: users follow topics and people, and the home page is a ranked feed. Its engineering blog has described a Python application on MySQL with sharding added later as data grew, and heavy use of machine learning for feed ranking, answer ranking and duplicate question detection. In 2017 Quora published a public dataset of question pairs labelled as duplicates or not, which became a popular benchmark for paraphrase detection, showing how central duplicate detection is to Q&A. The feed changes the design significantly: Quora's read path is closer to a news feed with candidate generation and ranking than to Stack Overflow's mostly anonymous, identical pages.
Discourse. An open-source forum platform (co-founded by Jeff Atwood, a Stack Overflow co-founder) built with Ruby on Rails, PostgreSQL and Redis, and deployed as one application per community or as a hosted multi-tenant service. It borrows trust levels (privileges unlocked by participation) from the Stack Overflow model, but organises content as discussion threads rather than questions with ranked answers.
Reddit. Community forums with votes, but votes rank threads and comments for discussion rather than to find a single correct answer, and the feed is personalised by subscriptions. Reddit has far higher write rates (votes and comments) than Stack Overflow, which drives a more scaled-out design with queues and sharded stores. The separate case study Design a Community Forum (Reddit) covers it.
Yahoo Answers. A large general Q&A site launched in 2005 and shut down in 2021. It is often cited as the counterexample on quality: without strong moderation, focus on answerable questions, or a reputation system that gated privileges, the content quality degraded. The lesson for system design is that the community mechanisms (reputation, privileges, closing, review) are part of the system, not a feature on top of it.
| System | Content unit | Ranking | Moderation | Architecture style |
|---|---|---|---|---|
| Stack Overflow | Question with ranked answers | Votes, accept | Reputation privileges, elected moderators, review queues | Scale-up monolith, SQL in RAM |
| Quora | Question with answers, social feed | ML ranking, follows | Staff plus ML, community reports | Python, sharded MySQL, ML-heavy |
| Discourse | Discussion thread | Chronological, likes | Trust levels, staff | Rails, PostgreSQL, Redis |
| Threaded discussion per community | Hot, best, top by votes | Volunteer moderators per community | Scaled-out services and queues |
Deep Dive: A 45-minute interview planShow
| Minutes | What to do |
|---|---|
| 0–5 | Clarify scope: questions, answers, comments, votes, reputation, tags, search, duplicates, moderation. Confirm the traffic mix (mostly anonymous readers from search engines) and the write rate. |
| 5–10 | Capacity: about 2,000 page views per second at peak, about 100 writes per second, 1–2 TB of data. State the conclusion out loud: the data fits in RAM and writes are tiny, so a relational database with replicas and strong caching is enough. |
| 10–15 | Entities and APIs: single posts table with a type, votes with a unique key per user and post, reputation events, tags. Idempotent PUT votes, edits with a base revision, canonical URLs. |
| 15–25 | High-level design: CDN, load balancers, stateless web servers, L1 and L2 caches, SQL primary and replicas, tag engine, search cluster, background workers, WebSocket servers. Walk the read path and the vote path. |
| 25–40 | Deep dives (pick two or three, guided by the interviewer): the reputation ledger and vote transaction; cache layers and invalidation races; the tag engine's set operations; duplicate suggestions with lexical plus semantic retrieval; scale-up versus scale-out with numbers. |
| 40–45 | Failure modes and evolution: database failover and read-only mode, viral questions, spam waves, vote fraud; what would change at 100 times the scale. |
Common mistakes.
- Sharding the database and adding Kafka before doing the arithmetic. The numbers do not need it, and saying so with evidence is the strongest signal in this problem.
- Storing reputation only as a counter, with no ledger, which makes fraud reversal and audits impossible.
- Toggle-style vote APIs that double count on retries.
- Treating duplicate detection as only a search problem, ignoring the community workflow and the signpost value of closed duplicates.
- Forgetting that most readers are anonymous, which is what makes caching so effective.
Deep Dive: Follow-up questions and strong answersShow
"What if writes grew 100 times, for example because of AI-assisted answering?" Votes and posts at 10,000 per second would still fit one well-tuned primary for a while, but the reputation update path would become the hot spot. Move reputation to an asynchronous ledger consumer (vote writes the vote and score; a queue carries the reputation event to a consumer that applies it idempotently by event ID). Then shard by question ID for posts and votes, and by user ID for reputation. Reputation becomes eventually consistent by seconds, which users tolerate.
"How do you keep the L1 caches on nine servers consistent?" Pub/sub invalidation on every write, short TTLs as a safety net, version stamps to reject stale fills, and a full flush on deploy. Consistency is eventual by milliseconds in the normal case and by the TTL in the worst case.
"How would you rank answers?" By score by default, which is simple and transparent. Offer "trending" (recent votes weighted more, so a newer, better answer can overtake an old accepted one) and newest. Do not pin the accepted answer on old questions, because acceptance reflects one asker's situation at one time.
"How do you stop people gaming reputation?" Caps (200 per day from votes, 40 votes per day), privilege thresholds before voting, vote locking, serial-voting reversal, account linking for sock puppets, and private detection thresholds. The reputation ledger makes all reversals clean.
"What happens if the database primary dies during peak?" The synchronous replica takes over in seconds. During those seconds, reads are served from caches and replicas; writes fail fast with a retry message. If the whole data centre fails, the site switches to the second data centre, initially in read-only mode, then promotes the asynchronous replica (accepting the loss of a few seconds of writes, the recovery point objective). See Disaster Recovery and Backups.
"How do you make search understand code?" A separate code field with a tokenizer that keeps symbols and identifiers (std::vector, __init__, ->), exact matching on error messages via phrase queries, and boosts for tag matches. Embeddings help for paraphrased natural-language questions but are weak on exact identifiers, which is why the hybrid of lexical and semantic retrieval works.
"Would you use microservices?" Not at this scale and team size. A modular monolith with clear internal modules (posts, votes and reputation, tags, search, moderation) gives most of the code-organisation benefits without network calls and distributed transactions. Extract a module into a service only when it has a different scaling profile (search, tag engine, WebSockets already are separate) or a separate team.
"How do you handle a new site in the network?" Create a new database from the schema, add a row to the site configuration (host name, thresholds, close reasons), and deploy nothing. Per-tenant databases make this a data operation, not a code change.
"How would you add AI-generated answer suggestions?" Retrieve the most similar questions and their top answers (the duplicate-detection retrieval), pass them to a language model to draft a summary with links to the sources, and show it to the asker before they post, clearly labelled. Keep it out of the archive unless a human posts it, attribute sources as the content license requires, and measure whether it reduces duplicate and low-quality questions.
Deep Dive: Operating a monolith on a small fleetShow
Deploys. A monolith deploys as one artefact. With nine web servers behind a load balancer, a rolling deploy takes servers out of rotation a few at a time, updates them, warms their L1 caches with a few synthetic requests, and puts them back. Stack Overflow has described deploying many times per day this way. Feature flags decouple deploy from release, so unfinished features ship dark. See CI/CD and Deployment Strategies.
Schema migrations. With a single database per site, migrations must not block traffic. The rule is expand, then contract: add a nullable column (instant in most databases), deploy code that writes both old and new, backfill old rows in small batches, deploy code that reads the new column, and drop the old column later. Index builds use online options. Migrations across 180 site databases run in a loop and must be safe to re-run if interrupted.
Profiling on every page. MiniProfiler shows developers the time of each step and SQL query on every page they view in production. This makes N+1 query patterns and slow queries obvious to the people who wrote them, which is the cheapest performance culture there is. Server-side, per-route timing and percentile dashboards catch regressions after each deploy. See Observability: Logs, Metrics and Traces.
Garbage collection and memory. Large in-process caches in a managed runtime (.NET, Java) put pressure on the garbage collector. Long pauses on a web server with 30 GB of cached objects would hurt tail latency. Mitigations: cache serialised byte arrays or structs rather than object graphs, use server GC modes tuned for throughput, bound cache sizes, and move the largest caches to Redis. Stack Overflow's engineers have written about tuning allocations and GC in their .NET code for this reason.
Capacity margin as a feature. Running at 10–15% CPU looks wasteful, but it buys resilience: losing half the web servers or a 5× traffic spike causes no incident. On a small fleet, the margin is cheap in absolute terms (a few servers), and it removes the need for autoscaling machinery. See Capacity Planning and Load Testing.
Network and hardware. With few servers, each one matters, so redundancy is at every level: two load balancers, two network paths, two power feeds, a database replica, spare web servers. Failures of single components should be routine, not incidents.
Deep Dive: Bounties, a small escrow systemShow
A bounty lets a user spend their own reputation to attract attention to a question that has not received a good answer. Mechanically it is a tiny escrow and timer system, and it is a good example of a workflow with money-like semantics inside a Q&A site.
The rules (Stack Overflow). A question becomes eligible for a bounty two days after it was asked. The bounty is between 50 and 500 reputation; the user who starts it pays the amount immediately, whether or not the bounty is later awarded. The question is shown in the "Featured" tab for seven days. The bounty starter can award it to any answer at any time after 24 hours; there is a grace period of 24 hours after the seven days end. If the starter does not award it, half the bounty is automatically awarded to the highest-voted answer posted after the bounty started, provided it has a score of at least 2; otherwise the reputation is simply lost. A second bounty by the same user on the same question must be at least double the previous one.
Why pay up front. Paying when the bounty starts, not when it is awarded, means the reputation cannot be spent twice and the starter cannot escape the cost by deleting the question or never awarding it. It is the same idea as a payment authorisation that captures immediately: the funds leave the account at the moment of commitment. The bounty's amount is held in the bounty row, not in anyone's account, until it is awarded.
Data and transactions.
-- Start: one transaction
INSERT INTO bounties (question_id, starter_id, amount, started_at, ends_at, state)
VALUES (@q, @u, 100, now(), now() + INTERVAL '7 days', 'open');
INSERT INTO reputation_events (user_id, amount, reason, post_id, created_at)
VALUES (@u, -100, @BOUNTY_START, @q, now());
UPDATE users SET reputation = reputation - 100 WHERE id = @u AND reputation >= 100;
-- abort if the UPDATE touched 0 rows (not enough reputation)
-- Award: one transaction, guarded by state
UPDATE bounties SET state = 'awarded', answer_id = @a, awarded_at = now()
WHERE id = @b AND state IN ('open', 'grace');
-- if 1 row updated: insert +100 reputation event for the answer's ownerThe state guard on the award (WHERE state IN ('open', 'grace')) makes the award idempotent and race-free: if the starter clicks award twice, or the automatic award job runs at the same moment, only one UPDATE changes a row, and only that transaction writes the reputation event. Bounty reputation is exempt from the daily cap, as accepts are.
The timer. A scheduled job runs every few minutes: bounties whose ends_at has passed move to grace; bounties whose grace period has ended are auto-awarded (if an eligible answer exists) or marked expired. Because state transitions are guarded and the job is idempotent, running it twice or late causes no harm. There is no need for a precise per-bounty timer: a few minutes of lateness is invisible to users. See Pattern: Managing Long-Running Tasks for the general pattern of durable timers polled by a job.
The Featured tab. Open bounties are listed by amount and time remaining. Since there are at most a few thousand open bounties at any time, the list is a simple indexed query (state, ends_at) cached for a minute.
Abuse. Users could try to move reputation to a friend by starting a bounty and awarding it to their friend's answer. The serial-voting and account-linking checks (Deep Dive 10) cover bounty awards too, and the cost is real: the starter loses the full amount. The ledger records every step, so reversal is the usual compensating-events operation.
Key Takeaways#
- Do the arithmetic first. About 2,000 page views per second, about 100 writes per second and 1–2 TB of data means a relational database in RAM plus caching handles the load with a large margin. Stack Overflow is a documented example of a top website served by a few large servers.
- Most traffic is anonymous and identical, so layered caching (CDN, output cache, in-process L1, shared Redis L2, database in RAM) carries the read load. Invalidate on write with pub/sub, and bound staleness with TTLs and version stamps.
- One posts table for questions and answers lets editing, voting, history, flagging and indexing be built once.
- Reputation is a ledger: each vote, accept or bounty writes an event in the same transaction as the vote, and the total is a projection. That makes caps, reversals, audits and recomputation clean.
- Privileges are derived from reputation with a threshold table, so there is nothing to keep in sync.
- Tags need an inverted index: per-tag sorted ID lists and bitmaps make include, exclude and sort queries take microseconds. Stack Overflow built a dedicated in-memory tag engine for this.
- Duplicate detection combines lexical and semantic retrieval with quality re-ranking while the user types. Community closure stays human, and closed duplicates become signposts that make the canonical question easier to find.
- Moderation is part of the system: flags, review queues with audits, close and delete workflows, automatic spam scoring, and elected moderators as exception handlers.
- Fraud detection is after the fact and private: serial-voting reversal, account linking, and caps, all relying on the reputation ledger.
- Know the limits: scale-up stops working when data or writes outgrow the biggest machine. Then shard by question and user, make reputation asynchronous, and split services by domain.