The 4-Step Approach: Scope, Estimate, High-Level Design, Decisions
"The design doc documents the high level implementation strategy and key design decisions with emphasis on the trade-offs that were considered during those decisions." — Malte Ubl, Design Docs at Google (Industrial Empathy, 6 July 2020)
Summary: Every system design, in an interview or at work, goes through the same four steps: agree what you are building (scope), turn it into numbers (estimate), draw the smallest design that fits the numbers (high-level design), then spend the remaining effort on the few places where it can break and write down why you chose what you chose (decisions). Focus: Functional and non-functional requirements, out of scope, assumptions, users and regions, read/write ratio and consistency needs; QPS from DAU/MAU with peak-to-average, storage with retention and replication, bandwidth, cache sizing with the 80/20 rule, server count with headroom and N+2; API design first, data model, component diagram, read and write data flows; bottlenecks, single points of failure, trade-off tables, ADRs, failure modes, monitoring and evolution; a reusable checklist and design doc template, three worked examples (rate limiter, news feed, ride matching) and the three classic anti-patterns, with a Go estimator and design-doc generator and a Laravel design:check command. Learning goal: Given a one-line prompt ("design a news feed"), produce in under an hour a design doc skeleton whose every box is justified by a requirement or a number, whose write path is sized as carefully as its read path, and whose three riskiest decisions each have an alternative, a consequence and a metric to watch.
This is the method chapter of the System Design path. What System Design Is explains the field; this page gives you the procedure you will reuse in every later chapter and in every case study, including the end-to-end Ticketing case study. Three siblings own the deep material and are linked, not repeated: the arithmetic method and its pitfalls live in Back-of-the-Envelope Capacity Estimation; SLIs, SLOs and error budgets in SLAs, SLOs, SLIs & Error Budgets; ADR formats and the decision process in Architecture Decisions. The tail-latency side of step 2 continues in Latency Budgets & Tail Latency.
Page map
| If you are looking for | Go to |
|---|---|
| The method on one screen | Everything in one minute |
| Why boxes-first designs fail | Why it exists |
| Dean's numbers, Nygard's ADRs, Google design docs, the interview framework | Where it comes from |
| Step 1: requirements, out of scope, assumptions, workload shape | Functional, Non-functional, Out of scope, Workload shape |
| Step 2: QPS, storage, bandwidth, cache, servers, the numbers to know | QPS, Storage, Bandwidth, Cache, Servers, Latency numbers |
| Step 3: API, data model, components, data flow | API, Data model, Components, Data flow |
| Step 4: bottlenecks, trade-offs, failure modes, evolution | Bottlenecks, Trade-offs and ADRs, Failure modes, Evolution and monitoring |
| The output: design doc, interview vs work | Design doc, Interview mode |
| Formulas, units, nines, lint codes | Mechanics |
| Code | Go, Laravel |
| Reusable checklist and template | The template |
| Three worked designs | Rate limiter, News feed, Ride matching |
| Anti-patterns | Jumping to microservices, Premature sharding, Ignoring the write path, Others |
| How much of each step | Choosing |
| Monolith to distributed system | In architecture |
| Run the estimator and the linter | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The four steps. The interview framework popularised by Alex Xu (secondary source, ByteByteGo) names them "Understand the problem and establish design scope", "Propose high-level design and get buy-in", "Design deep dive" and "Wrap up", and puts the back-of-the-envelope estimate inside step 2. This chapter pulls the estimate out into its own step because in real design work it is the step that most often changes the design, and folds "wrap up" into step 4 because evolution and monitoring are decisions, not a closing speech.
| Step | Question it answers | You produce | 45-min interview (Xu's rough guide) | Real design doc | Deep page |
|---|---|---|---|---|---|
| 1. Scope | What exactly are we building, for whom, how well? | Functional + non-functional requirements, out of scope, assumptions | 3-10 min | Context, goals and non-goals | Requirements to Architecture |
| 2. Estimate | How big is it, and where is it big? | QPS and peak, storage, bandwidth, cache, servers | Part of the 10-15 min of step 2 | Capacity section, assumptions table | Capacity Estimation |
| 3. High-level design | What is the smallest design that fits the numbers? | API, data model, component diagram, read and write data flows | 10-15 min | "The actual design" with a system context diagram | REST API Design |
| 4. Decisions | Where does it break, what did we choose and why? | Bottlenecks, deep dives, trade-off tables, failure modes, monitoring, evolution, ADRs | 10-25 min deep dive + 3-5 min wrap up | Alternatives considered, cross-cutting concerns, ADRs | Architecture Decisions |
The step 1 question bank. Ask these before drawing anything; write the answers down as requirements or as assumptions.
| Question | Why it matters | Example answer (news feed) |
|---|---|---|
| Which features, exactly? | Every feature is a path through the system | Post, read feed; no comments, no likes |
| Who are the users, how many, where? | DAU and regions drive QPS and placement | 10 M DAU, one region first |
| How fast must it answer? | Latency SLO decides caching and sync vs async | Feed read p99 under 300 ms |
| How available? | Availability target decides redundancy and failover | 99.95% for reads |
| How stale may data be? | Consistency requirement decides replication and caches | New post visible to friends within 5 s |
| What is the read/write ratio? | Read-heavy and write-heavy designs differ | 10 feed loads per post |
| How much data, kept how long? | Storage, retention, cost | Posts kept 5 years |
| What happens at the edges? | Hot keys, celebrities, spikes | Some authors have 5,000+ followers |
| What exists already? | Reuse beats rebuild | PostgreSQL and Redis already run |
| What are we NOT building? | Out of scope keeps the design small | Ranking, ads, notifications |
The estimate kit. Each row is unpacked in step 2; the method itself is taught in Capacity Estimation.
| Quantity | Formula | Rule of thumb |
|---|---|---|
| Average QPS | requests per day / 86,400 | 1 M per day is about 12 QPS; 1 B per day about 11,600 |
| Peak QPS | average x peak-to-average factor | 2-3 for global consumer traffic, 5-10 for local rush hours or launches |
| Read/write ratio | read QPS / write QPS | Feeds and catalogues 10:1 to 100:1; telemetry and location 1:100 or worse |
| Storage | writes per day x bytes x retention days x replication | Add indexes and overhead (often 1.5-2x the raw row) |
| Bandwidth | QPS x payload bytes, x 8 for bits | Media goes to a CDN, not to your app servers |
| Cache | hot fraction of the daily read set (80/20 rule) | 20% is an upper bound when you count repeated reads |
| Servers | ceil(peak / (per-server QPS x target utilisation)) + spares | Plan 50-70% utilisation and N+2 |
| Downtime budget | (1 - availability) x period | 99.99% is 52.56 minutes a year (Google SRE book) |
The picture is the whole method. The arrows back to step 1 are as important as the arrows forward: an estimate that says "this needs 70,000 writes a second" is a reason to revisit the scope (is fan-out on write a requirement or an implementation choice?), and a deep dive that finds an unsolvable consistency problem is a reason to renegotiate the requirement. Everything ends up in one design doc whose four main sections are the four steps.
Why it exists
A system design question is deliberately vague. Xu's framework describes it as "as vague as 'designing a well-known product X?'", and the vagueness is the test: the interviewer, or the review committee at work, wants to see whether you turn ambiguity into explicit requirements and numbers before spending anyone's time on boxes. The four-step approach is a discipline against the most common failure, which is to start drawing components you have used before and to defend them afterwards.
| Box-first design | Four-step design |
|---|---|
| Starts with familiar components (Kafka, Cassandra, Kubernetes) | Starts with what the user does and how many users do it |
| Requirements are implied by the boxes | Requirements are written, numbered and agreed |
| No out of scope, so the design grows to cover everything | Out of scope and non-goals keep the design small |
| Numbers, if any, appear after the design to justify it | Numbers come first and decide the design |
| The read path is drawn; the write path is an arrow | Both paths are drawn and sized, including fan-out |
| Every choice is "industry standard" | Every choice has an alternative and a consequence (ADR) |
| Failure is "we will add retries" | Each component has a failure mode, an impact and a mitigation |
| Done when the diagram looks complete | Done when the riskiest decisions are written down with what you would monitor |
The analogy we reuse on this page: building a house. Step 1 is the client's brief: how many people live there, do they work from home, what is the budget, and what is explicitly not wanted ("no basement"). Step 2 is the survey and the budget: plot size, soil, how many square metres the brief actually needs. Step 3 is the floor plan: rooms, doors, how people move between them (the data flow), where the water and power come in (the write path). Step 4 is the structural engineer's report: which wall carries the load (bottleneck), what happens in an earthquake (failure modes), why a steel beam rather than concrete (trade-off), and which cracks to inspect each year (monitoring). Nobody pours a foundation before the brief, and nobody chooses beams before knowing how many floors there are.
Three common misunderstandings, up front
- "The estimate is for the interviewer, not for the design." The estimate decides the design. In the news feed example, the read side is about 3,500 requests a second, which one database with a cache absorbs; the write side after fan-out is about 70,000 list writes a second, which no single PostgreSQL primary should take. That single number moves the feed lists into Redis and adds a hybrid fan-out rule.
- "High-level design means drawing the architecture." It means the smallest architecture that satisfies the numbers, starting from the API and the data model. Google's design-doc guidance says the same about the doc: "focus on the parts that are relevant to the design and its trade-offs."
- "Step 4 is where you show off advanced technology." Step 4 is where you find the two or three places the design is most likely to fail and decide them on purpose. Xu's framework names the red flag directly: "Over-engineering is a real disease of many engineers as they delight in design purity and ignore tradeoffs."
Where it comes from
The method is a combination of four older practices: estimating before building, writing requirements as targets, documenting decisions with their alternatives, and reviewing a design before writing code.
Estimating before building: Norvig 2002, Dean. Peter Norvig's essay Teach Yourself Programming in Ten Years ends with a table of "Approximate timing for various operations on a typical PC", from "fetch from L1 cache memory 0.5 nanosec" to "send packet US to Europe and back 150 milliseconds = 150,000,000 nanosec". Jeff Dean's Stanford CS295 talk turned it into the slide "Numbers Everyone Should Know" and stated the skill this chapter trains: "Important skill: ability to estimate performance of a system design – without actually having to build it!" The same slides work one example the way step 2 does: 30 thumbnails read serially cost "30 seeks * 10 ms/seek + 30 * 256K / 30 MB/s = 560 ms", read in parallel about 18 ms, "(Ignores variance, so really more like 30-60 ms, probably)".
Decisions as records: Nygard 2011. Michael Nygard's post Documenting Architecture Decisions (Cognitect, 15 November 2011) proposed keeping "a collection of records for 'architecturally significant' decisions: those that affect the structure, non-functional characteristics, dependencies, interfaces, or construction techniques", each with Title, Context, Decision, Status and Consequences. Martin Fowler's bliki entry Architecture Decision Record (24 March 2026) describes an ADR as "a short document that captures and explains a single decision relevant to a product or ecosystem".
Targets, not hopes: Google SRE, 2016. The SRE book's chapter on service level objectives starts step 1's non-functional requirements where they belong: "Start by thinking about (or finding out!) what your users care about, not what you can measure." Its Embracing Risk chapter turns availability into a budget ("a system with an availability target of 99.99% can be down for up to 52.56 minutes in a year") and its capacity-planning case study (Auxon) states the principle behind writing intent rather than machine counts: "Specify the requirements, not the implementation."
Design docs: Google, described 2020. Malte Ubl's Design Docs at Google lists the sections that became the template on this page: context and scope, goals and non-goals, the actual design (with a system-context diagram, APIs and data storage), alternatives considered, and cross-cutting concerns. It also bounds the effort: "around 10-20ish pages" for a larger project, or a "1-3 page 'mini design doc'" for incremental work.
The interview framework. Alex Xu's System Design Interview (chapter "A Framework For System Design Interviews", read on ByteByteGo; secondary source, a book for interview preparation) fixed the four-step shape used in interviews, with time allocation for a 45-minute session. We follow its order and rename the steps to match how design docs are written.
Reviews as conversations: AWS Well-Architected. The AWS Well-Architected Framework describes its review as "a constructive conversation about architectural decisions, and is not an audit mechanism" and lists six pillars (operational excellence, security, reliability, performance efficiency, cost optimization, sustainability), a useful checklist for step 1's non-functional requirements. Its design principles start with "Stop guessing your capacity needs", which in a design doc means step 2.
Year Idea What it gave the method
1 2002 Norvig's "approximate timing" table Latency numbers for step 2
2 - Dean's "Numbers Everyone Should Know" Back-of-the-envelope as a skill
3 2011 Nygard's ADRs Step 4 decisions with context and consequences
4 2013 Dean & Barroso, The Tail at Scale Percentiles, not averages, in the estimate
5 2016 Google SRE book: SLOs, error budgets, Auxon Non-functional requirements as numbers
6 2020 Ubl, Design Docs at Google The design doc template and "non-goals"
7 2020 Xu's 4-step interview framework Time boxes for a 45-minute session
8 2026 Fowler's ADR bliki entry; AWS WA (updated) Short records; reviews as conversationsThe concept catalogue
Each block follows the same order: plain words, the usual wrong belief, a definition, a sequence, real scenarios, what tools or products give you, and how to do it. The blocks are grouped by step.
Step 1: Functional requirements and scope Must-know
In plain words: the list of things a user (or another system) can do with what you build, written as verbs: "post", "read my feed", "request a ride".
Common misunderstanding: "More features make a better answer." Each feature is a path through the system that must be estimated, designed and defended. In an interview, three core features done well beat ten done vaguely; at work, every extra feature is a team-month.
Definition: functional requirements describe observable behaviour: inputs, outputs and rules ("a driver holds at most one trip"). They become API endpoints in step 3 and data flows in step 3's diagrams. Requirements that describe how well the system behaves (fast, available, consistent) are non-functional and belong to the next block.
You Interviewer / product owner
1 "Is it mobile, web or both?" "Both."
2 "Which features matter most?" "Post, and see friends' posts."
3 "Ordering: newest first or ranked?" "Newest first, to keep it simple."
4 "Images and video?" "Images; video later."
5 writes: F1 post (text + image), F2 read feed (reverse chronological, paginated)
6 writes: OUT ranking, video, comments, likes, notificationsReal scenario: a payments team asked for "a ledger" discovers in step 1 that refunds and partial captures are in scope but multi-currency is not; a "chat" prompt turns out to need group chats of 100 but not channels of 100,000; a "URL shortener" needs custom aliases but not analytics.
What provides it:
| Practice | What it adds | Source |
|---|---|---|
| User journeys / use cases | One path per feature, tested end to end | Requirements engineering (Quality attributes) |
| Goals in a design doc | Short list agreed by reviewers | Ubl, Design Docs at Google |
| Acceptance criteria | Testable statement per feature | Agile practice |
| Xu's question list | "What specific features are we going to build?" | ByteByteGo (secondary) |
How to do it: write three to five numbered requirements (F1, F2...), each one sentence with a verb; ask "who calls it, how often, what do they get back"; mark the one or two that carry the business (the core paths you will draw in data flow).
Non-functional requirements: availability target, SLO, latency, durability Must-know
In plain words: how well the system must do its job: how fast, how often up, how much data it may lose, how stale it may be, how secure and how cheap.
Common misunderstanding: "It should be highly available, fast and scalable." Those words are not requirements; nobody can design to them or test them. A requirement has a number and a scope: "feed read p99 under 300 ms, measured at the load balancer, over 28 days".
Definition: a non-functional requirement (quality attribute) is a measurable target on a property of the system. The SRE book's vocabulary makes them precise: an SLI is the measured indicator (latency, error rate, throughput, availability), an SLO is the target on it, and the error budget is what the target leaves you ("An error budget is just an SLO for meeting other SLOs!"). Prefer percentiles to means: "We generally prefer to work with percentiles rather than the mean (arithmetic average) of a set of values." The full treatment is in SLAs, SLOs, SLIs & Error Budgets.
Requirement as said Requirement as written (testable)
1 "fast" feed read p99 < 300 ms at the LB, 28-day window
2 "always up" 99.95% of feed reads succeed (262.8 min/year budget)
3 "never lose data" acknowledged posts survive a zone loss (RPO 0 within region)
4 "real-time" new post visible to friends within 5 s, p99
5 "scalable" design holds at 10x DAU with only added nodes
6 "secure" authN on every call; PII encrypted at restReal scenario: an internal admin tool gets 99.5% and no on-call; a checkout API gets 99.99% and multi-zone; a batch reporting job gets "finished by 06:00" rather than a latency target; Google's Ads Frontend once used scheduled maintenance windows counted "as planned downtime, not unplanned downtime" (SRE book, Embracing Risk).
What provides it:
| Attribute | Typical SLI | Design lever | Product examples |
|---|---|---|---|
| Availability | Successful requests / valid requests | Redundancy N+2, multi-zone, failover | AWS ALB across AZs, PostgreSQL with Patroni, Redis Sentinel |
| Latency | p50/p99/p99.9 at a named point | Caches, fewer hops, async writes | Redis, CDN (Cloudflare, CloudFront), read replicas |
| Durability | Data loss events, RPO | Replication factor, backups, WAL archiving | PostgreSQL synchronous replicas, S3 |
| Consistency | Staleness, read-your-writes violations | Leader reads, quorum, conditional writes | PostgreSQL primary, DynamoDB strongly consistent reads |
| Throughput | Requests or bytes per second | Partitioning, batching | Kafka partitions, Redis Cluster |
| Cost | Cost per request or per user | Right-sizing, tiered storage | S3 storage classes, spot instances |
| Security, operability, sustainability | Audit findings, toil, utilisation | Least privilege, automation, utilisation | AWS Well-Architected pillars |
How to do it: for each core path write latency (percentile + where measured), availability (target + window), consistency (how stale, for whom) and durability; pick the availability target from the business cost of downtime, not from what the current system happens to achieve (the first of the SRE book's target-setting tips; the others include "Have as few SLOs as possible" and "Keep a safety margin"); check the six Well-Architected pillars for anything you forgot.
Out of scope, non-goals and assumptions Must-know
In plain words: what you will deliberately not build, and the facts you are taking as given because nobody told you otherwise.
Common misunderstanding: "Out of scope is what I did not have time for." It is a decision, written early, that keeps the design small. Ubl's definition is precise: non-goals "aren't negated goals like 'The system shouldn't crash', but rather things that could reasonably be goals, but are explicitly chosen not to be goals."
Definition: out of scope lists features and qualities excluded from this design; assumptions list unverified facts the design depends on (traffic, sizes, existing systems). Xu's advice for interviews applies at work: when the other side asks you to assume, "write down your assumptions on the whiteboard or paper. You might need them later." Assumptions are the inputs of step 2; when one turns out wrong, the estimate tells you which part of the design moves.
Line in the doc Kind Consequence if wrong
1 OUT: ranking, ads, notifications scope new services later, not now
2 OUT: multi-region writes scope single-leader DB is fine
3 ASSUME: 10 M DAU, 10 reads + 1 post per day traffic QPS, servers
4 ASSUME: 200 friends on average, 5,000 max shape fan-out cost, hot users
5 ASSUME: posts 1 KB, images go to object storage size storage, bandwidth
6 ASSUME: PostgreSQL and Redis are already run context no new datastore without ADRReal scenario: an assumed "1 KB per post" becomes 40 KB once link previews are embedded, multiplying storage; "single region" quietly becomes "EU data stays in the EU", which is a new requirement, not an assumption; "celebrities are rare" fails on launch day when 200 brands join.
What provides it:
| Artifact | Where it lives | Owner |
|---|---|---|
| Goals and non-goals | Design doc (Ubl) | Author, agreed in review |
| Assumptions table with sources | Design doc, step 2 inputs | Author, product, analytics |
config/capacity.php (this chapter) | Repository, reviewed in pull requests | Team |
| Context section of an ADR | ADR (Nygard: "The language in this section is value-neutral") | Decision owner |
How to do it: write at least three out-of-scope lines and every number you used as an assumption with its source ("analytics dashboard, October" or "guess"); in the Go linter a doc without them fails with SCOPE003 and SCOPE004.
Workload shape: users, regions, read/write ratio, consistency requirement Must-know
In plain words: not just how much traffic, but what kind: who sends it, from where, how much is reading versus writing, and how fresh each read must be.
Common misunderstanding: "One QPS number describes the load." A system with 3,500 reads a second and 350 writes a second is a different system from one with 174 reads and 125,000 writes a second, even though the second has more "QPS". The SRE book warns about the same trap in capacity planning: "Different queries can have vastly different resource requirements."
Definition: the workload shape is the tuple (actors, regions, read/write ratio, request mix, hot keys, consistency requirement per path). The consistency requirement says, for each read, which writes it must see: read-your-writes for a user's own post, seconds of staleness for friends' feeds, linearizable for "is this driver free?". Consistency Models and CAP & PACELC own the theory.
Path Reads/s peak Writes/s peak Consistency needed Region
1 Feed read 3,472 - seconds stale is fine home region
2 Publish post - 347 durable on ack, own post RYW home region
3 Fan-out to feeds - 69,792 eventual (5 s target) home region
4 Driver location - 125,000 last write wins, seconds old per city
5 Assign driver to ride 174 174 strong: one trip per driver per cityReal scenario: a product catalogue (read-heavy, 100:1, cache everything); IoT telemetry (write-heavy, append-only, time-partitioned); a bank ledger (balanced, strongly consistent, audited); a ticketing on-sale (read-heavy until the gate opens, then a write storm on a few hot rows, see Ticketing).
What provides it:
| Shape | Typical choice | Products |
|---|---|---|
| Read-heavy, tolerant of staleness | Cache-aside, read replicas, CDN | Redis, PostgreSQL replicas, CloudFront |
| Write-heavy, append-only | Log or wide-column store, batching | Kafka, Cassandra, ClickHouse |
| Strong consistency on few keys | Single leader, conditional writes | PostgreSQL, DynamoDB conditional writes, etcd |
| Global users | GeoDNS, regional stacks, data residency | Route 53, Cloudflare |
How to do it: add a column for each core path with reads/s, writes/s and the consistency it needs; mark hot keys (celebrities, flash-sale items, big cities); the ratio and consistency column decide most of step 3.
Step 2: QPS from DAU and MAU, peak-to-average Must-know
In plain words: turn "10 million people use it a day" into "how many requests per second at the worst minute".
Common misunderstanding: "Average QPS is the load." Servers fall over at the peak, not at the average. Another one: "MAU is the user count to use." Daily load comes from DAU; MAU is converted with the DAU/MAU ratio (stickiness).
Definition: average QPS = (DAU x actions per user per day) / 86,400; peak QPS = average x peak-to-average factor. When only MAU is known, DAU = MAU x (DAU/MAU). The factor comes from real traffic graphs when you have them and from the product's rhythm when you do not (a global product's daily curve versus a city's rush hour or a ticket on-sale). Capacity Estimation owns the method.
Input Arithmetic Result
1 10 M DAU x 10 feed loads/day 100 M / 86,400 1,157 reads/s average
2 10 M DAU x 1 post/day 10 M / 86,400 116 writes/s average
3 peak factor 3 1,157 x 3 ; 116 x 3 3,472 reads/s ; 347 writes/s
4 read/write ratio 1,157 / 116 10:1
5 if only MAU = 20 M and DAU/MAU = 0.5 20 M x 0.5 10 M DAU (same as above)Real scenario: a sports app's peak factor is 20 during a final; a B2B tool has near-zero traffic at night and a 9:00 spike per time zone; a game launch makes "day one" the peak for months; Stripe's rate limiter post mentions adding "the ability to briefly burst above the cap for sudden spikes in usage during real-time events (e.g. a flash sale.)".
What provides it:
| Source of the numbers | What you get | Caveat |
|---|---|---|
| Product analytics (DAU, MAU, actions) | Inputs | Bots and retries not included |
| Load balancer metrics (AWS ALB, NGINX, Envoy) | Real peak and ratio | Only for systems that exist |
| Google SRE advice | Measure capacity "directly in available resources" | QPS is a proxy; requests differ in cost |
This chapter's Go estimate.Run and Laravel design:check | Reproducible arithmetic | Garbage in, garbage out |
How to do it: compute average and peak for reads and writes separately; state the peak factor and where it came from; remember 86,400 is close to 100,000 for head arithmetic (1 M per day is about 12/s).
Storage estimate and retention Must-know
In plain words: how many bytes you keep: what one record weighs, how many arrive per day, how long you keep them and how many copies exist.
Common misunderstanding: "Storage is cheap, skip it." Storage size decides whether one database node can hold the data, how long a backup or a replica rebuild takes, and how much the monthly bill is. Forgetting replication and retention is the usual 3x-10x error.
Definition: storage = writes per day x bytes per record x retention days x replication factor, plus indexes and engine overhead. Separate hot data (recent, on fast disks or in memory) from cold data (archive, object storage). The Capacity Estimation storage block shows row overhead and index sizes for PostgreSQL.
Item Per day Retention Copies Total
1 News feed posts (1 KB) 10 GB 5 years 3 54.75 TB
2 News feed images (10% x 500 KB) 500 GB 5 years object storage (11 nines durability class)
3 Ride location points (50 B) 360 GB 30 days 3 32.4 TB
4 Rate-limit buckets (200 B, 1 M) state, not log - 2 400 MB in memoryReal scenario: a logging pipeline that keeps everything for 13 months by default; a chat system where media dwarfs text by 100x; a time-series database that needs downsampling after 30 days; GDPR deletion that turns "append-only forever" into a requirement change.
What provides it:
| Tier | Products | Typical use |
|---|---|---|
| In-memory | Redis, Memcached | Live state, hot caches |
| Relational / document | PostgreSQL, MySQL, MongoDB | Source of truth for entities |
| Wide-column / log | Cassandra, Kafka with retention | High write rate, time-ordered data |
| Object storage | Amazon S3, GCS, MinIO | Media, archives, data lake |
How to do it: estimate per record (count bytes per field), multiply out, then decide the tier and the retention policy per data type; write retention into the requirements, because "keep forever" is a decision with a cost.
Bandwidth Important
In plain words: how many bytes per second go in and out of the system at peak.
Common misunderstanding: "Bandwidth only matters for video." A JSON API at a few thousand requests a second with 20 KB responses already needs more than half a gigabit per second, and links, load balancers and cloud egress bills are counted in exactly that.
Definition: ingress = peak write QPS x request bytes; egress = peak read QPS x response bytes; convert bytes to bits (x 8) to compare with link capacity. Move large static payloads to a CDN so your servers send references, not bytes. CDNs and Object Storage own the mechanics.
Path Peak rate Payload Bytes/s Bits/s
1 Feed read (text) 3,472/s 20 KB 69.4 MB/s 556 Mbit/s
2 Feed images via CDN - - CDN egress, not app egress
3 Driver location ingest 125,000/s ~200 B 25 MB/s 200 Mbit/s (assumed wire size)
4 Rate-limit checks to Redis 17,361/s 150 B 2.6 MB/s 21 Mbit/sReal scenario: an image service whose app servers stream originals and saturate their NICs; a mobile API whose egress bill exceeds compute; a cross-region replication link sized for average, not peak.
What provides it: CDNs (Cloudflare, Fastly, Amazon CloudFront) for static and cacheable content; compression (gzip, Brotli, zstd) for JSON; pagination and field selection (GraphQL, sparse fieldsets) to cut payload size; presigned URLs on S3 so uploads bypass the app.
How to do it: compute egress for the biggest read path and ingress for the biggest write path; decide which bytes never touch the app servers.
Cache sizing and the 80/20 rule Important
In plain words: keep the small part of the data that gets most of the reads in memory, and estimate how big that part is.
Common misunderstanding: "Cache 20% of the daily read volume." That popular interview formula counts the same hot item once per read, so it is an upper bound, sometimes 10x too big. In the news feed it gives 400 GB, while the actual hot set (the latest 500 post IDs of each active user) is about 40 GB before Redis overhead.
Definition: the 80/20 rule (the Pareto principle) says a small fraction of items receives most accesses. Two estimates bound the cache: the request-volume bound (daily read bytes x 0.2) and the distinct-items bound (distinct hot items x item size x overhead). Use the smaller one that still meets the hit-ratio target, then measure. Caching owns eviction, invalidation and stampedes.
Method Arithmetic Result
1 Request volume x 0.2 100 M reads x 20 KB x 0.2 400 GB (upper bound)
2 Distinct items 10 M active users x 500 ids x 8 B 40 GB raw
3 Plus Redis overhead (assume 2x) 40 GB x 2 ~80 GB
4 Hot posts of the day 10 GB/day of posts x 0.2 2 GB
5 Decision Redis Cluster, 4 x 25 GB nodes + replicasReal scenario: a product catalogue where 5% of SKUs get 80% of views; a feed where the hot set is "the last day"; a URL shortener where viral links are a tiny fraction of keys but most of the traffic.
What provides it:
| Product | Sizing note |
|---|---|
| Redis | maxmemory + eviction policy (allkeys-lru, allkeys-lfu); per-key overhead matters for small values |
| Memcached | Slab allocator; item size classes waste some memory |
| CDN cache (Cloudflare, CloudFront) | Sized by the provider; you control TTL and cache keys |
In-process (Go map with LRU, Laravel array store) | Per-instance, so N copies |
How to do it: compute both bounds, state the hit-ratio target (for example 95%), pick node count from the smaller bound with headroom, and plan to measure the real hit ratio in production.
Server count, headroom and N+2 Important
In plain words: how many machines you need at peak, plus enough spare that losing one or two does not hurt.
Common misunderstanding: "Peak QPS divided by what one server can do." That runs every server at 100% at peak and leaves nothing for a lost node, a deploy or a bad query.
Definition: servers = ceil(peak QPS / (per-server QPS x target utilisation)) + spare nodes. Target utilisation of 50-70% leaves headroom; N+2 means you can lose one node to failure while another is down for maintenance. The SRE book's capacity-planning chapter uses exactly this kind of intent: "I want to meet service Foo's demand in each geographic region, and have N + 2 redundancy" (quoted with a straight apostrophe). Per-server QPS must come from a load test of your code, not from a blog.
Step News feed Ride ingest
1 Peak total QPS 3,472 + 347 = 3,819 125,000 + 174
2 Per-server QPS (load-tested assumption) 500 10,000
3 Target utilisation 0.6 0.6
4 ceil(peak / (per-server x util)) ceil(12.7) = 13 ceil(20.9) = 21
5 + N+2 15 23Real scenario: an autoscaling group whose minimum equals average load and fails the first spike; a three-node cluster that loses quorum during a rolling restart; a team that sized by CPU and ran out of database connections first (Connection Pooling).
What provides it: Kubernetes HPA and AWS Auto Scaling (scale on CPU, request rate or custom metrics); PodDisruptionBudgets for maintenance headroom; load-testing tools (k6, hey) for per-server capacity; Scaling Strategies and Capacity Planning & DR for the longer view.
How to do it: count servers per tier (app, cache, database, workers), each from its own bottleneck resource; write the per-server number as an assumption with "load test pending" until measured.
Latency numbers and powers of two Must-know
In plain words: a handful of numbers that let you reason about speed and size without a calculator: memory is fast, disks and networks are slow, a cross-continent round trip is a sixth of a second.
Common misunderstanding: "Memorise exact numbers." Hardware changes; the ratios are what matter. Main memory is about 200x an L1 hit; a same-datacenter round trip is about 5,000x a memory reference; a transatlantic round trip is 300x a same-datacenter one.
Definition: Dean's slide "Numbers Everyone Should Know" (Stanford CS295):
| Operation | Time (Dean's slide) | Use in step 2 |
|---|---|---|
| L1 cache reference | 0.5 ns | In-process work is free at this scale |
| Main memory reference | 100 ns | A Redis value read is dominated by the network, not memory |
| Send 2K bytes over 1 Gbps network | 20,000 ns | Payload size matters at high QPS |
| Read 1 MB sequentially from memory | 250,000 ns | Scanning in memory is cheap |
| Round trip within same datacenter | 500,000 ns | Each synchronous hop costs about 0.5 ms |
| Disk seek | 10,000,000 ns | Random disk reads cost 10 ms (spinning disks) |
| Read 1 MB sequentially from disk | 30,000,000 ns | Sequential beats random |
| Send packet CA->Netherlands->CA | 150,000,000 ns | Cross-continent sync calls are expensive |
Powers of two for sizes: 2^10 = 1,024 (KiB, "thousand"), 2^20 (MiB, million), 2^30 (GiB, billion), 2^40 (TiB, trillion), 2^50 (PiB). Disks, networks and cloud bills use decimal units (1 KB = 1,000 B); RAM uses binary units. The difference is 2.4% at KB and 10% at TB, below the precision of any estimate.
Question Arithmetic Answer
1 Can a 3-hop sync chain meet 300 ms p99? 3 x 0.5 ms in-DC + work yes, network is not the problem
2 Can a US user call an EU database per request? 150 ms per round trip not inside a 300 ms budget with 2 calls
3 How long to read 1 GB from memory? 1,000 x 250 us 0.25 s
4 How many 8-byte ids fit in 64 GiB? 2^36 / 2^3 about 8.6 billionReal scenario: an API that calls a cross-region service twice per request and can never meet its SLO; a cache placed in another zone that adds more latency than it saves; a sort that is CPU-bound, not disk-bound, as Dean's quicksort example shows ("it should take ~30 seconds to sort 1 GB on one CPU").
What provides it: Dean's slides and Norvig's table for orders of magnitude; Colin Scott's interactive page for a modelled year-by-year view; your own measurements (ping, redis-benchmark, pgbench) for real values. The percentile side (p99 and fan-out amplification) is in Latency Budgets & Tail Latency: Dean and Barroso show that if one server in 100 is slow, a request that fans out to 100 servers is slow 63% of the time.
How to do it: keep the table nearby, round aggressively, and always say "about"; spend precision only where it changes the design.
Step 3: API design first Must-know
In plain words: before drawing boxes, write the handful of calls a client makes, with their inputs and outputs.
Common misunderstanding: "The API is an implementation detail for later." The API is the contract with every client and it fixes the data each path needs. Designing it first makes the data model and the components follow from it instead of the other way round.
Definition: an API sketch lists, per functional requirement, the operation (HTTP method and path, gRPC method, or message), the key parameters, the response shape, pagination, idempotency and error behaviour. Ubl's advice for design docs: sketch it, but "withstand the temptation to copy-paste formal interface or data definitions". REST API Design, API Idempotency and gRPC own the details.
Requirement Operation Notes
1 F1 publish post POST /v1/posts {body, media_id} Idempotency-Key header; 201 + post_id
2 F2 read feed GET /v1/feed?cursor=...&limit=20 cursor pagination; 200 + next_cursor
3 F3 upload image POST /v1/media -> presigned S3 URL bytes bypass the API
4 Errors 400 validation, 401, 429 + Retry-After RFC 6585 defines 429Real scenario: a feed API with offset pagination that becomes slow and inconsistent at page 50 (Pagination); a payment API without idempotency keys that double-charges on retry; a ride API where "accept offer" must be conditional on the driver still being free.
What provides it:
| Style | Fits | Product / spec |
|---|---|---|
| REST over HTTP | Public APIs, CRUD, caching | OpenAPI 3.1 |
| gRPC | Internal, low latency, streaming | Protocol Buffers |
| GraphQL | Many clients with different shapes | GraphQL spec |
| Events/messages | Async side effects | AsyncAPI, Kafka, RabbitMQ |
How to do it: one line per requirement with method, path, key fields, pagination and idempotency; mark which calls are on the latency-critical path; the Go design-doc linter fails a doc without an API sketch (HLD001).
Data model Must-know
In plain words: what you store, under which key, in which kind of store, chosen so that the core queries are cheap.
Common misunderstanding: "Choose the database first, then design tables." The access patterns from the API choose the store: which key you look up by, which range you scan, which rows change together.
Definition: for each entity: its key (and partition key if it will ever be sharded), the main fields, the indexes that serve the API, the store, and the consistency it needs. Ubl again: discuss "how and in what rough form" data is stored and avoid pasting full schemas. Choosing a Database and Schema Design go deeper; Database System Design works the same method from the database side.
API call Query it implies Entity / key / store
1 GET /v1/feed latest 20 post ids for user U, then posts feed:{U} list in Redis; posts by post_id
2 POST /v1/posts insert post, find followers of author A posts (PostgreSQL); follows index on followee
3 fan-out for each follower F: push post_id feed:{F} LPUSH + LTRIM 500
4 celebrity merge latest posts of followed celebrities posts index (author_id, created_at DESC)Real scenario: a chat store keyed by (channel, time bucket) so reads are one partition; an order table whose status changes need a transaction with stock; a location store that keeps only the latest point per driver in memory and the history in a log.
What provides it: PostgreSQL (relations, transactions, partial and composite indexes), Redis (lists, sorted sets, GEO), Cassandra/DynamoDB (partition key + sort key), object storage for blobs. The SQL for each worked example is in Solving the classic problems.
How to do it: derive one access pattern per API call, then the key and index that serve it; note which entities must change atomically together, because that is where you need a transaction or a conditional write.
Component diagram Important
In plain words: the boxes (clients, load balancer, services, stores, queues, caches, CDN) and the lines between them, at the level where each box has one job.
Common misunderstanding: "More boxes look more scalable." Each box is something to deploy, monitor, secure and page someone for. A box earns its place by a requirement or a number.
Definition: a component diagram shows runtime components and their connections; Ubl recommends a system-context diagram that "shows the system as part of the larger technical landscape". The diagram is followed by the data flows that walk across it. Xu's list of typical components ("clients (mobile/web), APIs, web servers, data stores, cache, CDN, message queue, etc.") is a palette, not a checklist.
Box Justified by
1 CDN + object storage image bytes (500 GB/day) must not pass through app servers
2 Load balancer more than one app server (15 at peak, N+2)
3 Post / feed services different scaling (writes vs reads), still one deployable at first
4 Kafka + fan-out workers 69,792 feed writes/s must not block POST /v1/posts
5 Redis feed lists hot set ~40 GB, p99 300 ms target
6 PostgreSQL + replicas 54.75 TB over 5 years, partitioned by monthReal scenario: the news feed diagram; a rate limiter that is a middleware plus Redis, not a new service; a ride-matching system where the matcher and the location ingest are separate because their load differs by 700x.
What provides it: C4 model diagrams (context, container), UML component and deployment diagrams (UML in Practice), Kruchten's physical view (4+1); tools such as Excalidraw, draw.io, Mermaid or Structurizr.
How to do it: draw the smallest diagram that serves the core paths; next to each box, write the requirement or number that justifies it; if you cannot, delete the box.
Data flow: the read path and the write path Must-know
In plain words: walk one request through the boxes, step by step, for each core path, and include the path that changes data, not only the one that shows it.
Common misunderstanding: "The write path is one arrow into the database." Writes carry the expensive parts: validation, transactions, replication, index updates, fan-out, events, cache invalidation. In the news feed the write path, not the read path, sets the largest number on the page.
Definition: a data flow is a numbered sequence of hops for one operation with the store touched at each hop, the synchronous/asynchronous boundary, and where the user gets the answer. Draw at least one read path and one write path per core feature.
Write path: POST /v1/posts Read path: GET /v1/feed
1 LB -> post service LB -> feed service
2 BEGIN; INSERT post; INSERT outbox; COMMIT LRANGE feed:{U} 0 19 (Redis)
3 201 to the user <- synchronous boundary merge celebrity posts (posts index)
4 relay -> Kafka PostCreated MGET post:{id} from cache, misses from replica
5 fan-out workers: followers of A, LPUSH each feed 200 + 20 posts + next_cursor
6 skip if A has > 10k followers (pulled at read)Real scenario: a "like" button whose write path updates a counter row that becomes a hot spot (Sharded Counters); an order placement whose write path must reserve stock and emit an event atomically (Outbox); a profile edit that must invalidate caches in three places.
What provides it: sequence diagrams (UML), the transactional outbox for reliable events, Kafka or RabbitMQ for the asynchronous part, Redis for derived views. The Go linter fails a doc without a write path (HLD002).
How to do it: for each core feature, write the read and the write flow as numbered steps; mark the synchronous boundary (where the user is answered); put the peak rate next to every arrow that crosses a store.
Step 4: Bottlenecks and single points of failure Must-know
In plain words: find the one part that saturates first as load grows, and the one part whose failure stops everything.
Common misunderstanding: "The database is always the bottleneck." Often it is, but the numbers decide: in the news feed it is the fan-out write rate; in ride matching it is location ingest; in a rate limiter it is the latency budget of one extra hop.
Definition: a bottleneck is the resource that limits throughput or latency first (CPU, memory, disk IOPS, connections, network, a lock, a single partition). A single point of failure (SPOF) is a component whose loss makes a core path unavailable. Both are found by walking each data flow with the step 2 numbers.
Walk: news feed at 10x Resource Limit reached?
1 3,472 -> 34,720 feed reads/s Redis (cluster) add shards
2 347 -> 3,470 posts/s PostgreSQL WAL single primary still fine
3 69,792 -> 697,920 list writes/s Redis + workers yes: celebrity threshold, batching
4 one Kafka cluster in one region SPOF for fan-out posts still accepted; feeds lag
5 one PostgreSQL primary SPOF for publish failover ~30 s; clients retryReal scenario: a single NAT gateway that every service uses for egress; a Redis instance without a replica that holds sessions; a cron host that runs billing; a hot partition key in DynamoDB (Sharding at System Level).
What provides it:
| SPOF | Usual fix | Products |
|---|---|---|
| One app server | Two or more behind a load balancer | AWS ALB, NGINX, HAProxy |
| One database primary | Replica + automatic failover | Patroni, Amazon RDS Multi-AZ |
| One cache node | Replica + Sentinel or Cluster | Redis Sentinel, Redis Cluster |
| One zone or region | Multi-AZ, then multi-region | AWS AZs, Route 53 failover |
| One scheduler | Leader election | Leader Election |
How to do it: list per component "what saturates first" and "what happens if it dies"; pick the top two or three as deep dives.
Trade-off tables, deep dives and ADRs Must-know
In plain words: for each important choice, put the real options side by side, pick one, and write down what you gain, what you give up, and when you would change your mind.
Common misunderstanding: "A decision with only one option is a decision." If there was no alternative, there was no decision, only a default. Ubl calls the alternatives section "one of the most important ones as it shows very explicitly why the selected solution is the best given the project goals".
Definition: a deep dive is focused work on one bottleneck or risky component. A trade-off table compares options against the requirements. An ADR records the outcome: Nygard's format has Title, Context ("the forces at play"), Decision ("We will ..."), Status (proposed, accepted, deprecated, superseded) and Consequences ("All consequences should be listed here, not just the 'positive' ones"). Fowler adds that ADRs "should not be modified if the decision is changed, but linked to a superseding decision". Architecture Decisions owns the process.
Deep dive: fan-out (news feed)
1 Context: 10:1 reads, 200 friends average, 5,000 max, p99 300 ms, 5 s freshness
2 Option A fan-out on write: fast reads; 69,792 writes/s; celebrities explode
3 Option B fan-out on read: no write amplification; each read merges 200 timelines
4 Option C hybrid: write for normal authors, read for authors above 10k followers
5 Decision: C. Consequence: two code paths; threshold is a tunable; monitor both
6 Status: accepted. Revisit if ranking is added (ranking changes the read path)Real scenario: fan-out on write vs read (Feeds); token bucket vs sliding window (Rate Limiting); compare-and-set vs distributed lock for assignment (Distributed Locking); PostgreSQL vs Cassandra for posts.
What provides it: ADR tools and templates (Nygard format, MADR, adr-tools), the "Alternatives considered" section of a design doc, review meetings; AWS Well-Architected reviews as "constructive conversations about architectural decisions, not audits".
How to do it: two or three deep dives, each ending in an ADR with at least two options; the linter raises DEC001 for a one-option decision.
Failure modes Important
In plain words: for each component, what goes wrong, what the user sees, and what the system does about it.
Common misunderstanding: "We will add retries." Retries without idempotency duplicate work; retries without budgets turn a slow dependency into an outage (Cascading Failures, Timeouts, Retries & Jitter).
Definition: a failure mode table lists component, failure (crash, slow, partition, corrupt data, overload), user impact, detection and mitigation. Xu's wrap-up advice: "Error cases (server failure, network loss, etc.) are interesting to talk about."
Event Without a plan With a plan
1 Redis (rate limiter) slow, 50 ms every API call +50 ms 5 ms timeout, fail open, alert
2 Fan-out workers lag 10 min feeds look empty, users repost Kafka buffers; lag alert; scale consumers
3 PostgreSQL primary fails POST /v1/posts 500s, duplicates failover; client retries same Idempotency-Key
4 Matcher crashes mid-offer driver stuck OFFERED forever offer expiry resets after 10 sReal scenario: Stripe's rate-limiter advice: "if there were bugs in the rate limiting code (or if Redis were to go down), requests wouldn't be affected" (fail open); a cache outage that sends 100% of reads to a database sized for 5%; a region loss that tests the disaster recovery plan for the first time.
What provides it: circuit breakers (Circuit Breaker), bulkheads and graceful degradation (Bulkheads), load shedding (Load Shedding), chaos experiments (Chaos Engineering).
How to do it: one row per component on a core path; decide fail open or fail closed explicitly for every dependency; the linter raises DEC003 when the table is empty.
Evolution and what you would monitor Important
In plain words: how the design changes at 10x and 100x, and which few numbers would tell you it is time.
Common misunderstanding: "Design for 100x now to be safe." That is premature optimisation: more cost, more operations, slower delivery, for traffic that may never come. Design for the current estimate with a written plan for the next step and a metric that triggers it.
Definition: the evolution section lists the next two scale steps and what changes at each (shard by key, add a region, split a service); the monitoring section lists the SLIs of each core path plus the leading indicators of the bottlenecks (replica lag, consumer lag, cache hit ratio, connection pool saturation). AWS's design principle "Consider evolutionary architectures" says the same: decisions should not be "static, onetime events".
Metric (news feed) Today Trigger Next step
1 Feed read p99 120 ms > 250 ms for a week more cache, check fan-in merge
2 Kafka consumer lag (fan-out) < 1 s > 5 s at peak more partitions and workers
3 PostgreSQL primary write IOPS 20% > 60% partition by month, then shard by author
4 Redis memory per node 40% > 70% add shard
5 Celebrity merge time 8 ms > 50 ms lower follower threshold or precomputeReal scenario: a team that set "shard when the primary hits 60% IOPS" and did it calmly a year later; a feed that added ranking and had to rewrite the read path; a ride system that split cities into separate cells once the largest city outgrew one Redis.
What provides it: Prometheus and Grafana, OpenTelemetry traces (Observability), SLO alerting (Alerting).
How to do it: list four or five metrics with today's value, a trigger and the next step; the linter raises DEC004 when nothing is monitored.
The design doc as the output Important
In plain words: one short document that holds the four steps, the decisions and the open questions, written before the code and kept as the system's memory.
Common misunderstanding: "A design doc is an implementation manual." Ubl: a doc that "basically says 'This is how we are going to implement it' without going into trade-offs, alternatives, and explaining decision making" should have been code instead.
Definition: a design doc has context and scope, goals and non-goals, the design (diagrams, API, data storage), alternatives considered, cross-cutting concerns (security, privacy, observability), and its lifecycle: "Creation and rapid iteration", "Review (may be in multiple rounds)", "Implementation and iteration", "Maintenance and learning". ADRs capture the individual decisions; the design doc links them.
Week Doc state What happens
1 0 draft: scope + estimate author + 1-2 teammates iterate
2 1 + high-level design + ADR drafts shared with the wider team; comments
3 2 review meeting cross-cutting concerns checked; ADRs accepted
4 3+ implementation doc updated when reality differs ("amendments")
5 +1y re-read by the author "What did you get right? What did you get wrong?"Real scenario: Google's "Where is the design doc?" as the first question about an unfamiliar system (Ubl); Uber's RFCs, later called ERDs (mentioned in the comments under Ubl's post, so treat as secondary); the Go generator that renders the three worked examples on this page into Markdown skeletons.
What provides it: Google Docs or a Markdown file in the repository, review tools, ADR directories (doc/arch/adr-NNN.md in Nygard's proposal), this chapter's designdoc.Render.
How to do it: use the template; aim for a "mini design doc" of 1-3 pages for most features and 10-20 pages only for a large system.
Interview mode vs real design work Good to know
In plain words: the same four steps, compressed into 45-60 minutes and spoken aloud.
Common misunderstanding: "There is a right answer." Xu: "There is neither the right answer nor the best answer." Interviewers grade the process: questions asked, numbers used, trade-offs named, reaction to feedback.
Definition: interview mode keeps the steps and shrinks each one: a few minutes of questions, a quick estimate only where it changes the design, a diagram on the whiteboard, and one or two deep dives chosen with the interviewer. Real design work adds data from production, written review, ADRs and a migration plan.
Minute Interview (45 min) Real design (2-3 weeks)
1 0-8 Scope: questions, write F1..F3, NFRs, OUT Interviews with product, analytics, SRE
2 8-13 Estimate: QPS, storage, the surprise Query real dashboards, load test
3 13-25 API, data model, diagram, both flows Design doc draft, prototypes
4 25-40 Two deep dives chosen with interviewer Review, ADRs, security/privacy review
5 40-45 Bottlenecks, failure, monitoring, 10x Rollout plan, migration, ownersReal scenario: an interviewer who stops the estimate after one minute ("assume it fits on one machine") because they want the deep dive; a senior candidate expected to drive the deep-dive choice; a real design review that rejects a doc because the estimate is missing.
What provides it: Xu's dos and don'ts ("Always ask for clarification. Do not assume your assumption is correct."; "Don't think in silence."); this page's checklist; practice on the three worked examples.
How to do it: say each step's name as you enter it, write the numbers where both sides can see them, and end with "the two things I would watch in production are ...".
Mechanics
The arithmetic routine
The routine below is the one the Go estimate.Run and the Laravel CapacityEstimator implement. Do it per core path, reads and writes separately.
Step Compute Watch out for
1 DAU MAU x (DAU/MAU), or given Using MAU as daily load
2 avg DAU x actions/user/day / 86,400 Forgetting background calls (sync, polling)
3 peak avg x peak factor (2-3 global, 5-10 local) Average-only sizing
4 fan peak writes x (1 + fan-out) The hidden write path
5 store writes/day x bytes x retention x replicas Indexes (1.5-2x), media vs metadata
6 net peak x payload, x 8 for bits Media through app servers
7 cache min(daily read bytes x 0.2, hot items x size) Repeated reads counted as distinct
8 nodes ceil(peak / (per-node x 0.5-0.7)) + 2 Per-node numbers from blogs, not tests
9 nines (1 - target) x minutes per year Dependencies multiply: 0.999^3 = 0.997Units and conversions
| Quantity | Value | Shortcut |
|---|---|---|
| Seconds per day | 86,400 | About 10^5 |
| Seconds per month (30 d) | 2,592,000 | About 2.5 x 10^6 |
| Seconds per year | 31,536,000 | About 3 x 10^7 |
| 1 M requests/day | 11.6 QPS | About 12 |
| 1 B requests/day | 11,574 QPS | About 12,000 |
| 2^10 / 2^20 / 2^30 / 2^40 | KiB / MiB / GiB / TiB | Thousand / million / billion / trillion |
| 1 Gbit/s | 125 MB/s | Divide bits by 8 |
| 1 KB vs 1 KiB | 1,000 vs 1,024 bytes | Below estimate precision |
Availability table
The SRE book: "Each additional nine corresponds to an order of magnitude improvement toward 100% availability." The minutes below are (1 - target) x 525,600.
| Target | Downtime per year | Per 30 days | Typical use |
|---|---|---|---|
| 99% | 3.65 days | 7.2 hours | Internal tools, batch |
| 99.9% | 8.76 hours | 43.2 minutes | Most business APIs |
| 99.95% | 4.38 hours | 21.6 minutes | Consumer reads (news feed example) |
| 99.99% | 52.56 minutes | 4.32 minutes | Checkout, ride requests |
| 99.999% | 5.26 minutes | 26 seconds | Telecom, core infrastructure |
The SRE book also counts in requests: "a system that serves 2.5M requests in a day with a daily availability target of 99.99% can serve up to 250 errors". A request through three dependencies each at 99.9% is at best 0.999^3, about 99.7%.
Lint codes
The Go linter (designdoc.Lint) and the Laravel validator (AssumptionValidator) print stable codes, so a CI job can fail a pull request that changes a design doc or config/capacity.php without fixing them.
| Code | Raised when | Fix |
|---|---|---|
SCOPE001 | No functional requirements | Write F1..Fn |
SCOPE002 | No availability target or SLO | Add numbers to the NFRs |
SCOPE003 | Out of scope is empty | Name what you will not build |
SCOPE004 | No assumptions | List every number you used and its source |
EST001 | QPS never computed | Run step 2 |
HLD001 | No API sketch | Start step 3 with the API |
HLD002 | No write path | Draw the path that changes state |
DEC001 | A decision has fewer than two options | Add the alternative you rejected |
DEC002 / DEC003 / DEC004 | No decisions / failure modes / monitoring | Fill step 4 |
ANTI001 | Microservices with fewer than 20 engineers | Start with a modular monolith |
ANTI002 | Sharding below 5,000 writes/s and 10 TB | Use one primary, partition later |
ANTI003 | Fan-out multiplies writes more than 10x and no decision mentions it | Size the write path |
CAP001 (Laravel) | Peak writes exceed one primary with no sharding or fan-out plan | Partition or shard |
CAP002 (Laravel) | Cache exceeds one Redis node | Plan a Redis Cluster |
CAP003 / CAP004 (Laravel) | Utilisation above 0.7 / redundancy below N+2 | Add headroom and spares |
The thresholds (20 engineers, 5,000 writes/s, 10 TB) are deliberately conservative planning numbers chosen for this chapter, not industry constants; put your own load-test numbers into SinglePrimaryWriteQPS or CAPACITY_PRIMARY_WRITE_QPS.
Error messages you will see
| Message | Where | Meaning |
|---|---|---|
estimate: invalid workload: "empty" needs DAU > 0, peak >= 1, replication >= 1 | Go estimate.Run | Step 1 numbers missing |
ANTI002 sharding at 3 peak writes/s and 110 GB: premature | Go designdoc.Lint | Box-first design caught |
Unknown system [news-fed] in config/capacity.php. | php artisan design:check news-fed | Typo; fail() exits with code 1 |
news-feed: dau > 0, peak_to_average >= 1 and replication_factor >= 1 are required | Laravel Workload | Bad config value |
429 Too Many Requests + Retry-After: 2 | Rate limiter example | RFC 6585: "the user has sent too many requests in a given amount of time" |
Go
The Go module (academy/four-step-approach) is standard library only: an estimate package with pure arithmetic, a designdoc package that renders and lints a design doc with text/template, the three worked examples, and a command.
Before
A box-first design: components chosen before any requirement or number exists. It compiles and looks like architecture.
// Command before is the box-first design: components chosen before any
// requirement or number exists. It compiles and "looks like architecture".
package main
import "fmt"
func main() {
boxes := []string{
"API gateway", "user-service", "post-service", "feed-service",
"notification-service", "Kafka (12 partitions)", "Cassandra (sharded)",
"Redis cluster", "Elasticsearch", "Kubernetes (3 regions)",
}
fmt.Println("Design: social feed for a 6-person startup")
for _, b := range boxes {
fmt.Println(" -", b)
}
// Missing: who uses it, how many, how fast, what may be stale,
// what is out of scope, the write path, and why each box exists.
}After
The estimator. Pure functions for every row of the estimate kit, and Run, which turns a Workload (step 1 numbers) into a Result (step 2 numbers).
// Package estimate holds the back-of-the-envelope arithmetic used in step 2
// of the four-step approach: QPS, peak, storage, bandwidth, cache and servers.
// Every function is pure so the numbers in a design doc can be pinned by tests.
package estimate
import (
"errors"
"fmt"
"math"
)
// SecondsPerDay is 86,400; in head arithmetic round it to 1e5.
const SecondsPerDay = 86_400
// Decimal (SI) units, used for disks, network and cloud bills.
const (
KB = 1_000.0
MB = 1_000 * KB
GB = 1_000 * MB
TB = 1_000 * GB
PB = 1_000 * TB
)
// Binary (IEC) units, used for RAM. 2^10 = 1,024 is "about a thousand".
const (
KiB = 1 << 10
MiB = 1 << 20
GiB = 1 << 30
TiB = 1 << 40
)
// Workload is the output of step 1 (scope) turned into numbers.
type Workload struct {
Name string
DAU float64 // daily active users
ReadsPerUserDay float64 // read requests per active user per day
WritesPerUserDay float64 // write requests per active user per day
PeakToAverage float64 // peak QPS divided by average QPS, e.g. 2 to 5
BytesPerWrite float64 // stored bytes per write (record + index share)
BytesPerRead float64 // response bytes per read
RetentionDays float64 // how long writes are kept
ReplicationFactor float64 // copies kept by the storage layer (3 is common)
FanOut float64 // extra internal writes per user write (0 = none)
HotFraction float64 // share of daily read data worth caching (0.2 = 80/20)
StateKeys float64 // live keys kept in memory (buckets, positions); 0 if none
BytesPerKey float64 // bytes per live key including store overhead
PerServerQPS float64 // measured or assumed capacity of one server
TargetUtilization float64 // fraction of that capacity you plan to use (0.5 to 0.7)
Redundancy int // spare servers on top of the need (N+2 -> 2)
}
// Result is what step 2 hands to step 3.
type Result struct {
ReadQPS, WriteQPS float64 // average
PeakReadQPS, PeakWriteQPS float64
InternalWriteQPS float64 // peak writes after fan-out
ReadWriteRatio float64
StoragePerDayBytes float64 // before replication
StorageTotalBytes float64 // after retention and replication
EgressBytesPerSec float64 // at peak
IngressBytesPerSec float64 // at peak
CacheBytes float64
StateBytes float64 // live keys x bytes x replication
Servers int
}
// ErrInvalid reports a workload that cannot be estimated.
var ErrInvalid = errors.New("estimate: invalid workload")
// QPS converts a daily count into an average per-second rate.
func QPS(perDay float64) float64 { return perDay / SecondsPerDay }
// Peak applies a peak-to-average factor.
func Peak(avg, factor float64) float64 { return avg * factor }
// FromMAU estimates DAU from monthly actives using the DAU/MAU "stickiness" ratio.
func FromMAU(mau, dauOverMAU float64) float64 { return mau * dauOverMAU }
// Storage returns bytes kept: writes/day x size x retention x replication.
func Storage(writesPerDay, bytesPerWrite, retentionDays, replication float64) float64 {
return writesPerDay * bytesPerWrite * retentionDays * replication
}
// Bandwidth returns bytes per second for a rate and a payload size.
func Bandwidth(qps, bytesPerRequest float64) float64 { return qps * bytesPerRequest }
// Bits converts bytes per second to bits per second (links are sold in bits).
func Bits(bytesPerSec float64) float64 { return bytesPerSec * 8 }
// Cache applies the 80/20 (Pareto) rule: cache the hot fraction of a day's read data.
func Cache(dailyReadBytes, hotFraction float64) float64 { return dailyReadBytes * hotFraction }
// CacheDistinct sizes a cache from distinct objects instead of request volume:
// distinct items x item size x hot fraction. It is the better formula when the
// same hot item is read many times a day.
func CacheDistinct(distinctItems, bytesPerItem, hotFraction float64) float64 {
return distinctItems * bytesPerItem * hotFraction
}
// Servers returns ceil(peak / (perServer x utilization)) + redundancy.
func Servers(peakQPS, perServerQPS, utilization float64, redundancy int) int {
if perServerQPS <= 0 || utilization <= 0 {
return 0
}
return int(math.Ceil(peakQPS/(perServerQPS*utilization))) + redundancy
}
// DowntimePerYear returns the allowed unplanned downtime for an availability target.
// 0.9999 gives 52.56 minutes, the figure the Google SRE book quotes.
func DowntimePerYear(availability float64) float64 { // minutes
return (1 - availability) * 365 * 24 * 60
}
// Run turns a Workload into a Result, checking the inputs first.
func Run(w Workload) (Result, error) {
if w.DAU <= 0 || w.PeakToAverage < 1 || w.ReplicationFactor < 1 {
return Result{}, fmt.Errorf("%w: %q needs DAU > 0, peak >= 1, replication >= 1", ErrInvalid, w.Name)
}
if w.HotFraction < 0 || w.HotFraction > 1 || w.TargetUtilization <= 0 || w.TargetUtilization > 1 {
return Result{}, fmt.Errorf("%w: %q hot fraction and utilization must be in (0,1]", ErrInvalid, w.Name)
}
var r Result
writesPerDay := w.DAU * w.WritesPerUserDay
readsPerDay := w.DAU * w.ReadsPerUserDay
r.ReadQPS, r.WriteQPS = QPS(readsPerDay), QPS(writesPerDay)
r.PeakReadQPS, r.PeakWriteQPS = Peak(r.ReadQPS, w.PeakToAverage), Peak(r.WriteQPS, w.PeakToAverage)
r.InternalWriteQPS = r.PeakWriteQPS * (1 + w.FanOut)
if r.WriteQPS > 0 {
r.ReadWriteRatio = r.ReadQPS / r.WriteQPS
}
r.StoragePerDayBytes = writesPerDay * w.BytesPerWrite
r.StorageTotalBytes = Storage(writesPerDay, w.BytesPerWrite, w.RetentionDays, w.ReplicationFactor)
r.EgressBytesPerSec = Bandwidth(r.PeakReadQPS, w.BytesPerRead)
r.IngressBytesPerSec = Bandwidth(r.PeakWriteQPS, w.BytesPerWrite)
r.CacheBytes = Cache(readsPerDay*w.BytesPerRead, w.HotFraction)
r.StateBytes = w.StateKeys * w.BytesPerKey * w.ReplicationFactor
r.Servers = Servers(r.PeakReadQPS+r.PeakWriteQPS, w.PerServerQPS, w.TargetUtilization, w.Redundancy)
return r, nil
}
// Human prints a byte count in decimal units with three significant digits.
func Human(b float64) string {
units := []string{"B", "KB", "MB", "GB", "TB", "PB"}
i := 0
for b >= 1000 && i < len(units)-1 {
b /= 1000
i++
}
return fmt.Sprintf("%.3g %s", b, units[i])
}Tests that pin the arithmetic, table-driven with subtests (t.Run) and an Example function whose // Output: comment is checked by go test:
package estimate
import (
"errors"
"fmt"
"math"
"testing"
)
func near(t *testing.T, name string, got, want, tol float64) {
t.Helper()
if math.Abs(got-want) > tol {
t.Errorf("%s = %.4f, want %.4f (+/- %g)", name, got, want, tol)
}
}
func TestPrimitives(t *testing.T) {
tests := []struct {
name string
got, want float64
}{
{"1M per day is about 11.6 QPS", QPS(1_000_000), 11.574},
{"peak x3", Peak(100, 3), 300},
{"DAU from MAU at 50%", FromMAU(20_000_000, 0.5), 10_000_000},
{"storage 1M x 1KB x 365 x 3", Storage(1_000_000, KB, 365, 3), 1.095 * TB},
{"bandwidth 1000 QPS x 20KB", Bandwidth(1000, 20*KB), 20 * MB},
{"bits", Bits(20 * MB), 160e6},
{"80/20 of 100 GB", Cache(100*GB, 0.2), 20 * GB},
{"distinct 1M x 1KB x 0.2", CacheDistinct(1_000_000, KB, 0.2), 200 * MB},
{"four nines = 52.56 min/year", DowntimePerYear(0.9999), 52.56},
{"three nines = 525.6 min/year", DowntimePerYear(0.999), 525.6},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) { near(t, tc.name, tc.got, tc.want, 0.01*math.Max(1, tc.want/100)) })
}
}
func TestServers(t *testing.T) {
tests := []struct {
peak, per, util float64
spare int
want int
}{
{3_472, 500, 0.6, 2, 14}, // 3472/300 = 11.6 -> 12, +2
{100, 1000, 0.5, 2, 3}, // tiny load still gets N+2
{1, 0, 0.5, 2, 0}, // unknown capacity: refuse to guess
}
for _, tc := range tests {
if got := Servers(tc.peak, tc.per, tc.util, tc.spare); got != tc.want {
t.Errorf("Servers(%v,%v,%v,%d) = %d, want %d", tc.peak, tc.per, tc.util, tc.spare, got, tc.want)
}
}
}
func TestRunNewsFeed(t *testing.T) {
r, err := Run(Workload{
Name: "news feed", DAU: 10e6, ReadsPerUserDay: 10, WritesPerUserDay: 1,
PeakToAverage: 3, BytesPerWrite: KB, BytesPerRead: 20 * KB,
RetentionDays: 5 * 365, ReplicationFactor: 3, FanOut: 200,
HotFraction: 0.2, PerServerQPS: 500, TargetUtilization: 0.6, Redundancy: 2,
})
if err != nil {
t.Fatal(err)
}
near(t, "read QPS", r.ReadQPS, 1157.4, 0.1)
near(t, "write QPS", r.WriteQPS, 115.7, 0.1)
near(t, "peak read", r.PeakReadQPS, 3472.2, 0.1)
near(t, "internal writes after fan-out", r.InternalWriteQPS, 69791.7, 0.5)
near(t, "ratio", r.ReadWriteRatio, 10, 1e-9)
near(t, "storage/day", r.StoragePerDayBytes, 10*GB, 1)
near(t, "storage total", r.StorageTotalBytes, 54.75*TB, 1e6)
near(t, "egress", r.EgressBytesPerSec, 69.44*MB, 0.01*MB)
if r.Servers != 15 { // (3472+347)/300 = 12.7 -> 13, +2
t.Errorf("servers = %d, want 15", r.Servers)
}
}
func TestRunRejectsNonsense(t *testing.T) {
_, err := Run(Workload{Name: "empty"})
if !errors.Is(err, ErrInvalid) {
t.Fatalf("want ErrInvalid, got %v", err)
}
_, err = Run(Workload{Name: "hot>1", DAU: 1, PeakToAverage: 1, ReplicationFactor: 1, HotFraction: 2, TargetUtilization: 0.5})
if !errors.Is(err, ErrInvalid) {
t.Fatalf("want ErrInvalid, got %v", err)
}
}
func TestHuman(t *testing.T) {
for in, want := range map[float64]string{999: "999 B", 54.75 * TB: "54.8 TB", 69.44 * MB: "69.4 MB"} {
if got := Human(in); got != want {
t.Errorf("Human(%v) = %q, want %q", in, got, want)
}
}
}
func ExampleDowntimePerYear() {
fmt.Printf("%.2f minutes\n", DowntimePerYear(0.9999))
// Output: 52.56 minutes
}The design doc generator and linter. Doc mirrors the template; Render writes Markdown; Lint returns the codes.
// Package designdoc turns the four steps into a design doc skeleton:
// scope, estimate, high-level design, decisions. Render writes Markdown;
// Lint flags the anti-patterns the chapter warns about.
package designdoc
import (
"fmt"
"io"
"strings"
"text/template"
"academy/four-step-approach/estimate"
)
// Endpoint is one line of the API sketch (step 3 starts here).
type Endpoint struct {
Method, Path, Purpose string
Idempotent bool
}
// Entity is one table, key space or topic in the data model.
type Entity struct {
Name, Store, Key, Notes string
}
// Flow is a numbered path through the components (read path, write path...).
type Flow struct {
Name string
Write bool // true for paths that change state
Steps []string
}
// Decision is an ADR-shaped record: context, options, choice, consequences.
type Decision struct {
ID, Title, Context string
Options []string
Choice string
Consequences string
Status string // proposed, accepted, superseded
}
// FailureMode is "what breaks, what the user sees, what we do".
type FailureMode struct {
Component, Failure, Impact, Mitigation string
}
// Doc is the whole skeleton.
type Doc struct {
Title string
Context string
Functional []string
NonFunctional []string // must include an availability target and a latency SLO
OutOfScope []string
Assumptions []string
Workload estimate.Workload
Estimate estimate.Result
API []Endpoint
DataModel []Entity
Components []string
Flows []Flow
Decisions []Decision
FailureModes []FailureMode
Monitoring []string
Evolution []string
TeamEngineers int // used by the microservices lint
Microservices bool // the design splits into independently deployed services
ShardedPrimary bool // the design shards the primary database
}
// Finding is one lint result. Code is stable so CI can allow-list it.
type Finding struct {
Code, Message string
}
func (f Finding) String() string { return f.Code + " " + f.Message }
// SinglePrimaryWriteQPS is a deliberately conservative planning number for
// one well-tuned relational primary; replace it with your own benchmark.
const SinglePrimaryWriteQPS = 5_000
// Lint checks a Doc for the gaps that make designs fail review.
func Lint(d Doc) []Finding {
var out []Finding
add := func(code, format string, a ...any) {
out = append(out, Finding{code, fmt.Sprintf(format, a...)})
}
if len(d.Functional) == 0 {
add("SCOPE001", "no functional requirements")
}
if !containsAny(d.NonFunctional, "availability", "slo") {
add("SCOPE002", "no availability target or SLO in non-functional requirements")
}
if len(d.OutOfScope) == 0 {
add("SCOPE003", "out of scope is empty: say what you will not build")
}
if len(d.Assumptions) == 0 {
add("SCOPE004", "no written assumptions")
}
if d.Estimate.PeakReadQPS+d.Estimate.PeakWriteQPS == 0 {
add("EST001", "no estimate: QPS was never computed")
}
if len(d.API) == 0 {
add("HLD001", "no API sketch: start step 3 with the API")
}
hasWrite := false
for _, f := range d.Flows {
hasWrite = hasWrite || f.Write
}
if !hasWrite {
add("HLD002", "no write path: every design needs the path that changes state")
}
for _, dec := range d.Decisions {
if len(dec.Options) < 2 {
add("DEC001", "%s %q has fewer than two options: a decision needs an alternative", dec.ID, dec.Title)
}
}
if len(d.Decisions) == 0 {
add("DEC002", "no decisions recorded")
}
if len(d.FailureModes) == 0 {
add("DEC003", "no failure modes")
}
if len(d.Monitoring) == 0 {
add("DEC004", "nothing to monitor")
}
if d.Microservices && d.TeamEngineers > 0 && d.TeamEngineers < 20 {
add("ANTI001", "microservices with %d engineers: start with a modular monolith", d.TeamEngineers)
}
if d.ShardedPrimary && d.Estimate.InternalWriteQPS < SinglePrimaryWriteQPS && d.Estimate.StorageTotalBytes < 10*estimate.TB {
add("ANTI002", "sharding at %.0f peak writes/s and %s: premature", d.Estimate.InternalWriteQPS, estimate.Human(d.Estimate.StorageTotalBytes))
}
if d.Estimate.PeakWriteQPS > 0 && d.Estimate.InternalWriteQPS > 10*d.Estimate.PeakWriteQPS && !mentions(d, "fan-out") {
add("ANTI003", "fan-out multiplies writes %.0fx but no decision mentions fan-out", d.Estimate.InternalWriteQPS/d.Estimate.PeakWriteQPS)
}
return out
}
func containsAny(items []string, words ...string) bool {
for _, it := range items {
l := strings.ToLower(it)
for _, w := range words {
if strings.Contains(l, w) {
return true
}
}
}
return false
}
func mentions(d Doc, word string) bool {
for _, dec := range d.Decisions {
if containsAny([]string{dec.Title, dec.Context, dec.Choice}, word) {
return true
}
}
return false
}
// ratio prints reads:writes so that write-heavy systems do not show "0:1".
func ratio(r float64) string {
switch {
case r == 0:
return "write-only"
case r >= 1:
return fmt.Sprintf("%.0f:1", r)
default:
return fmt.Sprintf("1:%.0f", 1/r)
}
}
var funcs = template.FuncMap{
"human": estimate.Human,
"f0": func(v float64) string { return fmt.Sprintf("%.0f", v) },
"mbit": func(v float64) string { return fmt.Sprintf("%.0f Mbit/s", estimate.Bits(v)/1e6) },
"join": strings.Join,
"inc": func(i int) int { return i + 1 },
"ratio": ratio,
}
var tmpl = template.Must(template.New("doc").Funcs(funcs).Parse(`# Design doc: {{.Title}}
{{.Context}}
## 1. Scope
**Functional requirements**
{{range .Functional}}- {{.}}
{{end}}
**Non-functional requirements**
{{range .NonFunctional}}- {{.}}
{{end}}
**Out of scope**
{{range .OutOfScope}}- {{.}}
{{end}}
**Assumptions**
{{range .Assumptions}}- {{.}}
{{end}}
## 2. Estimate
| Quantity | Value |
| --- | --- |
| Average read / write QPS | {{f0 .Estimate.ReadQPS}} / {{f0 .Estimate.WriteQPS}} |
| Peak read / write QPS (x{{.Workload.PeakToAverage}}) | {{f0 .Estimate.PeakReadQPS}} / {{f0 .Estimate.PeakWriteQPS}} |
| Peak internal writes after fan-out | {{f0 .Estimate.InternalWriteQPS}} |
| Read/write ratio | {{ratio .Estimate.ReadWriteRatio}} |
| Bytes written per day (one copy) | {{human .Estimate.StoragePerDayBytes}} |
| Stored: {{f0 .Workload.RetentionDays}} days retention x{{.Workload.ReplicationFactor}} copies | {{human .Estimate.StorageTotalBytes}} |
| Peak egress | {{human .Estimate.EgressBytesPerSec}}/s ({{mbit .Estimate.EgressBytesPerSec}}) |
| Cache (hot {{.Workload.HotFraction}} of daily reads) | {{human .Estimate.CacheBytes}} |
| Live key state in memory | {{human .Estimate.StateBytes}} |
| App servers (N+{{.Workload.Redundancy}}) | {{.Estimate.Servers}} |
## 3. High-level design
**API**
{{range .API}}- ` + "`{{.Method}} {{.Path}}`" + ` {{.Purpose}}{{if .Idempotent}} (idempotent){{end}}
{{end}}
**Data model**
{{range .DataModel}}- {{.Name}} in {{.Store}}, key {{.Key}}: {{.Notes}}
{{end}}
**Components:** {{join .Components ", "}}
{{range .Flows}}
**{{.Name}}**{{if .Write}} (write path){{end}}
{{range $i, $s := .Steps}}{{inc $i}}. {{$s}}
{{end}}{{end}}
## 4. Decisions and deep dives
{{range .Decisions}}### {{.ID}} {{.Title}} ({{.Status}})
- Context: {{.Context}}
- Options: {{join .Options "; "}}
- Choice: {{.Choice}}
- Consequences: {{.Consequences}}
{{end}}**Failure modes**
| Component | Failure | User impact | Mitigation |
| --- | --- | --- | --- |
{{range .FailureModes}}| {{.Component}} | {{.Failure}} | {{.Impact}} | {{.Mitigation}} |
{{end}}
**Monitoring:** {{join .Monitoring "; "}}
**Evolution:** {{join .Evolution "; "}}
`))
// Render writes the doc as Markdown.
func Render(w io.Writer, d Doc) error { return tmpl.Execute(w, d) }package designdoc
import (
"bytes"
"strings"
"testing"
"academy/four-step-approach/estimate"
)
func codes(fs []Finding) string {
var c []string
for _, f := range fs {
c = append(c, f.Code)
}
return strings.Join(c, ",")
}
func TestLintCatchesBoxFirstDesign(t *testing.T) {
r, _ := estimate.Run(estimate.Workload{Name: "x", DAU: 50_000, ReadsPerUserDay: 20, WritesPerUserDay: 2,
PeakToAverage: 3, BytesPerWrite: 1_000, RetentionDays: 365, ReplicationFactor: 3,
TargetUtilization: 0.6, HotFraction: 0.2, PerServerQPS: 500})
d := Doc{
Title: "box-first", Functional: []string{"feed"}, Estimate: r,
Flows: []Flow{{Name: "read feed", Steps: []string{"GET"}}},
Decisions: []Decision{{ID: "ADR-1", Title: "Use Cassandra", Options: []string{"Cassandra"}}},
Microservices: true,
TeamEngineers: 6,
ShardedPrimary: true,
}
got := codes(Lint(d))
want := "SCOPE002,SCOPE003,SCOPE004,HLD001,HLD002,DEC001,DEC003,DEC004,ANTI001,ANTI002"
if got != want {
t.Fatalf("codes = %s\nwant %s", got, want)
}
}
func TestLintIgnoresShardingWhenNumbersJustifyIt(t *testing.T) {
d := Doc{ShardedPrimary: true, Estimate: estimate.Result{PeakWriteQPS: 60_000, InternalWriteQPS: 60_000}}
for _, f := range Lint(d) {
if f.Code == "ANTI002" {
t.Fatal("ANTI002 raised for 60k writes/s")
}
}
}
func TestRenderHasEveryStep(t *testing.T) {
var b bytes.Buffer
if err := Render(&b, Doc{Title: "t", Workload: estimate.Workload{Redundancy: 2}}); err != nil {
t.Fatal(err)
}
for _, h := range []string{"## 1. Scope", "## 2. Estimate", "## 3. High-level design", "## 4. Decisions and deep dives", "**Out of scope**", "**Failure modes**"} {
if !strings.Contains(b.String(), h) {
t.Errorf("rendered doc misses %q", h)
}
}
}
func TestRatio(t *testing.T) {
for in, want := range map[float64]string{0: "write-only", 10: "10:1", 0.001: "1:1000"} {
if got := ratio(in); got != want {
t.Errorf("ratio(%v) = %q, want %q", in, got, want)
}
}
}The three worked examples as data, plus the box-first doc that the linter rejects. The test pins every number quoted on this page:
// Package examples holds the three worked designs of the chapter, each built
// with the same template: rate limiter (small), news feed (large, read-heavy
// with a hidden write path), ride matching (write-heavy, geospatial).
package examples
import (
"academy/four-step-approach/designdoc"
"academy/four-step-approach/estimate"
)
func ep(method, path, purpose string, idempotent bool) designdoc.Endpoint {
return designdoc.Endpoint{Method: method, Path: path, Purpose: purpose, Idempotent: idempotent}
}
func ent(name, store, key, notes string) designdoc.Entity {
return designdoc.Entity{Name: name, Store: store, Key: key, Notes: notes}
}
func flow(name string, write bool, steps []string) designdoc.Flow {
return designdoc.Flow{Name: name, Write: write, Steps: steps}
}
func adr(id, title, context string, options []string, choice, consequences, status string) designdoc.Decision {
return designdoc.Decision{ID: id, Title: title, Context: context, Options: options,
Choice: choice, Consequences: consequences, Status: status}
}
func fm(component, failure, impact, mitigation string) designdoc.FailureMode {
return designdoc.FailureMode{Component: component, Failure: failure, Impact: impact, Mitigation: mitigation}
}
func build(d designdoc.Doc) designdoc.Doc {
r, err := estimate.Run(d.Workload)
if err != nil {
panic(err) // the examples are constants; a bad one is a programming error
}
d.Estimate = r
return d
}
// RateLimiter: 500 M checks/day from 10,000 API keys, enforced at the gateway.
func RateLimiter() designdoc.Doc {
return build(designdoc.Doc{
Title: "API rate limiter service",
Context: "Public HTTP API behind an API gateway; protect it from abusive or runaway clients.",
Functional: []string{
"Limit each API key to N requests per second per endpoint class, with a short burst",
"Return 429 Too Many Requests with Retry-After and RateLimit headers",
"Operators change limits without a deploy",
},
NonFunctional: []string{
"Availability: the API must stay up if the limiter fails (fail open)",
"SLO: limiter adds < 2 ms p99 to each request",
"Limits are approximate across nodes (a few % over is acceptable)",
},
OutOfScope: []string{"Billing and quota per month", "Bot detection and DDoS scrubbing (CDN/WAF layer)"},
Assumptions: []string{"10,000 active API keys/day", "1 check per request", "~1 M (key, class) buckets of ~200 B"},
Workload: estimate.Workload{
Name: "rate limiter", DAU: 10_000, WritesPerUserDay: 50_000, PeakToAverage: 3,
BytesPerWrite: 150, ReplicationFactor: 2, StateKeys: 1e6, BytesPerKey: 200,
PerServerQPS: 50_000, TargetUtilization: 0.5, Redundancy: 1,
},
API: []designdoc.Endpoint{
ep("POST", "/v1/check", "internal: consume one token for (key, class); returns allowed, remaining, reset", false),
ep("PUT", "/v1/limits/{class}", "admin: set rate and burst", true),
},
DataModel: []designdoc.Entity{
ent("bucket", "Redis", "rl:{key}:{class}", "hash {tokens, ts}, TTL 2 x refill window"),
ent("limit_rules", "PostgreSQL", "class", "rate, burst; cached in gateway memory for 30 s"),
},
Components: []string{"API gateway with limiter middleware", "Redis primary + replica", "rules table", "metrics"},
Flows: []designdoc.Flow{
flow("Check", true, []string{"request reaches gateway", "middleware runs token-bucket Lua script on Redis", "allowed: forward; denied: 429 + Retry-After", "Redis error or > 5 ms: allow and count fail_open"}),
},
Decisions: []designdoc.Decision{
adr("ADR-1", "Algorithm", "Need bursts and smooth refill", []string{"fixed window", "sliding window log", "token bucket"}, "token bucket", "Two numbers per bucket; burst is explicit", "accepted"),
adr("ADR-2", "Where state lives", "Many gateway nodes", []string{"local memory per node", "central Redis", "local + periodic sync"}, "central Redis, Lua for atomicity", "One network hop (~0.5 ms in-DC); Redis becomes a dependency, so fail open", "accepted"),
},
FailureModes: []designdoc.FailureMode{
fm("Redis", "down or slow", "none if fail-open works; abuse unprotected", "timeout 5 ms, fail open, alert"),
fm("Hot key", "one client floods", "that client gets 429", "per-key bucket; local pre-check"),
},
Monitoring: []string{"allowed vs denied per class", "limiter p99 latency", "fail_open count", "Redis CPU and memory"},
Evolution: []string{"10x: shard buckets by key across Redis Cluster", "multi-region: per-region limits, no global sync"},
})
}
// NewsFeed: 10 M DAU, reverse-chronological feed, average 200 friends.
func NewsFeed() designdoc.Doc {
return build(designdoc.Doc{
Title: "News feed",
Context: "Social app (web + mobile); users post and read a feed of friends' posts.",
Functional: []string{
"Publish a post (text, optional image)",
"Read my feed: friends' posts, newest first, paginated",
},
NonFunctional: []string{
"Availability target 99.95% for feed reads",
"SLO: feed read p99 < 300 ms; a new post visible to friends within 5 s (eventual)",
"Posts are durable once acknowledged",
},
OutOfScope: []string{"Ranking/ML ordering", "Comments, likes, notifications", "Ads"},
Assumptions: []string{"10 M DAU", "1 post and 10 feed loads per user per day", "200 friends on average, 5,000 max", "post 1 KB, feed page 20 KB (text)"},
Workload: estimate.Workload{
Name: "news feed", DAU: 10e6, ReadsPerUserDay: 10, WritesPerUserDay: 1,
PeakToAverage: 3, BytesPerWrite: estimate.KB, BytesPerRead: 20 * estimate.KB,
RetentionDays: 5 * 365, ReplicationFactor: 3, FanOut: 200,
HotFraction: 0.2, PerServerQPS: 500, TargetUtilization: 0.6, Redundancy: 2,
},
API: []designdoc.Endpoint{
ep("POST", "/v1/posts", "create a post; Idempotency-Key header", true),
ep("GET", "/v1/feed?cursor=", "page of 20 posts, cursor pagination", true),
},
DataModel: []designdoc.Entity{
ent("posts", "PostgreSQL", "post_id (time-ordered)", "author_id, body, media_url, created_at"),
ent("follows", "PostgreSQL", "(follower_id, followee_id)", "index on followee_id for fan-out"),
ent("feed:{user}", "Redis", "user_id", "list of the latest 500 post_ids"),
},
Components: []string{"CDN", "load balancer", "post service", "feed service", "fan-out workers", "Kafka", "Redis feed cache", "PostgreSQL", "object storage"},
Flows: []designdoc.Flow{
flow("Publish", true, []string{"POST /v1/posts", "insert post + outbox row in one transaction", "relay publishes PostCreated to Kafka", "fan-out workers push post_id to each follower's feed list", "authors with > 10k followers are skipped (pull at read time)"}),
flow("Read feed", false, []string{"GET /v1/feed", "read post_ids from feed:{user}", "merge posts of followed celebrities", "hydrate posts from cache, then PostgreSQL", "return 20 posts + next cursor"}),
},
Decisions: []designdoc.Decision{
adr("ADR-1", "Fan-out on write vs read", "10:1 reads, but each post multiplies into ~200 feed writes", []string{"fan-out on write", "fan-out on read", "hybrid: write for normal users, read for celebrities"}, "hybrid fan-out", "Peak ~70k feed-list writes/s go to Redis, not PostgreSQL; celebrity posts merged at read time", "accepted"),
adr("ADR-2", "Post store", "55 TB over 5 years with 3 replicas", []string{"one PostgreSQL primary + replicas", "sharded PostgreSQL by author_id", "Cassandra"}, "PostgreSQL primary + read replicas now; partition by month; shard by author_id when one primary is outgrown", "Simple now; resharding later is planned work, not an emergency", "accepted"),
},
FailureModes: []designdoc.FailureMode{
fm("Fan-out workers", "lag behind", "new posts appear late", "Kafka buffers; scale consumers; alert on lag"),
fm("Redis feed cache", "node lost", "slower feeds for some users", "rebuild feed from follows + posts on miss"),
fm("PostgreSQL primary", "failover", "posting fails for ~30 s", "client retry with the same Idempotency-Key"),
},
Monitoring: []string{"feed p99 and error rate (SLO)", "Kafka consumer lag", "fan-out writes/s", "cache hit ratio", "replica lag"},
Evolution: []string{"10x: shard posts by author_id, Redis Cluster", "ranking service later", "second region read-only"},
Microservices: true, TeamEngineers: 40,
})
}
// RideMatching: 1 M drivers/day sending a location every 4 s; 10 M rides/day.
func RideMatching() designdoc.Doc {
return build(designdoc.Doc{
Title: "Ride matching (skeleton)",
Context: "Rider requests a ride; the system offers it to a nearby available driver.",
Functional: []string{
"Drivers report location every 4 s while online",
"Rider requests a ride; system finds nearby available drivers and offers the trip",
"A driver can hold at most one trip",
},
NonFunctional: []string{
"Availability target 99.99% for ride requests in each city",
"SLO: match decision p99 < 2 s",
"Strong consistency for driver assignment; positions may be seconds stale",
},
OutOfScope: []string{"Pricing and surge", "Payments", "ETA routing engine", "Driver onboarding"},
Assumptions: []string{"1 M drivers/day, 8 h online, update every 4 s", "10 M rides/day", "location point 50 B stored, 30 days raw"},
Workload: estimate.Workload{
Name: "ride matching", DAU: 1e6, WritesPerUserDay: 7_200, ReadsPerUserDay: 10,
PeakToAverage: 1.5, BytesPerWrite: 50, BytesPerRead: 2 * estimate.KB,
RetentionDays: 30, ReplicationFactor: 3, HotFraction: 0.2,
StateKeys: 1e6, BytesPerKey: 100,
PerServerQPS: 10_000, TargetUtilization: 0.6, Redundancy: 2,
},
API: []designdoc.Endpoint{
ep("POST", "/v1/drivers/{id}/location", "lat, lng, ts; last write wins", true),
ep("POST", "/v1/rides", "request a ride; Idempotency-Key", true),
ep("POST", "/v1/offers/{id}/accept", "driver accepts; conditional on driver still free", true),
},
DataModel: []designdoc.Entity{
ent("drivers:{city}", "Redis GEO", "driver_id", "latest position; GEOSEARCH by radius"),
ent("driver_state", "PostgreSQL", "driver_id", "status AVAILABLE/OFFERED/ON_TRIP, version"),
ent("rides", "PostgreSQL", "ride_id", "rider_id, driver_id, status, city"),
ent("locations", "Kafka -> object storage", "driver_id", "raw points for 30 days"),
},
Components: []string{"mobile gateway", "location ingest", "Redis GEO per city", "matcher", "trip service", "PostgreSQL per region", "Kafka"},
Flows: []designdoc.Flow{
flow("Location update", true, []string{"driver app posts location", "ingest writes GEOADD drivers:{city}", "ingest appends point to Kafka"}),
flow("Match", true, []string{"rider POST /v1/rides", "matcher GEOSEARCH 2 km, COUNT 20, ASC", "filter AVAILABLE in driver_state", "UPDATE driver_state SET status = OFFERED WHERE status = AVAILABLE AND version = v", "push offer; timeout 10 s then next driver"}),
},
Decisions: []designdoc.Decision{
adr("ADR-1", "Geospatial index", "125k position writes/s, radius search", []string{"PostgreSQL + PostGIS", "Redis GEO per city", "H3 cells in memory"}, "Redis GEO per city now, H3 cells if radius search becomes the bottleneck", "Positions are not durable; they are rebuilt within 4 s", "accepted"),
adr("ADR-2", "Double assignment", "Two matchers may pick the same driver", []string{"distributed lock", "conditional update with version", "single matcher per city"}, "conditional update (compare-and-set)", "Losing matcher retries with the next driver", "accepted"),
},
FailureModes: []designdoc.FailureMode{
fm("Redis GEO city shard", "lost", "no matches in that city for seconds", "replica promotion; positions refill in 4 s"),
fm("Matcher", "crash mid-offer", "driver stuck OFFERED", "offer expiry job resets after 10 s"),
},
Monitoring: []string{"match latency p99", "unmatched request rate per city", "location ingest lag", "offers expired"},
Evolution: []string{"partition everything by city/region", "H3 cells", "multi-region active-active by city"},
Microservices: true, TeamEngineers: 120, ShardedPrimary: true,
})
}
// BoxFirst is the "before" design written as a doc: boxes, no scope, no numbers
// worth the boxes. Lint is expected to reject it.
func BoxFirst() designdoc.Doc {
return build(designdoc.Doc{
Title: "Social feed (box-first)",
Functional: []string{"feed"},
Workload: estimate.Workload{
Name: "box-first", DAU: 50_000, ReadsPerUserDay: 20, WritesPerUserDay: 2,
PeakToAverage: 3, BytesPerWrite: 1_000, RetentionDays: 365, ReplicationFactor: 3,
HotFraction: 0.2, PerServerQPS: 500, TargetUtilization: 0.6,
},
Components: []string{"API gateway", "5 microservices", "Kafka", "Cassandra (sharded)", "Redis cluster", "Elasticsearch"},
Flows: []designdoc.Flow{flow("Read feed", false, []string{"GET /feed"})},
Decisions: []designdoc.Decision{adr("ADR-1", "Use Cassandra", "it scales", []string{"Cassandra"}, "Cassandra", "", "accepted")},
Microservices: true, TeamEngineers: 6, ShardedPrimary: true,
})
}package examples
import (
"math"
"testing"
"academy/four-step-approach/designdoc"
)
// The numbers quoted on the page are pinned here; change one and a test fails.
func TestNumbersOnThePage(t *testing.T) {
tests := []struct {
name string
got float64
want float64
}{
{"limiter peak checks/s", RateLimiter().Estimate.PeakWriteQPS, 17_361},
{"feed peak reads/s", NewsFeed().Estimate.PeakReadQPS, 3_472},
{"feed peak fan-out writes/s", NewsFeed().Estimate.InternalWriteQPS, 69_792},
{"feed storage TB", NewsFeed().Estimate.StorageTotalBytes / 1e12, 54.75},
{"rides peak location writes/s", RideMatching().Estimate.PeakWriteQPS, 125_000},
{"limiter bucket state MB", RateLimiter().Estimate.StateBytes / 1e6, 400},
{"rides storage TB", RideMatching().Estimate.StorageTotalBytes / 1e12, 32.4},
}
for _, tc := range tests {
if math.Abs(tc.got-tc.want) > 1 {
t.Errorf("%s = %.2f, want %.2f", tc.name, tc.got, tc.want)
}
}
if s := RideMatching().Estimate.Servers; s != 23 {
t.Errorf("ride ingest servers = %d, want 23", s)
}
if s := RateLimiter().Estimate.Servers; s != 2 {
t.Errorf("limiter Redis nodes = %d, want 2", s)
}
}
func TestExamplesPassLint(t *testing.T) {
for _, d := range []designdoc.Doc{RateLimiter(), NewsFeed(), RideMatching()} {
if f := designdoc.Lint(d); len(f) != 0 {
t.Errorf("%s: unexpected findings %v", d.Title, f)
}
}
}
func TestBoxFirstIsRejected(t *testing.T) {
if n := len(designdoc.Lint(BoxFirst())); n != 10 {
t.Errorf("box-first findings = %d, want 10", n)
}
}The command:
// Command designdoc renders a worked example as a design doc skeleton and lints it.
//
// go run ./cmd/designdoc -example newsfeed
// go run ./cmd/designdoc -example all -lint
package main
import (
"flag"
"fmt"
"os"
"academy/four-step-approach/designdoc"
"academy/four-step-approach/examples"
)
func main() {
name := flag.String("example", "ratelimiter", "ratelimiter | newsfeed | ridematching | boxfirst | all")
lintOnly := flag.Bool("lint", false, "print lint findings only")
flag.Parse()
all := map[string]func() designdoc.Doc{
"ratelimiter": examples.RateLimiter,
"newsfeed": examples.NewsFeed,
"ridematching": examples.RideMatching,
"boxfirst": examples.BoxFirst,
}
order := []string{"ratelimiter", "newsfeed", "ridematching"}
if *name != "all" {
if _, ok := all[*name]; !ok {
fmt.Fprintf(os.Stderr, "unknown example %q\n", *name)
os.Exit(2)
}
order = []string{*name}
}
failed := false
for _, n := range order {
d := all[n]()
if !*lintOnly {
if err := designdoc.Render(os.Stdout, d); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
findings := designdoc.Lint(d)
fmt.Printf("lint %s: %d findings\n", n, len(findings))
for _, f := range findings {
fmt.Println(" ", f)
failed = true
}
}
if failed {
os.Exit(1)
}
}The Go angle
| Go feature | Use here | Note |
|---|---|---|
testing table-driven tests + t.Run | One row per formula | pkg.go.dev: "Run runs f as a subtest of t called name." |
t.Helper() | near() reports the caller's line | Clean failure messages |
Example functions | ExampleDowntimePerYear doubles as documentation | "Example functions without output comments are compiled but not executed." |
text/template + FuncMap | Markdown rendering of the doc | Not html/template: output is Markdown, not HTML |
errors.Is + %w | ErrInvalid from Run | Callers test the kind, not the text |
math.Ceil | Server counts | Always round capacity up |
go vet composites check | Forced keyed struct literals (helpers ep, adr...) | Keyed fields survive struct changes |
Untyped constants (KB, GiB) | Decimal vs binary units side by side | 1 << 30 is exact |
Laravel
Before
Numbers that are decisions without the assumptions behind them:
<?php
// Before: decisions without the assumptions that justify them.
// Nobody can tell whether 16 shards is too many, too few, or why Redis has 64 GB.
return [
'database_shards' => 16,
'redis_memory_gb' => 64,
'queue_workers' => 40,
'app_servers' => 30,
];After
Assumptions as configuration, reviewed in pull requests like code. env() lets an environment override the planning limits.
<?php
// Design assumptions as code: step 1 and step 2 of the design doc, reviewed in
// pull requests and checked by `php artisan design:check`.
return [
'limits' => [
// Planning numbers, not benchmarks: replace them with your own measurements.
'single_primary_write_qps' => (int) env('CAPACITY_PRIMARY_WRITE_QPS', 5000),
'redis_node_memory_bytes' => (int) env('CAPACITY_REDIS_NODE_BYTES', 25_000_000_000),
'max_target_utilization' => 0.7,
'min_redundancy' => 2,
],
'systems' => [
'news-feed' => [
'dau' => 10_000_000,
'reads_per_user_day' => 10,
'writes_per_user_day' => 1,
'peak_to_average' => 3,
'bytes_per_write' => 1_000,
'bytes_per_read' => 20_000,
'retention_days' => 5 * 365,
'replication_factor' => 3,
'fan_out' => 200,
'hot_fraction' => 0.2,
'per_server_qps' => 500,
'target_utilization' => 0.6,
'redundancy' => 2,
'availability_target' => 0.9995,
'sharded_primary' => false,
],
'ride-matching' => [
'dau' => 1_000_000,
'reads_per_user_day' => 10,
'writes_per_user_day' => 7_200,
'peak_to_average' => 1.5,
'bytes_per_write' => 50,
'bytes_per_read' => 2_000,
'retention_days' => 30,
'replication_factor' => 3,
'fan_out' => 0,
'hot_fraction' => 0.2,
'per_server_qps' => 10_000,
'target_utilization' => 0.6,
'redundancy' => 2,
'availability_target' => 0.9999,
'sharded_primary' => true,
],
],
];Value objects and the estimator:
<?php
namespace App\Support\Capacity;
use InvalidArgumentException;
final readonly class Workload
{
public function __construct(
public string $name,
public float $dau,
public float $readsPerUserDay,
public float $writesPerUserDay,
public float $peakToAverage,
public float $bytesPerWrite,
public float $bytesPerRead,
public float $retentionDays,
public float $replicationFactor,
public float $fanOut,
public float $hotFraction,
public float $perServerQps,
public float $targetUtilization,
public int $redundancy,
public float $availabilityTarget,
public bool $shardedPrimary,
) {
if ($dau <= 0 || $peakToAverage < 1 || $replicationFactor < 1) {
throw new InvalidArgumentException("{$name}: dau > 0, peak_to_average >= 1 and replication_factor >= 1 are required");
}
}
/** @param array<string, mixed> $c */
public static function fromConfig(string $name, array $c): self
{
return new self(
name: $name,
dau: (float) $c['dau'],
readsPerUserDay: (float) $c['reads_per_user_day'],
writesPerUserDay: (float) $c['writes_per_user_day'],
peakToAverage: (float) $c['peak_to_average'],
bytesPerWrite: (float) $c['bytes_per_write'],
bytesPerRead: (float) $c['bytes_per_read'],
retentionDays: (float) $c['retention_days'],
replicationFactor: (float) $c['replication_factor'],
fanOut: (float) ($c['fan_out'] ?? 0),
hotFraction: (float) ($c['hot_fraction'] ?? 0.2),
perServerQps: (float) $c['per_server_qps'],
targetUtilization: (float) $c['target_utilization'],
redundancy: (int) ($c['redundancy'] ?? 2),
availabilityTarget: (float) ($c['availability_target'] ?? 0.999),
shardedPrimary: (bool) ($c['sharded_primary'] ?? false),
);
}
}<?php
namespace App\Support\Capacity;
final readonly class Estimate
{
public function __construct(
public float $readQps,
public float $writeQps,
public float $peakReadQps,
public float $peakWriteQps,
public float $internalWriteQps,
public float $storageTotalBytes,
public float $egressBytesPerSecond,
public float $cacheBytes,
public int $servers,
public float $downtimeMinutesPerYear,
) {}
}<?php
namespace App\Support\Capacity;
final class CapacityEstimator
{
public const SECONDS_PER_DAY = 86_400;
public function estimate(Workload $w): Estimate
{
$readQps = $w->dau * $w->readsPerUserDay / self::SECONDS_PER_DAY;
$writeQps = $w->dau * $w->writesPerUserDay / self::SECONDS_PER_DAY;
$peakRead = $readQps * $w->peakToAverage;
$peakWrite = $writeQps * $w->peakToAverage;
$servers = $w->perServerQps > 0
? (int) ceil(($peakRead + $peakWrite) / ($w->perServerQps * $w->targetUtilization)) + $w->redundancy
: 0;
return new Estimate(
readQps: $readQps,
writeQps: $writeQps,
peakReadQps: $peakRead,
peakWriteQps: $peakWrite,
internalWriteQps: $peakWrite * (1 + $w->fanOut),
storageTotalBytes: $w->dau * $w->writesPerUserDay * $w->bytesPerWrite * $w->retentionDays * $w->replicationFactor,
egressBytesPerSecond: $peakRead * $w->bytesPerRead,
cacheBytes: $w->dau * $w->readsPerUserDay * $w->bytesPerRead * $w->hotFraction,
servers: $servers,
downtimeMinutesPerYear: (1 - $w->availabilityTarget) * 365 * 24 * 60,
);
}
}The assumption validator, the Laravel twin of the Go linter's capacity rules:
<?php
namespace App\Support\Capacity;
final class AssumptionValidator
{
/**
* Compare an estimate with the planning limits and return findings.
*
* @param array<string, int|float> $limits
* @return list<array{code: string, severity: string, message: string}>
*/
public function validate(Workload $w, Estimate $e, array $limits): array
{
$findings = [];
$add = function (string $code, string $severity, string $message) use (&$findings): void {
$findings[] = ['code' => $code, 'severity' => $severity, 'message' => $message];
};
$primary = (float) $limits['single_primary_write_qps'];
if (! $w->shardedPrimary && $e->internalWriteQps > $primary && $w->fanOut === 0.0) {
$add('CAP001', 'error', sprintf('%.0f peak writes/s exceed one primary (%.0f): partition or shard', $e->internalWriteQps, $primary));
}
if ($w->shardedPrimary && $e->internalWriteQps < $primary && $e->storageTotalBytes < 10e12) {
$add('ANTI002', 'warning', sprintf('sharded at %.0f writes/s: premature sharding', $e->internalWriteQps));
}
if ($w->fanOut > 10) {
$add('ANTI003', 'info', sprintf('fan-out turns %.0f writes/s into %.0f: size the write path, not only reads', $e->peakWriteQps, $e->internalWriteQps));
}
if ($e->cacheBytes > (float) $limits['redis_node_memory_bytes']) {
$add('CAP002', 'info', sprintf('cache of %.0f GB needs %d Redis nodes', $e->cacheBytes / 1e9, (int) ceil($e->cacheBytes / $limits['redis_node_memory_bytes'])));
}
if ($w->targetUtilization > (float) $limits['max_target_utilization']) {
$add('CAP003', 'error', sprintf('target utilization %.2f leaves no headroom for a lost node', $w->targetUtilization));
}
if ($w->redundancy < (int) $limits['min_redundancy']) {
$add('CAP004', 'error', sprintf('N+%d is below the N+%d policy', $w->redundancy, $limits['min_redundancy']));
}
return $findings;
}
}The Artisan command. Laravel 13 defines the signature and description with attributes: "you should define the command's signature and description using the Signature and Description attributes." Dependencies are injected into handle, and fail() "will immediately terminate execution of the command and return an exit code of 1".
<?php
namespace App\Console\Commands;
use App\Support\Capacity\AssumptionValidator;
use App\Support\Capacity\CapacityEstimator;
use App\Support\Capacity\Workload;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use InvalidArgumentException;
#[Signature('design:check {system? : Key under capacity.systems} {--strict : Fail on warnings too}')]
#[Description('Estimate QPS, storage, bandwidth and servers from config/capacity.php and validate the assumptions')]
class DesignCheck extends Command
{
public function handle(CapacityEstimator $estimator, AssumptionValidator $validator): int
{
$systems = config('capacity.systems', []);
$names = $this->argument('system') ? [$this->argument('system')] : array_keys($systems);
$failed = false;
foreach ($names as $name) {
if (! isset($systems[$name])) {
$this->fail("Unknown system [{$name}] in config/capacity.php.");
}
try {
$workload = Workload::fromConfig($name, $systems[$name]);
} catch (InvalidArgumentException $e) {
$this->error($e->getMessage());
$failed = true;
continue;
}
$e = $estimator->estimate($workload);
$this->info("== {$name}");
$this->table(['Quantity', 'Value'], [
['Peak read / write QPS', sprintf('%.0f / %.0f', $e->peakReadQps, $e->peakWriteQps)],
['Peak internal writes (fan-out)', sprintf('%.0f', $e->internalWriteQps)],
['Storage incl. replicas', sprintf('%.1f TB', $e->storageTotalBytes / 1e12)],
['Peak egress', sprintf('%.0f Mbit/s', $e->egressBytesPerSecond * 8 / 1e6)],
['Cache (80/20)', sprintf('%.0f GB', $e->cacheBytes / 1e9)],
['App servers', (string) $e->servers],
['Downtime budget', sprintf('%.1f min/year', $e->downtimeMinutesPerYear)],
]);
foreach ($validator->validate($workload, $e, config('capacity.limits')) as $f) {
$line = "{$f['code']} {$f['message']}";
match ($f['severity']) {
'error' => $this->error($line),
'warning' => $this->warn($line),
default => $this->line($line),
};
$failed = $failed || $f['severity'] === 'error'
|| ($f['severity'] === 'warning' && $this->option('strict'));
}
}
return $failed ? self::FAILURE : self::SUCCESS;
}
}A unit test that pins the same numbers as the Go test:
<?php
namespace Tests\Unit;
use App\Support\Capacity\AssumptionValidator;
use App\Support\Capacity\CapacityEstimator;
use App\Support\Capacity\Workload;
use PHPUnit\Framework\TestCase;
class CapacityEstimatorTest extends TestCase
{
private function feed(array $overrides = []): Workload
{
$config = require __DIR__.'/../../config/capacity.php';
return Workload::fromConfig('news-feed', array_merge($config['systems']['news-feed'], $overrides));
}
public function test_news_feed_numbers_match_the_design_doc(): void
{
$e = (new CapacityEstimator)->estimate($this->feed());
$this->assertEqualsWithDelta(3472.2, $e->peakReadQps, 0.1);
$this->assertEqualsWithDelta(69791.7, $e->internalWriteQps, 0.5);
$this->assertEqualsWithDelta(54.75e12, $e->storageTotalBytes, 1e6);
$this->assertSame(15, $e->servers);
$this->assertEqualsWithDelta(262.8, $e->downtimeMinutesPerYear, 0.01);
}
public function test_validator_flags_missing_headroom_and_redundancy(): void
{
$w = $this->feed(['target_utilization' => 0.9, 'redundancy' => 0]);
$e = (new CapacityEstimator)->estimate($w);
$limits = (require __DIR__.'/../../config/capacity.php')['limits'];
$codes = array_column((new AssumptionValidator)->validate($w, $e, $limits), 'code');
$this->assertContains('CAP003', $codes);
$this->assertContains('CAP004', $codes);
$this->assertContains('ANTI003', $codes);
}
}The Laravel angle
| Laravel 13 feature | Use | Note |
|---|---|---|
#[Signature], #[Description] | Define design:check {system?} {--strict} | Illuminate\Console\Attributes |
handle(CapacityEstimator $e, ...) | Container injects services | Keep commands thin, logic in services (the docs' own advice) |
$this->table() | Prints the estimate | Column widths computed for you |
$this->fail() / self::FAILURE | Non-zero exit for CI | fail() exits with 1 immediately |
config('capacity.systems') | Reads config/capacity.php | Cached by php artisan config:cache; use env() only inside config files |
RateLimiter::attempt() / tooManyAttempts() | The rate-limiter worked example inside Laravel | Store chosen with the limiter key in config/cache.php |
Http::retry(), ShouldQueue | Failure modes and write paths in a Laravel design | See Service Communication |
Scheduler (Schedule::command('design:check --strict')) | Nightly check of live numbers vs assumptions | Feed real DAU into the config |
Solving the classic problems
The template
Copy this checklist into every design. Each line maps to a section of the generated design doc and to a lint code.
| # | Step | Checklist item | Lint |
|---|---|---|---|
| 1 | Scope | Three to five functional requirements, each a verb | SCOPE001 |
| 2 | Scope | NFRs with numbers: latency percentile, availability target, consistency, durability | SCOPE002 |
| 3 | Scope | Out of scope / non-goals (at least three) | SCOPE003 |
| 4 | Scope | Assumptions with sources; users, regions, read/write ratio, hot keys | SCOPE004 |
| 5 | Estimate | Average and peak QPS, reads and writes separately, fan-out included | EST001, ANTI003 |
| 6 | Estimate | Storage with retention and replication; bandwidth; cache; servers with N+2 | - |
| 7 | HLD | API sketch: method, path, pagination, idempotency, errors | HLD001 |
| 8 | HLD | Data model: key, store, indexes, what changes atomically | - |
| 9 | HLD | Component diagram; each box justified by a requirement or a number | ANTI001 |
| 10 | HLD | Read path and write path, numbered, with the synchronous boundary | HLD002 |
| 11 | Decisions | Bottlenecks and SPOFs from walking the flows at 10x | - |
| 12 | Decisions | Two or three deep dives, each an ADR with at least two options | DEC001, DEC002 |
| 13 | Decisions | Failure mode table: component, failure, impact, mitigation, fail open/closed | DEC003 |
| 14 | Decisions | Monitoring: SLIs plus leading indicators with triggers | DEC004 |
| 15 | Decisions | Evolution at 10x and 100x; sharding only when numbers demand it | ANTI002 |
The design doc skeleton the Go command renders (go run ./cmd/designdoc -example newsfeed), shortened:
# Design doc: <title>
<context>
## 1. Scope Functional / Non-functional / Out of scope / Assumptions
## 2. Estimate table: QPS avg and peak, fan-out writes, ratio, storage, egress, cache, state, servers
## 3. High-level design API / Data model / Components / numbered flows (write path marked)
## 4. Decisions and deep dives ADR-1..n (context, options, choice, consequences) / Failure modes / Monitoring / EvolutionWorked example 1: rate limiter service (small)
Step 1, scope. F1: limit each API key to N requests per second per endpoint class, with a short burst. F2: answer 429 Too Many Requests with Retry-After (RFC 6585 defines 429; RFC 9110 defines Retry-After as "how long the user agent ought to wait before making a follow-up request"). F3: operators change limits without a deploy. NFRs: the API must stay up if the limiter fails (fail open); the limiter adds less than 2 ms p99; limits may be a few percent over across nodes. Out of scope: monthly quotas and billing, bot detection and DDoS (CDN/WAF layer, see DDoS Protection). Assumptions: 10,000 active API keys a day, 500 M requests a day, one check per request, about 1 M (key, class) buckets of about 200 bytes.
Step 2, estimate.
| Quantity | Value | How |
|---|---|---|
| Checks per second, average / peak | 5,787 / 17,361 | 500 M / 86,400, x3 |
| Read/write ratio | write-only | Every check is an atomic read-modify-write on a bucket |
| Bucket state | 400 MB | 1 M x 200 B x 2 copies (primary + replica) |
| Traffic to Redis | 2.6 MB/s (21 Mbit/s) | 17,361 x 150 B |
| Redis nodes | 2 | ceil(17,361 / (50,000 x 0.5)) + 1 replica; 50,000 ops/s per node is an assumption to verify with redis-benchmark |
| Latency added | about 0.5 ms | One same-datacenter round trip (Dean: 500,000 ns) |
The numbers say this is a small system. The interesting part is not size but placement and failure behaviour.
Step 3, high-level design. The limiter is middleware in the API gateway (or a Laravel middleware / Go http.Handler), not a separate service: one network hop to Redis per request. Stripe describes the same shape: "We use the token bucket algorithm to do rate limiting" and "We implement our rate limiters using Redis".
-- Rules: small, cached in gateway memory for 30 s; Redis holds the buckets.
CREATE TABLE limit_rules (
endpoint_class text PRIMARY KEY,
rate_per_sec integer NOT NULL CHECK (rate_per_sec > 0),
burst integer NOT NULL CHECK (burst >= rate_per_sec),
updated_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO limit_rules VALUES ('read', 100, 200, now()), ('write', 20, 40, now()); Gateway node Redis (primary) Upstream API
1 request key=k1 class=write arrives
2 EVALSHA token_bucket rl:{k1}:write 20 40 now -> refill, take 1 token, TTL
3 <- allowed=1 remaining=37
4 forward request ------------------------------------------------> 200
5 ... 41st request within 1 s: allowed=0 retry_after=0.05
6 respond 429, Retry-After: 1
7 Redis timeout (> 5 ms): allow, increment fail_open counter, alert if > 1%Step 4, decisions.
| Decision | Options | Choice | Consequence |
|---|---|---|---|
| Algorithm | Fixed window; sliding window log; token bucket | Token bucket | Two numbers per bucket; burst explicit; see Rate Limiting |
| State location | Local memory per node; central Redis; local + sync | Central Redis with a Lua script | One hop; Redis is a dependency, so fail open |
| Failure policy | Fail closed; fail open | Fail open with a 5 ms timeout | Abuse briefly unprotected during a Redis outage; API stays up |
| Rollout | Enforce at once; dark launch | Dark launch (Stripe: "Dark launch each rate limiter to watch the traffic they would block") | Thresholds tuned before anyone is blocked |
Monitoring: allowed vs denied per class, limiter p99, fail_open count, Redis CPU and memory. Evolution: at 10x, shard buckets by key across Redis Cluster; multi-region gets per-region limits rather than a global counter. In Laravel the same limiter is RateLimiter::attempt('api:'.$key, $perSecond, fn () => ...) with the limiter store set to redis in config/cache.php.
Worked example 2: news feed (large, read-heavy, with a hidden write path)
Step 1, scope. F1: publish a post (text, optional image). F2: read my feed, friends' posts newest first, paginated. NFRs: 99.95% availability for feed reads; feed p99 under 300 ms; a new post visible to friends within 5 s; acknowledged posts are durable. Out of scope: ranking, comments and likes, notifications, ads. Assumptions: 10 M DAU; 1 post and 10 feed loads per user per day; 200 friends on average, 5,000 maximum; post 1 KB; feed page 20 KB of text; images go to object storage. (These are the numbers of Xu's interview example extended with our own assumptions.)
Step 2, estimate.
| Quantity | Value | How |
|---|---|---|
| Feed reads, average / peak | 1,157 / 3,472 per s | 100 M / 86,400, x3 |
| Posts, average / peak | 116 / 347 per s | 10 M / 86,400, x3 |
| Read/write ratio | 10:1 | |
| Feed-list writes after fan-out, peak | 69,792 per s | 347 x (1 + 200) |
| Post storage | 10 GB/day, 54.75 TB over 5 years x3 | 10 M x 1 KB x 1,825 x 3 |
| Images | about 500 GB/day to object storage | assume 10% of posts x 500 KB |
| Egress (text) | 69.4 MB/s, 556 Mbit/s | 3,472 x 20 KB |
| Cache | 400 GB by the 80/20 volume formula; about 40 GB of feed ids (x2 overhead, about 80 GB) | see Cache sizing |
| App servers | 15 | ceil(3,819 / (500 x 0.6)) + 2 |
| Downtime budget | 262.8 minutes/year | (1 - 0.9995) x 525,600 |
The picture is step 2 for this example: five inputs, five formulas, five outputs. The last row is the one that changes the design.
Step 3, high-level design.
CREATE TABLE posts (
post_id bigint PRIMARY KEY, -- time-ordered id (see /database/id-generation)
author_id bigint NOT NULL,
body text NOT NULL CHECK (length(body) <= 5000),
media_url text,
created_at timestamptz NOT NULL DEFAULT now()
) PARTITION BY RANGE (created_at);
CREATE INDEX posts_author_recent ON posts (author_id, created_at DESC);
CREATE TABLE follows (
follower_id bigint NOT NULL,
followee_id bigint NOT NULL,
PRIMARY KEY (follower_id, followee_id)
);
CREATE INDEX follows_by_followee ON follows (followee_id);
CREATE TABLE outbox (
id bigserial PRIMARY KEY,
topic text NOT NULL,
payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);The picture shows both flows. The write path ends at the user after the transaction commits; everything after the outbox row is asynchronous (Transactional Outbox), so a slow fan-out delays freshness but never fails a post. The read path touches Redis first and the database only for misses and celebrity posts.
Step 4, decisions.
| Decision | Options | Choice | Consequence |
|---|---|---|---|
| Fan-out | On write; on read; hybrid | Hybrid: write for normal authors, read for authors above 10k followers | Peak ~70k list writes/s hit Redis, not PostgreSQL; two read code paths (Feeds) |
| Post store | One PostgreSQL primary + replicas; sharded PostgreSQL by author_id; Cassandra | One primary + replicas, partitioned by month | 347 writes/s fits one primary; shard by author_id is planned, not urgent |
| Feed cache | Precomputed id lists; cached rendered pages | Id lists (latest 500 per user) | 40 GB hot set; hydration step per read |
| Pagination | Offset; cursor | Cursor on post_id | Stable under inserts (Pagination) |
| Publish reliability | Dual write DB + Kafka; outbox | Outbox + relay | At-least-once; fan-out must be idempotent (LPUSH of an id already present is filtered) |
| Component | Failure | User impact | Mitigation |
|---|---|---|---|
| Fan-out workers | Lag behind | New posts appear late | Kafka buffers; scale consumers; alert on lag > 5 s |
| Redis feed cache | Node lost | Slower feeds for some users | Rebuild feed from follows + posts on miss; replicas |
| PostgreSQL primary | Failover | Posting fails for ~30 s | Client retries with the same Idempotency-Key |
| Kafka | Cluster down | Posts saved, feeds stale | Outbox keeps rows until the relay catches up |
Monitoring: feed p99 and error rate (the SLO), Kafka consumer lag, fan-out writes/s, cache hit ratio, replica lag. Evolution: at 10x, shard posts by author_id and move to Redis Cluster; add a ranking service (changes the read path); add a read-only second region.
Worked example 3: ride matching skeleton (write-heavy, geospatial)
This is a skeleton for the method, not a description of how any company does it. For what Uber has published about its own system, see the Uber case study; everything below about architecture is our inference from the requirements. One published fact we use: H3, the hexagonal grid, "was developed to address the challenges of Uber's data science needs" (h3geo.org).
Step 1, scope. F1: drivers report their location every 4 s while online. F2: a rider requests a ride; the system finds nearby available drivers and offers the trip. F3: a driver holds at most one trip. NFRs: 99.99% for ride requests per city; match decision p99 under 2 s; strong consistency for assignment, positions may be seconds stale. Out of scope: pricing and surge, payments, ETA routing, onboarding. Assumptions: 1 M drivers a day, online 8 h, one update every 4 s (7,200 per driver per day); 10 M rides a day; a stored location point is 50 bytes; raw points kept 30 days.
Step 2, estimate.
| Quantity | Value | How |
|---|---|---|
| Location writes, average / peak | 83,333 / 125,000 per s | 1 M x 7,200 / 86,400, x1.5 |
| Match requests, average / peak | 116 / 174 per s | 10 M / 86,400, x1.5 (city rush hours are higher; size per city) |
| Read/write ratio | 1:720 | Write-heavy: the opposite of the feed |
| Raw location storage | 360 GB/day, 32.4 TB for 30 days x3 | 7.2 B x 50 B x 30 x 3 |
| Live positions in memory | 300 MB | 1 M x 100 B x 3 |
| Ingest bandwidth | about 25 MB/s, 200 Mbit/s | 125,000 x ~200 B on the wire (assumption) |
| Ingest servers | 23 | ceil(125,174 / (10,000 x 0.6)) + 2 |
The surprise is the opposite of the news feed's: the "product" request (match) is tiny, and the background write (location) is the system.
Step 3, high-level design.
CREATE TABLE driver_state (
driver_id bigint PRIMARY KEY,
city text NOT NULL,
status text NOT NULL CHECK (status IN ('OFFLINE','AVAILABLE','OFFERED','ON_TRIP')),
ride_id bigint,
version bigint NOT NULL DEFAULT 0,
updated_at timestamptz NOT NULL DEFAULT now()
);
-- The consistency boundary: claim a driver only if still available (compare-and-set).
UPDATE driver_state
SET status = 'OFFERED', ride_id = $1, version = version + 1, updated_at = now()
WHERE driver_id = $2 AND status = 'AVAILABLE' AND version = $3;
-- 1 row updated: the offer is ours. 0 rows: another matcher won; try the next driver.The picture separates the two paths: location ingest writes the latest position into a Redis GEO set per city (GEOADD) and the raw point into Kafka; the matcher searches with GEOSEARCH drivers:{city} FROMLONLAT lng lat BYRADIUS 2 km COUNT 20 ASC (Redis 6.2.0+, complexity "O(N+log(M))") and claims one driver with the conditional update above. Positions are eventually consistent; the claim is strongly consistent.
Step 4, decisions.
| Decision | Options | Choice | Consequence |
|---|---|---|---|
| Geospatial index | PostgreSQL + PostGIS; Redis GEO per city; H3 cells in memory | Redis GEO per city now; H3 cells if radius search becomes the bottleneck | Positions not durable; rebuilt within 4 s (Geospatial Indexing) |
| Double assignment | Distributed lock; conditional update with version; single matcher per city | Conditional update (compare-and-set) | Losing matcher retries the next driver; no lock service (Distributed Locking) |
| Partitioning | By driver_id hash; by city/region | By city | Natural locality; big cities may need sub-city cells |
| Location history | Store every point in PostgreSQL; Kafka to object storage | Kafka to object storage, 30 days | Cheap; analytics reads from the lake |
| Component | Failure | User impact | Mitigation |
|---|---|---|---|
| Redis GEO city shard | Lost | No matches in that city for seconds | Replica promotion; positions refill within 4 s |
| Matcher | Crash mid-offer | Driver stuck in OFFERED | Expiry job resets OFFERED after 10 s |
| Ingest | Overloaded | Stale positions, worse matches | Shed every other update (positions are idempotent, last write wins) |
Monitoring: match latency p99, unmatched requests per city, ingest lag, expired offers. Evolution: partition everything by city or region (a cell per region), move to H3 cells, then multi-region active-active by city.
Anti-pattern: jumping to microservices
Symptom: the first diagram has ten services, a service mesh and three regions for a team of six. Why it fails: every service boundary is a network call with its own failure modes, deployments and on-call; the team spends its time on plumbing. Fowler's MonolithFirst (3 June 2015) reports the pattern: "Almost all the successful microservice stories have started with a monolith that got too big and was broken up" (Monolith vs Microservices vs Modular Monolith).
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Modular monolith first | Modules with owned tables and interfaces, one deployable | One deploy, in-process calls, transactions | Discipline needed to keep module boundaries (Modular Monolith) |
| Split by scaling need | Separate only the part whose numbers differ (fan-out workers, location ingest) | Spend complexity where the estimate demands it | Needs the estimate first |
| Split by team | One service per team that must deploy independently | Conway-aligned | Only valid when teams exist (Service Boundaries) |
The Go linter flags it as ANTI001 (microservices with 6 engineers: start with a modular monolith).
Anti-pattern: premature sharding
Symptom: "we shard by user_id from day one" for 3 writes per second and 110 GB. Why it fails: cross-shard queries, resharding, distributed transactions and operational load arrive immediately; the benefit arrives never. The box-first example has exactly these numbers.
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Vertical scale + replicas | Bigger primary, read replicas for reads | No application change | Write ceiling of one node (Storage & Data Scaling) |
| Partitioning inside one database | PostgreSQL declarative partitioning by time | Cheap retention (drop old partitions), smaller indexes | Still one primary (Partitioning & Sharding in PostgreSQL) |
| Choose the shard key now, shard later | Put author_id or city in every key and query | Sharding becomes a migration, not a rewrite | Must keep queries single-key |
| Shard when a trigger fires | Write IOPS > 60%, storage > one node, or writes > measured primary limit | Real need, known key | Planned migration work (Sharding at System Level) |
Linter code: ANTI002. The Laravel validator raises the same code from config/capacity.php.
Anti-pattern: ignoring the write path
Symptom: the read path is drawn with caches and CDNs; the write path is one arrow labelled "DB". Why it fails: the write path carries transactions, replication, index maintenance, events, cache invalidation and fan-out. In the news feed, 347 posts/s become 69,792 list writes/s; in ride matching, the write path is 720 times the read path.
Question to ask about every write News feed answer
1 What else must change in the same transaction? outbox row
2 Who must hear about it, and how fast? followers' feeds, within 5 s
3 How many internal writes does one user write cause? 201
4 What happens if the second half fails? relay retries; fan-out idempotent
5 Which caches become stale? feed lists (appended), post cache (none: posts immutable)| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Size writes after fan-out | Multiply by fan-out and index count in step 2 | The real bottleneck appears in the estimate | Needs the shape (followers distribution) |
| Make the expensive part asynchronous | Outbox + queue + workers | User latency independent of fan-out | Eventual consistency; lag to monitor |
| Bound the amplification | Celebrity threshold, batching, write coalescing | Caps worst case | Two code paths (Write Buffering) |
Linter code: HLD002 (no write path) and ANTI003 (fan-out not addressed by any decision).
Other anti-patterns
| Anti-pattern | Symptom | Fix |
|---|---|---|
| Silent scope | No questions asked; the design answers a different problem | Step 1 question bank, written answers |
| Average-only sizing | Servers sized for average QPS | Peak factor, N+2, utilisation target |
| Precision theatre | Five significant digits on guessed inputs | Round; say "about"; spend precision where it changes the design |
| Technology shopping list | Every popular product appears once | Each box justified by a number or requirement |
| No alternatives | Every decision has one option | ADR with at least two options (DEC001) |
| Perfect design | "Nothing can be improved" | Xu: "Never say your design is perfect and nothing can be improved." |
| Consistency hand-waving | "Eventually consistent" everywhere, or strong everywhere | Consistency per path in the workload shape |
| Design for 100x today | Multi-region active-active for a beta | Evolution plan with triggers |
Choosing
How much of each step
| Situation | Scope | Estimate | High-level design | Decisions | Artifact |
|---|---|---|---|---|---|
| 45-minute interview | 5-8 min, spoken, written on the board | Only the numbers that change the design | One diagram, two flows | 2 deep dives chosen with the interviewer | Whiteboard |
| Small feature in an existing system | Half a page | Skip unless it changes load | Changed components only | 1 ADR if a real choice exists | Mini design doc (1-3 pages) |
| New service | Full, with non-goals | Full, per path | Full | 2-4 ADRs, failure table, monitoring | Design doc (5-10 pages) |
| New large system or platform | Full, with stakeholders | Full, with load tests | Full, plus migration | Many ADRs, security and privacy reviews | Design doc (10-20 pages) + ADR directory |
| Incident follow-up | The failure as the requirement | Load at the incident | The changed path | 1-2 ADRs | Postmortem + ADR |
Which number decides which component
| If the estimate says | Then consider | Not yet |
|---|---|---|
| Peak reads in the thousands, data fits one node | One database + read replicas + cache-aside | Sharding |
| Read/write above 10:1 and staleness allowed | Cache, CDN, precomputed views | Strong-consistency stores everywhere |
| Writes beyond one primary (measured) | Partitioning by key, write batching, log-structured stores | Multi-leader replication |
| Fan-out over 10x per write | Async workers, hybrid fan-out, coalescing | Synchronous fan-out in the request |
| Payload x QPS near a NIC or egress budget | CDN, compression, presigned uploads | Bigger app servers |
| Users on several continents with a strict latency SLO | Regional stacks, GeoDNS, local reads | Global synchronous writes |
| Availability target 99.99% or higher | Multi-AZ, automatic failover, N+2, no single region | Manual failover |
| Strong consistency on a few keys | Conditional writes or a single leader for those keys | A distributed lock service by default |
In architecture: from a single process to a distributed system
The four steps do not change with scale; what changes is how much each step can hide inside one process.
Monolith: one process, one database
How it shows up: scope and estimate are the same; the high-level design is one deployable, one PostgreSQL, maybe Redis. Step 4's decisions are mostly about the database: indexes, transactions, connection pool, backups.
Example (simple): an internal booking tool for 500 users: 2 QPS peak, 5 GB, one Laravel app, one PostgreSQL, 99.5%. The design doc is two pages and one ADR ("PostgreSQL, not a document store, because bookings need a unique constraint on room and slot").
Example (production-shaped): the news feed at 100k DAU: 35 feed reads/s peak, 3.5 writes/s, fan-out 700 writes/s, all inside one Laravel app with Redis lists and a queued job for fan-out. The same design doc template, but the estimate says one primary and one Redis are enough.
Modular monolith: boundaries without the network
How it shows up: step 3 adds module boundaries: each module owns its tables and exposes an interface; the data flows cross module APIs in process. Step 4 records which modules may later become services and why.
Example: posts, feeds and users as three Laravel modules (or Go packages) with their own tables; feeds read posts through a PostQuery interface, never through SQL joins into posts' tables. The ADR "split feeds out when fan-out workers need independent scaling" carries the trigger. See Modular Monolith.
Microservices: every arrow is a decision
How it shows up: each arrow in the component diagram becomes a network contract with a timeout, a retry policy, an idempotency rule and a failure mode. Step 2 is done per service; step 4 adds sagas, outbox and contract tests.
Example: ride matching with location ingest, matcher and trip service as separate services: the matcher calls the trip service synchronously to create a ride (POST /v1/rides, Idempotency-Key), the trip service publishes RideOffered through an outbox, the driver app accepts with a conditional update. Each arrow has its own row in the failure table. See Service Communication and Saga.
Distributed data: replicas, caches, regions
How it shows up: step 1's consistency requirement per path becomes concrete choices: which reads go to replicas (and tolerate lag), which go to the leader (read-your-writes), what the cache may serve stale, which writes need quorum or a conditional update, which data must stay in a region.
Example: the news feed with replicas and Redis: a user's own post is read from the primary for 5 s after writing (read-your-writes), friends' feeds come from Redis lists (seconds stale), replica lag is a monitored SLI. In ride matching, positions are per-city Redis (lossy, rebuilt in 4 s) while assignment is a conditional update on the city's PostgreSQL primary. See Replication Topologies and Replication & Failover.
Scaling path: 1x, 10x, 100x
| Scale | News feed | Ride matching | Rate limiter |
|---|---|---|---|
| 1x (this page) | One primary + replicas, Redis lists, Kafka fan-out, 15 app servers | Redis GEO per city, 23 ingest nodes, PostgreSQL per region | Gateway middleware + one Redis primary/replica |
| 10x | Shard posts by author_id; Redis Cluster; more Kafka partitions; celebrity threshold tuned | Sub-city cells (H3); ingest per region; matcher per cell | Redis Cluster sharded by key; local pre-checks |
| 100x | Multi-region reads, ranking service, tiered storage for old posts | Cell-based architecture per region; active-active by city | Per-region limits, approximate global limits |
| Trigger to move | Write IOPS > 60%, Redis memory > 70%, consumer lag > 5 s | Largest city's Redis CPU > 60%, match p99 > 1.5 s | Redis CPU > 50% or limiter p99 > 1 ms |
Lab: estimate, lint and render three designs
The Go parts are single-process programs and were run; the Laravel part needs an application and is written as expected output, not run.
Setup. Copy docs/snippets/system-design/four-step-approach/go to a folder and run from the module root (Go 1.24 or newer).
Run the tests that pin the page's numbers.
bashgo test ./... # ? academy/four-step-approach/before [no test files] # ? academy/four-step-approach/cmd/designdoc [no test files] # ok academy/four-step-approach/designdoc # ok academy/four-step-approach/estimate # ok academy/four-step-approach/examplesChange
FanOut: 200toFanOut: 500inexamples.goand run again:TestNumbersOnThePagefails withfeed peak fan-out writes/s = 173958.33, want 69792.00. The estimate is now a regression test for the design doc.Lint the box-first design.
bashgo run ./before go run ./cmd/designdoc -example boxfirst -lint # lint boxfirst: 10 findings # SCOPE002 no availability target or SLO in non-functional requirements # SCOPE003 out of scope is empty: say what you will not build # SCOPE004 no written assumptions # HLD001 no API sketch: start step 3 with the API # HLD002 no write path: every design needs the path that changes state # DEC001 ADR-1 "Use Cassandra" has fewer than two options: a decision needs an alternative # DEC003 no failure modes # DEC004 nothing to monitor # ANTI001 microservices with 6 engineers: start with a modular monolith # ANTI002 sharding at 3 peak writes/s and 110 GB: premature # exit status 1Render the three worked designs.
bashgo run ./cmd/designdoc -example all -lint # lint ratelimiter: 0 findings # lint newsfeed: 0 findings # lint ridematching: 0 findings go run ./cmd/designdoc -example newsfeed | sed -n '/## 2. Estimate/,/## 3/p' # | Average read / write QPS | 1157 / 116 | # | Peak read / write QPS (x3) | 3472 / 347 | # | Peak internal writes after fan-out | 69792 | # | Read/write ratio | 10:1 | # | Bytes written per day (one copy) | 10 GB | # | Stored: 1825 days retention x3 copies | 54.8 TB | # | Peak egress | 69.4 MB/s (556 Mbit/s) | # | Cache (hot 0.2 of daily reads) | 400 GB | # | Live key state in memory | 0 B | # | App servers (N+2) | 15 |Break the write path on purpose. In
NewsFeed(), remove the "Fan-out on write vs read" decision and rungo run ./cmd/designdoc -example newsfeed -lint. Expected:ANTI003 fan-out multiplies writes 201x but no decision mentions fan-out, exit status 1.The Laravel side (expected, not run). Copy the
php/tree into a Laravel 13 application (config/capacity.php,app/Support/Capacity/*,app/Console/Commands/DesignCheck.php,tests/Unit/CapacityEstimatorTest.php).bashphp artisan design:check news-feed # == news-feed # +--------------------------------+-----------------+ # | Quantity | Value | # +--------------------------------+-----------------+ # | Peak read / write QPS | 3472 / 347 | # | Peak internal writes (fan-out) | 69792 | # | Storage incl. replicas | 54.8 TB | # | Peak egress | 556 Mbit/s | # | Cache (80/20) | 400 GB | # | App servers | 15 | # | Downtime budget | 262.8 min/year | # +--------------------------------+-----------------+ # ANTI003 fan-out turns 347 writes/s into 69792: size the write path, not only reads # CAP002 cache of 400 GB needs 16 Redis nodes echo $? # 0: info findings only CAPACITY_PRIMARY_WRITE_QPS=1000 php artisan design:check ride-matching; echo $? # 0: sharded, so no CAP001 php artisan design:check news-fed; echo $? # ERROR Unknown system [news-fed] in config/capacity.php. # 1 php artisan test --filter=CapacityEstimatorTest # PASS Tests\Unit\CapacityEstimatorTest (2 tests)The estimator and validator classes were also exercised outside Laravel with a stub
env()and produced the table values above; the Artisan output format itself is expected, not run.Exercise. Write the design doc for a URL shortener with the template (100 M new URLs a month, 10:1 redirects to creations, 5 years retention) and make
Lintreturn zero findings. Compare with the worked sketch in Database System Design.
Common misconceptions
| Belief | Reality |
|---|---|
| The estimate is a ritual for the interviewer | It is the step that most often changes the design (news feed: 69,792 writes/s after fan-out) |
| More features show more skill | Three core features done well; out of scope keeps the design honest |
| "Highly available and fast" are requirements | Requirements have numbers: p99 under 300 ms, 99.95% |
| Average QPS sizes the servers | Peak x headroom + N+2 sizes them |
| QPS is the whole workload | Read/write ratio, fan-out, payload size and consistency per path matter as much; the SRE book warns QPS is a poor proxy |
| Cache 20% of daily read volume | That is an upper bound; distinct hot items x size is often 10x smaller |
| Start with microservices to be scalable | Fowler: "Almost all the successful microservice stories have started with a monolith" |
| Shard early to avoid resharding | Choose the key early, shard when a measured trigger fires |
| The write path is one arrow | It carries transactions, events, fan-out and invalidation, and often sets the largest number |
| A decision with one option is fine | No alternative means no decision; ADRs list options and consequences |
| A design doc is an implementation manual | It records trade-offs and alternatives; code is the manual |
| There is one right answer | Xu: "There is neither the right answer nor the best answer"; the process is graded |
| 100% availability is the goal | The SRE book: "reliable enough, but no more reliable than it needs to be" |
| Latency numbers must be exact | Ratios and orders of magnitude matter; measure for real values |
Cheat sheet
| Topic | Remember |
|---|---|
| The four steps | Scope -> Estimate -> High-level design -> Decisions, with loops back to scope |
| Step 1 | F1..Fn verbs; NFRs with numbers; out of scope; assumptions with sources; users, regions, R/W ratio, consistency per path |
| QPS | per day / 86,400 (about 10^5); 1 M/day is about 12 QPS |
| Peak | x2-3 global, x5-10 local or launch; size for peak |
| Storage | writes/day x bytes x retention x replicas, + indexes |
| Bandwidth | QPS x payload; x8 for bits; media via CDN |
| Cache | min(volume x 0.2, distinct hot items x size); measure hit ratio |
| Servers | ceil(peak / (per-node x 0.5-0.7)) + 2 |
| Nines | 99.9% = 8.76 h/yr; 99.99% = 52.56 min/yr |
| Latency | memory 100 ns; in-DC round trip 0.5 ms; disk seek 10 ms; CA-NL-CA 150 ms |
| Step 3 | API first, then data model, then components, then read AND write flows |
| Step 4 | Bottlenecks, SPOFs, 2-3 deep dives, ADRs with options, failure table, monitoring, evolution |
| ADR | Title, Context, Decision, Status, Consequences; supersede, never edit |
| Design doc | Context, goals/non-goals, design, alternatives, cross-cutting concerns; 1-3 or 10-20 pages |
| Anti-patterns | Microservices first, premature sharding, ignoring the write path |
| Interview time | Scope 3-10, high level 10-15, deep dive 10-25, wrap up 3-5 minutes (Xu) |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Name the four steps and the artifact each produces. Must-know
Answer
Answer: Scope (functional and non-functional requirements, out of scope, assumptions), estimate (QPS and peak, storage, bandwidth, cache, servers), high-level design (API, data model, component diagram, read and write flows), decisions (bottlenecks, deep dives, ADRs, failure modes, monitoring, evolution). See Everything in one minute.
2 — Rewrite "the system should be fast and highly available" as two testable requirements. Must-know
Answer
Answer: For example: "Feed read p99 under 300 ms measured at the load balancer over 28 days" and "99.95% of valid feed reads succeed over 28 days (about 21.6 minutes of failures per 30 days)". See Non-functional requirements.
3 — What is the difference between a non-goal and a negated goal? Important
Answer
Answer: A negated goal ("the system shouldn't crash") is not a choice. A non-goal is something that could reasonably be a goal but is explicitly excluded, such as ranking in a first feed or ACID compliance for a cache (Ubl). See Out of scope.
4 — 50 M DAU, each doing 4 writes a day, peak factor 3. What is the peak write QPS? Must-know
Answer
Answer: 50 M x 4 = 200 M per day; / 86,400 = about 2,315 average; x3 = about 6,944 per second at peak. See QPS.
5 — Why does the 80/20 formula overstate the news-feed cache, and what is the better estimate? Important
Answer
Answer: It multiplies daily read volume (every repeated read of the same hot item) by 0.2, giving 400 GB. The distinct hot set is the latest 500 post ids per active user: 10 M x 500 x 8 B = 40 GB raw, about 80 GB with Redis overhead. See Cache sizing.
6 — A tier needs 3,819 QPS at peak, one server handles 500 QPS, and you plan 60% utilisation with N+2. How many servers? Must-know
Answer
Answer: ceil(3,819 / 300) = 13, plus 2 = 15. See Servers.
7 — In the news feed, which number changes the design most, and what does it change? Must-know
Answer
Answer: Fan-out: 347 posts/s become 69,792 feed-list writes/s. It moves feed lists to Redis, makes fan-out asynchronous behind an outbox and Kafka, and adds the hybrid rule that pulls celebrity posts at read time. See the news feed and ignoring the write path.
8 — How does the ride-matching skeleton prevent two riders from getting the same driver without a distributed lock? Important
Answer
Answer: A conditional update on driver_state (WHERE status = 'AVAILABLE' AND version = $3): exactly one matcher gets one row updated; the others get zero rows and try the next driver. Positions stay eventually consistent; only the claim is strong. See ride matching.
9 — Why does the rate limiter fail open, and what must exist for that to be safe? Important
Answer
Answer: Its job is to protect the API, and a limiter outage must not become an API outage (Stripe's advice). Fail-open needs a tight timeout (5 ms), a fail_open counter with an alert, and other layers (CDN/WAF) for real attacks. See the rate limiter.
10 — What makes a decision "architecturally significant" in Nygard's ADR proposal, and what happens when it is reversed? Important
Answer
Answer: It affects "the structure, non-functional characteristics, dependencies, interfaces, or construction techniques". A reversed decision is kept and marked superseded, with a link to the new ADR. See Trade-offs and ADRs.
11 — Give two signs that sharding is premature, and what to do instead. Must-know
Answer
Answer: Peak writes far below what one measured primary handles (the box-first example: 3 writes/s) and data that fits one node (110 GB). Instead: one primary with replicas, time partitioning, and a shard key chosen now so sharding later is a migration. See premature sharding.
12 — In a 45-minute interview, the interviewer says "assume it all fits on one machine" during your estimate. What do you do? Must-know
Answer
Answer: Write the assumption down, skip the rest of the estimate, and move to the high-level design; the interviewer wants time for the deep dive. Come back to numbers only if a deep dive needs them. See Interview mode.
Glossary
| Term | Meaning |
|---|---|
| Four-step approach | Scope, estimate, high-level design, decisions (deep dives); the method of this page |
| Scope | Agreed boundary of what is being designed |
| Functional requirements | Observable behaviours: what users and systems can do |
| Non-functional requirements | Measurable quality targets: latency, availability, durability, consistency, cost, security |
| Out of scope / non-goals | Things that could be goals but are explicitly excluded |
| Assumptions | Unverified facts the design depends on, written with their source |
| Workload shape | Actors, regions, request mix, read/write ratio, hot keys, consistency per path |
| Read/write ratio | Read QPS divided by write QPS; decides caching and storage choices |
| Consistency requirement | Which writes a given read must see (read-your-writes, bounded staleness, linearizable) |
| DAU / MAU | Daily / monthly active users; DAU/MAU is stickiness |
| QPS | Queries (requests) per second; average = per day / 86,400 |
| Peak-to-average | Ratio of the busiest interval's rate to the mean rate |
| Back-of-the-envelope | Quick order-of-magnitude estimate before building (Dean) |
| Storage estimate | writes/day x bytes x retention x replication, plus overhead |
| Retention | How long data is kept before deletion or archiving |
| Replication factor | Number of copies a store keeps |
| Bandwidth | Bytes or bits per second in (ingress) and out (egress) |
| Cache sizing | Estimating memory for the hot set; bounded by volume and by distinct items |
| 80/20 rule / Pareto principle | A small fraction of items receives most accesses |
| Headroom / target utilisation | Spare capacity kept free at peak, typically 30-50% |
| N+2 | Enough nodes to lose one to failure while another is in maintenance |
| Latency numbers | Dean's and Norvig's orders of magnitude for memory, disk and network |
| Powers of two | 2^10 KiB, 2^20 MiB, 2^30 GiB, 2^40 TiB; binary vs decimal units |
| Availability target | Required fraction of successful requests or uptime, in "nines" |
| SLI / SLO / error budget | Indicator / target on it / what the target allows to fail |
| p99 / tail latency | The 99th-percentile latency; the slow tail users notice |
| API design | Operations, parameters, responses, pagination, idempotency, errors |
| Idempotency key | Client-chosen key that makes a retried request safe |
| Data model | Entities, keys, stores and indexes chosen from access patterns |
| High-level design | The smallest component design that meets requirements and numbers |
| Component diagram | Boxes (clients, services, stores, queues) and connections |
| System context diagram | The system in its larger landscape (Ubl) |
| Data flow | Numbered path of one operation through components |
| Read path / write path | The flow that serves data / the flow that changes it |
| Fan-out | One write causing many internal writes (feeds, notifications) |
| Bottleneck | The resource that saturates first |
| Single point of failure (SPOF) | A component whose loss stops a core path |
| Deep dive | Focused design work on one risky component or bottleneck |
| Trade-off | What you give up to get something; recorded per decision |
| Trade-off table | Options compared against requirements |
| ADR | Architecture Decision Record: Title, Context, Decision, Status, Consequences (Nygard) |
| Superseded | ADR status for a reversed decision, linked to its replacement |
| Failure mode | How a component fails, the user impact and the mitigation |
| Fail open / fail closed | On dependency failure, allow the request / deny it |
| Evolution | Planned design changes at 10x and 100x, with triggers |
| Monitoring | SLIs and leading indicators with thresholds that trigger the next step |
| Design doc | Document holding context, goals, design, alternatives and cross-cutting concerns |
| Mini design doc | 1-3 page design doc for incremental work (Ubl) |
| Well-Architected pillars | AWS's six: operational excellence, security, reliability, performance efficiency, cost optimization, sustainability |
| Premature sharding | Splitting a database before numbers require it |
| Modular monolith | One deployable with enforced module boundaries |
| Token bucket | Rate-limit algorithm: tokens refill at a rate up to a burst size |
| Geospatial index | Index for "near me" queries (Redis GEO, H3, geohash) |
| Compare-and-set | Conditional write that succeeds only if the value is unchanged |
| Interview mode | The four steps compressed into 45-60 minutes, spoken |
| Template / checklist | The reusable list of items each design must contain |
References
- Malte Ubl, "Design Docs at Google", Industrial Empathy, 6 July 2020
- Michael Nygard, "Documenting Architecture Decisions", Cognitect blog, 15 November 2011
- Martin Fowler, "Architecture Decision Record", bliki, 24 March 2026; "MonolithFirst", 3 June 2015
- Google SRE Book: "Service Level Objectives", "Embracing Risk", "Handling Overload", "Software Engineering in SRE" (intent-based capacity planning, Auxon); SRE Workbook "Implementing SLOs"
- Jeff Dean, "Software Engineering Advice from Building Large-Scale Distributed Systems", Stanford CS295 talk slides ("Numbers Everyone Should Know", back-of-the-envelope examples)
- Peter Norvig, "Teach Yourself Programming in Ten Years" (appendix "Approximate timing for various operations on a typical PC")
- Colin Scott, "Latency Numbers Every Programmer Should Know" (interactive) (a model, not measurements)
- Jeffrey Dean and Luiz André Barroso, "The Tail at Scale", CACM, February 2013
- Alex Xu, System Design Interview, "A Framework For System Design Interviews", ByteByteGo (secondary source, interview preparation)
- AWS, AWS Well-Architected Framework, Framework design principles, the six pillars
- Paul Tarjan, "Scaling your API with rate limiters", Stripe blog, 30 March 2017
- H3 introduction (h3geo.org); Redis
GEOSEARCHandINCR(rate limiter pattern) - RFC 6585 (429 Too Many Requests); RFC 9110 (HTTP Semantics,
Retry-After) - Laravel 13: Artisan Console, Configuration, Rate Limiting, Task Scheduling
- Go:
testing,text/template