What System Design Is and How It Evolved
"Reliability at massive scale is one of the biggest challenges we face at Amazon.com, one of the largest e-commerce operations in the world; even the slightest outage has significant financial consequences and impacts customer trust." — DeCandia et al., Dynamo: Amazon's Highly Available Key-value Store, SOSP 2007
Summary: System design is the work of turning requirements into a structure of components, data flows and trade-offs that keeps working when load grows and parts fail. This chapter is the map of the whole section: the definition, the 60-year history of why the shapes changed, the shared vocabulary, a first worked sketch (a URL shortener) and a one-line tour of every other chapter. Focus: Functional and non-functional requirements, availability and nines, reliability, fault tolerance, redundancy and single points of failure, latency and throughput, consistency and CAP, durability, scalability and elasticity, stateless and stateful, the standard building blocks (load balancer, cache, CDN, message queue, database, replication, sharding), SLI/SLO/SLA, cost, back-of-the-envelope arithmetic, and the eras from mainframe to serverless and edge. Learning goal: Read any system diagram and say which requirement each box serves and which trade-off it bought; use the vocabulary precisely; do the arithmetic for nines, rates and storage on a napkin; sketch a small system end to end before the 4-step approach turns the sketch into a method.
This is chapter one of the System Design path. It teaches nothing in depth. Software design (classes, modules, patterns) is in Architecture vs Design; the structural decisions that outlive any one system are in What Is Software Architecture; estimation method and SLOs live in Capacity Estimation and SLA, SLO, SLI & Error Budgets. Database internals are in the Database path, brokers in the Messaging path. Here we give names to the things the other chapters take apart.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in four tables | Everything in one minute |
| Why system design exists as a discipline | Why it exists |
| Mainframe to serverless, with the forces behind each shift | Where it comes from |
| What system design is, and what it is not | Definition |
| Functional vs non-functional requirements | Requirements |
| Nines, uptime, serial and parallel availability | Availability, Nines arithmetic |
| Reliability, fault tolerance, redundancy, SPOF | Reliability |
| Latency, throughput, tail, napkin math | Latency and throughput, Numbers |
| Consistency, CAP, partition tolerance | Consistency |
| Durability, RPO, RTO | Durability |
| Scalability, elasticity, stateless vs stateful | Scalability |
| Load balancer, cache, CDN, queue, database, replication, sharding | Building blocks |
| SLI, SLO, SLA, error budget | Service levels |
| Cost and trade-offs | Cost, Trade-offs |
| A first complete design | URL shortener sketch |
| Code | Go, Laravel |
| Every other chapter in one sentence | Tour of the path |
| Interview vs real life | Two audiences |
| Monolith to distributed system | In architecture |
| Practice with numbers | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
What system design is, next to its neighbours.
| Discipline | Question it answers | Typical unit | Typical artefact | Chapter |
|---|---|---|---|---|
| Software design | How is the code inside one program shaped? | Class, module, function | UML, interfaces, patterns | Architecture vs Design |
| Software architecture | Which structural decisions are costly to change? | Component, style, quality attribute | ADRs, views, fitness functions | What Is Software Architecture |
| System design | How do components, data and traffic fit together so the whole meets its numbers? | Service, store, queue, region | Diagram + estimates + trade-off table | This path |
| Infrastructure and operations | How is it deployed, watched and recovered? | Cluster, pipeline, runbook | Terraform, dashboards, on-call | Containers & Kubernetes |
The eras.
| Era | Typical shape | Force that created it | Price paid |
|---|---|---|---|
| Mainframe (1960s-70s) | One big machine, dumb terminals | Computers were rare and expensive | Scale means buying a bigger machine |
| Client-server (1980s) | Rich client talks to a database server | Cheap PCs and LANs | Logic scattered over desktops, painful deploys |
| Three-tier web (late 1990s) | Browser, app server, database | The browser as a zero-install client | One database becomes the bottleneck |
| SOA (2000s) | Services behind a bus | Integrating many enterprise systems | Heavy middleware and standards |
| Cloud and microservices (2006-2015 on) | Fleets of small services on commodity servers | Moore's law slowing for one core, cloud rental, Dynamo/Bigtable/MapReduce, containers, Kubernetes | Distributed-systems failure modes everywhere |
| Serverless and edge (2014 on) | Functions and caches near the user | Pay per use, latency to the user | Cold starts, limits, vendor shapes |
The vocabulary.
| Term | One line | A number to remember |
|---|---|---|
| Availability | Fraction of time (or requests) the system works | 99.99% allows 52.56 minutes down a year |
| Reliability | Does the right thing, even with faults | Measured as failure rate, MTBF |
| Fault tolerance | Keeps serving through a component failure | Needs redundancy plus failover |
| Latency | Time for one request | Same-datacenter round trip is about 500 microseconds |
| Throughput | Requests or bytes per unit time | Little's law: in flight = rate x latency |
| Consistency | Do readers see the latest write? | Linearizable vs eventual |
| Durability | Once acknowledged, data survives | Counted in copies and years, not nines of uptime |
| Scalability | Grows by adding resources | Horizontal needs stateless or sharded state |
| Elasticity | Grows and shrinks automatically with load | Autoscaling reaction time in seconds to minutes |
| Cost | Money per request or per month | Often the constraint that decides |
The picture groups the vocabulary into speed, staying up, correctness, growth and money; they pull against each other, and SLIs, SLOs and SLAs are how you measure the pull.
The standard building blocks.
| Block | Solves | Introduces | Chapter |
|---|---|---|---|
| Load balancer | Spread requests, hide dead servers | Another hop, a part that must itself be redundant | Load Balancing |
| Cache | Repeated reads are fast and cheap | Staleness, invalidation, stampedes | Caching |
| CDN | Static and cacheable content close to the user | Purge delays, cache keys | CDNs |
| Message queue | Absorb bursts, decouple producer and consumer | Delay, duplicates, ordering | Messaging Fundamentals |
| Database | Durable, queryable state | The hardest thing to scale | Choosing a Database |
| Replication | Copies for reads and failover | Lag, conflicts | Replication Topologies |
| Sharding | Split data across machines | Hot keys, cross-shard queries | Sharding at System Level |
The picture is the history in one row: each box is an era and each caption is the force that ended the previous one. The questions never change; the place where the answers live does.
Why it exists
One program on one machine has a short list of problems. Add a second machine, a network between them, and users who expect it to work at 3 a.m. on Black Friday, and every simple thing becomes a decision: where is the state, who may write, what happens when the call times out, how many copies are enough, how much does that cost. System design is the discipline of making those decisions on purpose, before the incident makes them for you.
| Without a design pass | With one |
|---|---|
| Components appear as features arrive | Components exist because a requirement or a number demands them |
| "It scales" is a hope | "It handles 20,000 reads/s because the cache absorbs 95% of them" is a claim with arithmetic |
| Failure is discovered in production | Failure modes are listed and each has an answer or an accepted risk |
| One favourite technology everywhere | Each store, queue and cache is chosen for its access pattern |
| Cost surprises at the invoice | Cost per request is part of the estimate |
| Arguments about taste | Arguments about numbers and trade-offs |
The analogy we reuse on this page: building a restaurant, not cooking a dish. Cooking one dish is software design: the recipe, the order of steps. Designing the restaurant is system design: how many cooks and stoves (throughput), how long a guest waits for a table (latency), what happens when the fryer breaks (fault tolerance), whether a second location is worth the rent (cost), what the menu promises (SLA), and how the kitchen handles a bus tour arriving unannounced (elasticity). The recipe matters, but a perfect recipe cannot fix a kitchen with one stove and no door at the back.
Three common misunderstandings, up front
- "System design means drawing boxes for interviews." The boxes are the output; the work is the requirements, the numbers and the trade-offs behind each box. A diagram without those is decoration.
- "Good system design means microservices, Kafka and Kubernetes." A single PostgreSQL server behind one Laravel or Go process serves a very large number of products. The design that fits the requirements is correct; the fashionable one is a cost. Every added box is a new failure mode.
- "There is a best design." There is a design that is best for these requirements, this team and this budget. Dynamo chose availability over consistency for shopping carts; Spanner chose consistency and paid in latency and atomic-clock hardware. Both are right for their requirement.
Where it comes from
The word "design" is old; the field of designing distributed systems on purpose is mostly a story of one forcing function after another.
Mainframes (1960s-70s). One expensive machine, shared by time-slicing. The design question was capacity planning: how big a machine to buy. Availability meant the vendor's maintenance contract.
Client-server (1980s). Cheap PCs and local networks moved the interface to the desktop and kept the data on a server. It was the first time a call could fail halfway, but the system was still small enough for one team to reason about.
Three-tier web (late 1990s). The browser removed client installation, and the stack settled into presentation, application and data tiers. Martin Fowler's description of the era's default is still the clearest: enterprise applications "are often built in three main parts: a client-side user interface ... a database ... and a server-side application", and that server-side application "is a monolith - a single logical executable." Scaling meant cloning the application tier behind a load balancer and buying a bigger database. This is still the right first design for most products.
SOA (2000s). Large enterprises needed their many systems to talk. Fowler's 2005 note on the term is a warning about vocabulary as much as history: "SOA means so many different things to different people." Service Oriented Architecture introduced contracts, discovery and orchestration, and also heavyweight middleware; its lasting contribution is the idea that a service is a unit with a published interface.
The web-scale papers (2003-2012). A small group of publications changed what engineers believed possible on cheap hardware. MapReduce (Dean and Ghemawat, OSDI 2004) is "a programming model and an associated implementation for processing and generating large data sets" that "runs on a large cluster of commodity machines." Bigtable (Chang et al., OSDI 2006) is "a distributed storage system for managing structured data that is designed to scale to a very large size: petabytes of data across thousands of commodity servers." Dynamo (DeCandia et al., SOSP 2007) is "a highly available key-value storage system" that, to reach its availability, "sacrifices consistency under certain failure scenarios." Spanner (Corbett et al., OSDI 2012) is "the first system to distribute data at global scale and support externally-consistent distributed transactions." Between them: the case for commodity hardware, for treating failure as normal, for choosing availability or consistency explicitly, and for putting the trade-off in the API.
The end of the free lunch. Single-core speed stopped doubling every couple of years in the mid-2000s, and vendors added cores instead. To use more compute a program had to be spread over more cores and, at scale, more machines. Horizontal scaling stopped being exotic. (This is the usual account of Moore's law and its consequences; the chapter does not quote a primary source for it.)
Cloud and microservices (2006 on). The NIST definition (SP 800-145, September 2011) describes cloud computing as "a model for enabling ubiquitous, convenient, on-demand network access to a shared pool of configurable computing resources ... that can be rapidly provisioned and released with minimal management effort." Renting servers by the hour removed the purchasing lead time. Fowler and Lewis's microservice article (2014) describes the style as "an approach to developing a single application as a suite of small services, each running in its own process and communicating with lightweight mechanisms", "independently deployable by fully automated deployment machinery". Containers packaged the process and Kubernetes scheduled the fleet.
Serverless and edge (2014 on). Fowler's serverless article defines serverless architectures as "application designs that incorporate third-party 'Backend as a Service' (BaaS) services, and/or that include custom code run in managed, ephemeral containers on a 'Functions as a Service' (FaaS) platform." Edge computing pushes small pieces of that code and its caches into points of presence near users, so the speed of light costs less. Both trade control for a smaller operational surface.
Tail latency becomes a design input (2013). Dean and Barroso's The Tail at Scale made the point that outliers, not averages, rule large systems: "Temporary high latency episodes which are unimportant in moderate size systems may come to dominate overall service performance at large scale." The chapter Latency Budgets & Tail Latency takes it further.
Year Event What changed in practice
1 1960s Mainframe time-sharing Capacity planning by purchase order
2 1980s Client-server First partial failures across a network
3 1990s Browser + three-tier web Stateless app tier behind a load balancer
4 2000s SOA Service contracts and middleware
5 2004 MapReduce (OSDI) Commodity clusters, failure as normal
6 2006 Bigtable (OSDI); AWS rents servers Wide-column stores; rent instead of buy
7 2007 Dynamo (SOSP) Availability over consistency made explicit
8 2012 Spanner (OSDI) Global consistency with bounded clock error
9 2013 Tail at Scale (CACM) p99 treated as a design input
10 2014 Microservices article; containers; K8s One deployable per team; orchestrated fleets
11 2014+ Serverless functions, edge runtimes Pay per use, compute near the userThe concept catalogue
Each block follows the same order: plain words, the usual wrong belief, a definition, a flow or timeline, real scenarios, which products provide it, and how to use it. Blocks are short on purpose; the chapter named in each block owns the depth.
System design, and how it differs from software design and architecture Must-know
In plain words: system design decides which parts a system has, what each part owns, how data and requests move between them, and what the design costs in speed, safety and money.
Common misunderstanding: "System design and software architecture are the same job." They overlap, but the questions differ. Architecture is about decisions that are expensive to reverse inside a system (styles, boundaries, quality-attribute priorities), and lives for the life of the codebase. System design, in the sense of this path, is the concrete shape of a whole running system for a given load: which stores, which queues, how many replicas, where the cache sits. A modular monolith has an architecture and still needs system design the day it must serve ten times the traffic.
Definition: the process of defining the components, interfaces, data flows and deployment topology of a system so that it satisfies stated functional and non-functional requirements within stated constraints, with the trade-offs recorded.
Input Process Output
1 Requirements (what, how well) Scope and prioritise Agreed requirement list
2 Constraints (team, budget, law) Estimate load, storage, latency Numbers with stated assumptions
3 Numbers Choose blocks and place state High-level diagram
4 Diagram Probe failures and bottlenecks Decisions + trade-off table
5 Decisions Review, build, measure Revised design, SLOs, runbooksReal scenario: a startup asks "can our app survive a TV ad?"; a team splitting a monolith asks "which parts must be separately scalable?"; a bank asks "what happens to payments if one region is lost?"; an interviewer asks "design a URL shortener".
What provides it:
| Neighbour | Where the boundary falls | Use it when |
|---|---|---|
| Software design (Architecture vs Design) | Inside a process: classes, interfaces, patterns | You are choosing how to model the code |
| Software architecture (What Is Software Architecture) | Structural decisions and quality-attribute priorities for the whole codebase | You are choosing monolith, modular monolith or services |
| System design (this path) | Running topology and numbers: stores, queues, caches, regions, capacity | You are asking whether the whole thing meets its load and failure targets |
| Hohpe's framing (The Architect Elevator) | Communication between the business penthouse and the engine room | You must justify the cost of a design to people who do not read diagrams |
Fix / how to use it: start every design with a one-paragraph statement of purpose, a list of requirements and a list of numbers. Hohpe's summary of the modern architect applies to the designer too: replace "buzzwords with decision discipline, clear trade-offs, and a multi-dimensional solution space."
Requirements: functional and non-functional Must-know
In plain words: functional requirements say what the system does ("a user can shorten a URL and later follow it"); non-functional requirements say how well it must do it ("99.9% of redirects answer in under 100 ms, and no link is ever lost").
Common misunderstanding: "Non-functional requirements are polish for later." They decide the structure. A URL shortener that only needs to work for a hundred users is a single script; one that needs 99.99% availability across two regions is a different system with the same functional list.
Definition: Functional requirements describe behaviour and data (features, inputs, outputs, rules). Non-functional requirements (quality attributes: performance, availability, reliability, scalability, durability, security, cost, operability) describe measurable properties of that behaviour. Constraints are fixed from outside: budget, deadline, team skills, regulation, existing systems.
Vague wish Testable requirement
1 "Fast" p99 of GET /{code} under 100 ms at 20,000 requests/s
2 "Always up" 99.9% of redirects succeed per 30 days (SLO)
3 "Never lose a link" Acknowledged links survive loss of one zone (durability)
4 "Cheap" Under 0.5 USD per million redirects at average load
5 "Secure" No open redirect to non-http(s) schemes; abuse reports actionableReal scenario: the checkout page must show a price in 200 ms (latency) and must never charge twice (correctness); a photo app must accept uploads during a regional outage (availability) and may show likes a few seconds late (consistency); a payments system accepts being down for minutes but never wrong (consistency over availability).
What provides it:
| Practice | Product or artefact | Chapter |
|---|---|---|
| Write requirements as testable sentences | A table like the one above | 4-Step Approach |
| Turn a quality into a number | SLI, SLO | SLA, SLO, SLI & Error Budgets |
| Rank qualities that conflict | Quality attribute scenarios, utility tree | Requirements to Architecture |
Fix / how to use it: for every adjective ("fast", "reliable", "scalable") write the number, the unit, the percentile and the period. If nobody can give the number, write your assumption and mark it as one.
Availability and the nines Must-know
In plain words: availability is how often the system is up when someone needs it; "nines" count how many 9s are at the front of that percentage.
Common misunderstanding: "More nines is always better." Each extra nine is about ten times harder and costs more, and the user may not notice. Google's SRE book says it directly: "a user on a 99% reliable smartphone cannot tell the difference between 99.99% and 99.999% service reliability!" and "We strive to make a service reliable enough, but no more reliable than it needs to be."
Definition: availability = successful time (or requests) divided by total time (or requests) over a period. "Time-based" availability is uptime over total time. "Aggregate" availability is the fraction of requests that succeeded, which suits globally distributed services where some part is always up for someone. Each added nine is an order of magnitude less allowed downtime.
Target Downtime per year Per 30-day month Per week
1 99% 3.65 days 7.2 hours 1.68 hours
2 99.9% 8.76 hours 43.2 minutes 10.1 minutes
3 99.95% 4.38 hours 21.6 minutes 5.04 minutes
4 99.99% 52.56 minutes 4.32 minutes 1.01 minutes
5 99.999% 5.26 minutes 25.9 seconds 6.05 seconds
6 99.9999% 31.5 seconds 2.59 seconds 0.6 secondsReal scenario: a three-service chain each at 99.9% delivers about 99.7% to the user (about 26 hours a year); an internal tool is allowed 99% because nobody works at night; a payment API commits to 99.99% in its SLA and needs multi-zone redundancy to meet it; a status page counts a 4-minute outage and burns the whole monthly budget of a 99.99% target.
What provides it:
| Product or practice | How it raises availability | Limit |
|---|---|---|
| Redundant instances behind NGINX, HAProxy, Envoy, AWS ALB | One instance can die | The balancer is a new single point of failure unless it is redundant too |
| Multiple availability zones (AWS, GCP) | Survives a datacentre failure | Cross-zone traffic costs latency and money |
| PostgreSQL streaming replication with failover, Amazon Aurora | A standby takes over | Failover takes seconds to minutes; possible data loss if asynchronous |
| Health checks, auto-restart, Kubernetes self-healing | Dead processes replaced | A crash loop caused by a bad deploy is replicated everywhere |
| Graceful degradation | Core path survives when extras fail | Needs design work per feature |
Fix / how to use it: compute the budget, then design to it (Nines arithmetic). The code that does this arithmetic is Go example 1.
Reliability, fault tolerance, redundancy and single points of failure Must-know
In plain words: reliability is "does the right thing, consistently"; fault tolerance is "keeps doing it when a part breaks"; redundancy is "a spare exists"; a single point of failure (SPOF) is a part with no spare whose failure stops everything.
Common misunderstanding: "Reliable and available are the same." A system can be up and wrong (returns stale or corrupt data) or correct and down (refuses requests to avoid being wrong). Kleppmann's Designing Data-Intensive Applications is built on three concerns, "reliable, scalable and maintainable" (the book site's wording; the chapter text itself was not readable here because the O'Reilly page returned 403, so the fault and failure definitions below are standard terminology, not a quotation). Fault tolerance exists to stop faults becoming failures.
Definition: Fault: a component deviates from its specification. Failure: the system stops delivering its service. Fault tolerance: the ability to continue despite faults. Redundancy: extra components or copies so a fault in one does not remove the capability. Single point of failure: a component whose fault is a failure.
Request path with a hidden SPOF After removing it
1 client -> DNS -> load balancer (1 box) -> 3 app -> DB client -> DNS -> LB pair (active/standby)
2 LB crashes -> 3 app (2 zones) -> DB primary + replica
3 -> every request fails, apps and DB are healthy LB A crashes -> LB B takes the virtual IP
4 recovery: someone pages, someone replaces the box -> requests continue; an alert firesReal scenario: the one cron server that sends invoices; the single NAT gateway all private subnets use; a certificate that expires and takes down TLS everywhere; one Redis instance holding sessions for every user; the DNS provider you did not duplicate.
What provides it:
| Mechanism | Product examples | What it protects against |
|---|---|---|
| Active-active replicas | NGINX/HAProxy pairs, Kubernetes Deployments with N replicas | One process or host failure |
| Active-passive failover | PostgreSQL with Patroni, Redis Sentinel, keepalived VRRP | Primary failure, with a gap while failing over |
| Multi-zone / multi-region | AWS multi-AZ, GCP regional resources, Route 53 or Cloudflare traffic steering | Datacentre and region failure |
| Retries, timeouts, circuit breakers | Go context deadlines, Laravel HTTP client timeout() | Transient network faults, slow dependencies |
| Graceful degradation | Serve cached or partial data | A non-essential dependency down |
Fix / how to use it: walk the request path and ask for every box "what if this dies right now?". The chapters Cascading Failures, Timeouts, Retries & Jitter, Circuit Breaker and Bulkheads & Graceful Degradation own the fixes.
Latency, throughput and back-of-the-envelope arithmetic Must-know
In plain words: latency is how long one request takes; throughput is how many requests (or bytes) per second the system handles. A road can be short (low latency) and narrow (low throughput).
Common misunderstanding: "Faster average means faster system." Users feel the slow tail: if a page makes 100 backend calls and 1% of calls are slow, most page loads contain a slow call. Dean and Barroso: "Temporary high latency episodes which are unimportant in moderate size systems may come to dominate overall service performance at large scale." Averages hide this; percentiles (p50, p95, p99) show it.
Definition: Latency: time from sending a request to receiving the response (distinguish service time from time queued). Throughput: completed work per unit time. Little's law: average in flight = arrival rate x average time in system. Back-of-the-envelope estimation: rough arithmetic to find the order of magnitude of rate, storage and bandwidth before choosing a design.
Napkin math for the URL shortener (all inputs are assumptions)
1 100 million new links per month -> 100e6 / 2.592e6 s = about 39 writes/s
2 100 redirects per created link -> about 3,860 reads/s on average
3 peak is 5x the average -> about 19,300 reads/s
4 20 ms server time per redirect -> 19,300 x 0.020 = about 386 requests in flight
5 500 bytes per link, 5 years -> 6e9 links x 500 B = 3 TB
6 62^6 = 5.7e10 codes -> 6 base62 characters are enough for 6e9 linksReal scenario: deciding whether one database can take the writes (39/s: yes, trivially); whether reads need a cache (19k/s at peak: a cache removes most database load); how many application servers (386 in flight at 20 ms is a few servers if each handles dozens concurrently); whether 3 TB fits one disk (it does, but backups and failover argue for planning shards).
What provides it:
| Tool | Gives you | Notes |
|---|---|---|
| Latency numbers (Norvig, Dean) | Orders of magnitude: memory 100 ns, SSD read 150 us, datacentre round trip 500 us, disk seek 10 ms, CA to Netherlands and back 150 ms | The gist's own caveat: values are approximate, hardware changes them |
| Prometheus histograms, OpenTelemetry | Real percentiles in production | Averages of percentiles are wrong; aggregate histograms |
| Load tools (k6, wrk, vegeta) | Measured throughput vs latency curve | Test the realistic mix, not just GET |
| Capacity Estimation | The method | Write assumptions down |
Fix / how to use it: always estimate first, then check against measurements. Go example 2 is the napkin math as a tested function.
Consistency, CAP and partition tolerance Must-know
In plain words: consistency asks "after I write, does everyone who reads see my write?". When data lives on several machines and the network between them breaks, you must pick: refuse some requests (stay consistent) or answer with possibly old data (stay available).
Common misunderstanding: "CAP means you pick any two of consistency, availability and partition tolerance." Partitions are not optional in a distributed system; they happen. The real choice is only what to do during a partition. In normal operation a system can have both, and then the trade-off is latency against consistency (the PACELC refinement, covered in CAP, PACELC).
Definition: Consistency in CAP is linearizability: every read returns the latest acknowledged write. Availability in CAP: every request to a non-failed node gets a non-error response. Partition tolerance: the system keeps working despite lost messages between nodes. Eventual consistency: if no new writes arrive, all replicas converge. Dynamo's choice, in its own words: "Dynamo targets the design space of an 'always writeable' data store", for example "the shopping cart service must allow customers to add and remove items from their shopping cart even amidst network and server failures", and "Dynamo is designed to be an eventually consistent data store; that is all updates reach all replicas eventually."
Client A Replica 1 (leader) Replica 2 (follower) Client B
1 write x=2 -> x=2 acknowledged
2 --- network partition between replicas ---
3 still x=1
4 <- read x
5 CP choice: Replica 2 refuses (error 503) AP choice: Replica 2 answers x=1 (stale)
6 partition heals: Replica 2 catches up x=2 everywhere (eventual)Real scenario: a bank balance read must be current (consistency over availability); a social feed may lag by seconds (availability over consistency); a shopping cart must always accept adds (Dynamo); a ticket seat must be sold once (strong consistency, a single writer or consensus).
What provides it:
| Product | Default stance | Knob |
|---|---|---|
| PostgreSQL with one primary | Consistent for writes; replicas lag asynchronously | synchronous_commit, synchronous standbys |
| Amazon DynamoDB | Eventually consistent reads by default | ConsistentRead per read |
| Apache Cassandra | Tunable, usually AP | Consistency level per query (ONE, QUORUM, ALL) |
| Google Spanner | External consistency, pays latency | Read staleness options |
| Redis (single instance) | Consistent; replicas asynchronous | WAIT command, Cluster failover can lose writes |
Fix / how to use it: decide per feature, not per system: money and inventory consistent, feeds and counters eventual. The chapters CAP, PACELC, Consistency Models and ACID vs BASE own the detail.
Durability Important
In plain words: once the system says "saved", the data stays saved, even if a machine dies the next second.
Common misunderstanding: "Durable means highly available" or "a replica is a backup". A replica copies mistakes instantly: a bad DELETE is replicated too. Durability against hardware failure and protection against operator error are different problems.
Definition: Durability: committed data survives crashes and failures within the stated failure model. It is provided by writing to stable storage (fsync of a write-ahead log), by copies on several machines or zones, and by backups with point-in-time recovery. Related targets: RPO (recovery point objective: how much data you can afford to lose, as time) and RTO (recovery time objective: how long you can be down).
Step Event State on disk / network
1 COMMIT arrives at PostgreSQL WAL record written
2 fsync of the WAL completes -> acknowledged to the client
3 standby receives and flushes WAL (synchronous standby only: now on 2 machines)
4 primary disk is destroyed standby promoted; no acknowledged write lost
5 asynchronous standby instead writes in the last lag window may be lost (RPO > 0)Real scenario: an order accepted and then lost after a crash; a deleted production table needing point-in-time recovery; Amazon S3's design target of very high object durability; a cache that is purposely non-durable and rebuilt from the database.
What provides it:
| Product | Durability mechanism | Where it is weak |
|---|---|---|
| PostgreSQL, MySQL/InnoDB | Write-ahead log with fsync, backups, PITR | Weak if fsync or synchronous_commit is relaxed for speed |
| Redis | RDB snapshots and AOF with appendfsync policy | Default policies can lose up to about a second or more |
| Kafka | Replicated log; acks=all, min.insync.replicas | acks=1 can lose acknowledged data on leader failure |
| Object storage (Amazon S3, GCS) | Many copies across zones | Does not protect from your own DELETE without versioning |
Fix / how to use it: state RPO and RTO as requirements; match each store to them; test the restore, not just the backup. See Capacity Planning & Disaster Recovery and Durability, WAL & Crash Recovery.
Scalability, elasticity, horizontal and vertical scaling, stateless and stateful Must-know
In plain words: scalability is "twice the load can be handled with about twice the resources"; elasticity is "resources follow the load automatically, up and down". Vertical scaling makes one machine bigger; horizontal scaling adds machines. A stateless server remembers nothing between requests; a stateful one does.
Common misunderstanding: "Add servers and it scales." Adding application servers only helps if the work can be split. If every request needs the same database row, or the servers keep session data in local memory, more servers add cost, not capacity. The database is usually the real limit.
Definition: Scalability: the property that a system's capacity grows with added resources at acceptable cost. Vertical scaling (scale up): a bigger machine; simple, limited by the largest box, a single point of failure. Horizontal scaling (scale out): more machines; needs work to be divisible. Elasticity: automatic, fast scaling in both directions. Stateless: any instance can serve any request because state lives elsewhere (database, cache, client token). Stateful: the instance holds data that others do not have.
Load Design change What gets harder
1 1x One app server + one PostgreSQL Nothing yet
2 10x Several stateless app servers + load balancer; cache Session storage, cache invalidation
3 100x Read replicas, queue for async work, CDN Replica lag, duplicates
4 1000x Sharded storage, regional deployments Cross-shard queries, global consistencyReal scenario: a launch-day spike handled by autoscaling from 4 to 40 pods and back; a Laravel session driver changed from file to redis so any server can serve any user; a single hot key (one viral link) that no number of servers helps; a nightly report that is vertical-only because one machine is simpler.
What provides it:
| Product | Scaling lever | Note |
|---|---|---|
| Kubernetes Horizontal Pod Autoscaler | Pods follow CPU or custom metrics | Needs stateless pods |
| AWS Auto Scaling Groups, GCP managed instance groups | VM count follows policy | Warm-up time matters |
| AWS Lambda, Google Cloud Run, Cloudflare Workers | Per-request scaling | Cold starts, concurrency limits |
| Laravel Octane | Keeps the app booted in memory (FrankenPHP, Swoole, Open Swoole, RoadRunner) for more requests per server | State leaks between requests are now your problem |
| Go | Goroutines per request in net/http | Shared memory still needs locks or external state |
Fix / how to use it: make the app tier stateless first (sessions and uploads in shared stores), then find the real bottleneck by measuring. Scaling Strategies is the deep chapter.
The standard building blocks Must-know
In plain words: most systems are assembled from the same few parts: a load balancer in front, stateless app servers, a cache next to the database, a CDN for static files, a message queue for slow jobs, a database as the source of truth, replicas for reads and failover, and shards when one database is too small.
Common misunderstanding: "Add a cache and the database problem is solved." A cache removes repeated reads only; it adds invalidation bugs, cold-start traffic spikes and a second thing to keep up. It is a trade, not a cure.
Definition: Load balancer: spreads requests over servers and removes dead ones (L4 by connection, L7 by HTTP). Cache: a fast, smaller copy of data keyed for reuse. CDN: a global cache for content near the user. Message queue: a durable buffer between producer and consumer. Database: durable, queryable state. Replication: copies of data on more than one node. Sharding: splitting data across nodes by a key.
Read of one short link at peak
1 client -> CDN hit for popular static pages; miss for dynamic redirect
2 CDN -> load balancer health check removes dead app servers
3 LB -> app server (stateless) parse code, look up
4 app -> cache (Redis) hit: return in under 1 ms of server time
5 miss: app -> database replica read, then fill the cache
6 app -> queue (click event) async; failure does not fail the redirect
7 worker -> counter store increments off the critical pathReal scenario: the shortener's read path above; a product catalogue behind Redis; profile images on a CDN such as Cloudflare or Amazon CloudFront; email sending behind a Laravel queue on Redis or SQS; a user table sharded by user_id after one PostgreSQL primary could not hold the writes.
What provides it:
| Block | Open source / software | Managed |
|---|---|---|
| Load balancer | NGINX, HAProxy, Envoy | AWS ALB/NLB, Google Cloud Load Balancing |
| Cache | Redis, Memcached | Amazon ElastiCache, Google Memorystore |
| CDN | Varnish (self-hosted edge cache) | Cloudflare, Amazon CloudFront, Fastly |
| Message queue / log | RabbitMQ, Apache Kafka | Amazon SQS, Amazon MSK, Google Pub/Sub |
| Database | PostgreSQL, MySQL, Cassandra | Amazon RDS, Aurora, DynamoDB, Spanner |
| Object storage | MinIO, Ceph | Amazon S3, Google Cloud Storage |
Fix / how to use it: add a block only when a number or a failure mode demands it, and write down what it costs. Chapters: Load Balancing, Caching, CDNs, Messaging Fundamentals, Replication Topologies, Sharding at System Level.
Service levels: SLI, SLO and SLA Important
In plain words: an SLI is the number you measure (percent of requests under 100 ms), an SLO is the target for it (99% of them), and an SLA is the contract with consequences if you miss (credits, penalties).
Common misunderstanding: "SLO and SLA are the same thing." The Google SRE book: "SLAs are service level agreements: an explicit or implicit contract with your users that includes consequences of meeting (or missing) the SLOs they contain." The SLO is an internal target, normally stricter than the SLA, so you notice and fix problems before the contract is breached.
Definition: SLI (indicator): a carefully defined measurement, such as the proportion of valid requests served successfully. SLO (objective): a target value or range for an SLI over a window. SLA (agreement): a business contract that references SLOs and states consequences. Error budget: 100% minus the SLO; the amount of unreliability you may spend on releases and experiments.
Window: 30 days, SLO 99.9% of redirects succeed
1 Total redirects 2,592,000,000
2 Error budget (0.1%) 2,592,000 failed requests allowed
3 Day 9: bad deploy fails 1,800,000 requests
4 Budget remaining 792,000 -> release freeze until the budget recovers
5 SLA promised to customers 99.5% (looser: gives engineering a buffer)Real scenario: a cloud provider credits 10% of the bill below 99.9%; a team freezes launches when the budget is nearly spent; a dashboard shows p99 latency against a 300 ms objective.
What provides it:
| Tool | Role |
|---|---|
| Prometheus with recording rules; Grafana | Compute and show SLIs |
| OpenTelemetry | Emit the measurements consistently |
| Sloth, Pyrra (SLO generators) | Turn an SLO into burn-rate alerts |
| Cloud provider SLAs (AWS, GCP) | Contractual numbers per service; read the exclusions |
Fix / how to use it: pick two or three SLIs per user journey (availability, latency, correctness). SLA, SLO, SLI & Error Budgets owns the method; Alerting That Actually Works uses it.
Cost Important
In plain words: every requirement has a price, and the price often decides the design.
Common misunderstanding: "Cost is finance's problem, not design's." A design with three regions, five stores and a streaming platform may meet every technical requirement and still bankrupt the product. In the cloud, architecture is a purchasing decision made on every request.
Definition: Cost in system design: money per unit of work (per request, per user, per GB stored) plus the human cost of building and operating. Main drivers: compute hours, storage, cross-zone and egress traffic, managed-service premiums, on-call load.
Option Meets 99.9%? Rough cost shape
1 One VM + one database No (single point of failure) lowest
2 Two app VMs + managed DB with standby Yes about 2x
3 Two regions, active-active, global DB Yes, and region loss 5x to 10x and operational complexity
4 Serverless functions + managed storage Yes pay per request; cheap when idle, costly at steady high loadReal scenario: cross-zone data transfer fees that surprise a team after enabling multi-AZ; a cache that costs less than the database reads it saves; a managed Kafka cluster idling at night; a serverless workload that is cheap at 1 million requests and not at 10 billion.
What provides it:
| Practice | Product | Note |
|---|---|---|
| Estimate unit cost early | Cloud pricing calculators (AWS, GCP) | Prices change; cite the date |
| Right-size and autoscale | Kubernetes HPA, AWS Auto Scaling | Costs follow load |
| Reserve or commit for steady load | Savings plans, committed use | Trade flexibility for price |
| Reduce egress | CDN, compression, regional placement | Egress is a major line item |
Fix / how to use it: put "cost per million requests" next to latency and availability in the requirements table. Capacity Planning & Disaster Recovery revisits it.
Trade-offs Must-know
In plain words: you cannot have everything. Gaining one property costs another, and the skill is choosing the right loss.
Common misunderstanding: "A trade-off means a compromise nobody likes." A trade-off recorded in writing is a decision: you know what you gave up and why, and you can revisit it when the requirement changes.
Definition: a trade-off is a design choice where improving one quality attribute degrades another. The recurring ones are listed below; the same few pairs appear in every chapter of this path.
Gain Pay with
1 Availability Consistency (CAP during a partition), cost (redundancy)
2 Low latency Consistency (read replicas, caches), cost (more regions)
3 Consistency Latency (coordination), availability (during partitions)
4 Throughput Latency (batching), complexity (async, sharding)
5 Simplicity Scale ceiling
6 Durability Write latency (fsync, synchronous replication), cost (copies)
7 Flexibility (microservices) Operational complexity, network failure modesReal scenario: Dynamo accepts stale cart reads to always accept writes; Spanner accepts commit-wait latency to give external consistency; a team chooses a cache with a 60-second TTL knowing users may see old prices for a minute; a startup stays on a monolith and accepts that scaling one component means scaling all.
What provides it:
| Practice | Artefact |
|---|---|
| Record the decision | An architecture decision record: context, decision, consequences (ADR and trade-offs) |
| Compare options on the same axes | A decision table with the requirement numbers |
| Revisit on a trigger | "If reads exceed 10,000/s, add a cache" |
Fix / how to use it: every design ends with a trade-off table: option, gains, costs, trigger to reconsider.
Mechanics
Nines arithmetic
For a period P and availability A, the allowed downtime is (1 - A) x P. The number of nines is -log10(1 - A): 99.9% is 3, 99.95% is about 3.3. The Google SRE book's own example: a target of 99.99% allows "up to 52.56 minutes in a year".
| Composition | Formula | Example | Result |
|---|---|---|---|
| Serial (all must work) | A1 x A2 x ... x An | 3 x 99.9% | 99.7003% |
| Parallel (any one works) | 1 - (1 - A1)(1 - A2)... | 2 x 99.9% | 99.9999% |
| Serial then parallel | multiply the group results | LB 99.99% x (2 app x 99.9%) x DB 99.95% | about 99.94% |
| Retries (k independent attempts) | 1 - (1 - A)^k | 3 tries at 99% | 99.9999% |
The top row is the serial chain, the bottom row the redundant pair; the footnote is the caveat that matters.
Parallel math assumes independent failures. A shared deploy, a shared database, the same zone or the same bug couples the copies, and the real figure is lower. Redundancy cannot rescue a defect that is shipped to every copy at once.
Little's law and concurrency
L = lambda x W: average requests in the system equals arrival rate times average time spent in the system. At 19,300 requests/s and 20 ms, about 386 requests are in flight. If latency doubles to 40 ms with the same arrival rate, in-flight work doubles; a server with a fixed number of workers will queue, and queueing makes latency worse, which is how a slow dependency becomes an outage (Cascading Failures).
Numbers every designer carries
From the widely circulated latency table credited to Jeff Dean and Peter Norvig (the saved gist lists these values; hardware has moved them, so treat them as orders of magnitude):
| Operation | Time | Relative idea |
|---|---|---|
| Main memory reference | 100 ns | 200x an L1 hit (0.5 ns) |
| Send 1 KB over a 1 Gbps network | 10 us | |
| Read 4 KB randomly from SSD | 150 us | |
| Read 1 MB sequentially from memory | 250 us | |
| Round trip within the same datacentre | 500 us | 20x less than a disk seek |
| Read 1 MB sequentially from SSD | 1 ms | 4x memory |
| Disk seek | 10 ms | |
| Read 1 MB sequentially from disk | 20 ms | |
| Packet California to Netherlands and back | 150 ms | the speed of light is a floor |
Two derived habits: avoid a network round trip on the hot path when memory will do, and treat any cross-region call as roughly a hundred datacentre round trips.
Status codes and messages you will actually see
| Where | Signal | Meaning for design |
|---|---|---|
| HTTP 301 | Moved Permanently | "any future references to this resource ought to use one of the enclosed URIs" (RFC 9110, 15.4.2); clients may cache it indefinitely |
| HTTP 302 | Found | "the target resource resides temporarily under a different URI" (RFC 9110, 15.4.3); the shortener's choice |
| HTTP 404 | Not Found | Unknown code; do not cache forever or a later valid code is hidden |
| HTTP 502 | Bad Gateway | The proxy "received an invalid response from an inbound server" |
| HTTP 503 | Service Unavailable | "temporary overload or scheduled maintenance"; may carry Retry-After; the correct overload signal |
| HTTP 504 | Gateway Timeout | The proxy "did not receive a timely response from an upstream server" |
Go context deadline exceeded | context.DeadlineExceeded | A deadline passed; the work may still have completed elsewhere |
Go http.Client{Timeout: 0} | "A Timeout of zero means no timeout" | A client with no timeout can hang forever |
Go
Example 1: nines, serial and parallel availability
The first package turns an availability target into a downtime budget and composes availability for chains and replicas. The tests encode the SRE-book figure (52.56 minutes) and the 99.7% / 99.9999% examples above.
// Package nines turns availability targets into numbers a team can plan with.
package nines
import (
"math"
"time"
)
// DowntimeBudget is how long a service may be down in period and still meet
// the availability target (0.9999 means "four nines").
func DowntimeBudget(availability float64, period time.Duration) time.Duration {
return time.Duration((1 - availability) * float64(period))
}
// Nines is the number of leading nines: 0.999 -> 3, 0.9995 -> 3.3.
func Nines(availability float64) float64 {
if availability >= 1 {
return math.Inf(1)
}
return -math.Log10(1 - availability)
}
// Serial is the availability of a chain where every component must work.
// It assumes failures are independent, which is optimistic.
func Serial(components ...float64) float64 {
a := 1.0
for _, c := range components {
a *= c
}
return a
}
// Parallel is the availability of redundant copies where one working copy is
// enough. It assumes independent failures: a shared deploy, rack or bug breaks
// that assumption, and the real number is lower.
func Parallel(copies ...float64) float64 {
allDown := 1.0
for _, c := range copies {
allDown *= 1 - c
}
return 1 - allDown
}package nines
import (
"math"
"testing"
"time"
)
const year = 365 * 24 * time.Hour
func TestDowntimeBudgetMatchesSRETable(t *testing.T) {
// Google SRE book: 99.99% allows about 52.56 minutes of downtime a year.
got := DowntimeBudget(0.9999, year)
want := 52*time.Minute + 33600*time.Millisecond
if d := got - want; d > time.Second || d < -time.Second {
t.Fatalf("got %v, want about %v", got, want)
}
}
func TestSerialThreeDependencies(t *testing.T) {
got := Serial(0.999, 0.999, 0.999)
if math.Abs(got-0.997003) > 1e-9 {
t.Fatalf("got %.9f", got)
}
}
func TestParallelTwoReplicas(t *testing.T) {
got := Parallel(0.999, 0.999)
if math.Abs(got-0.999999) > 1e-9 {
t.Fatalf("got %.9f", got)
}
}
func TestNines(t *testing.T) {
if got := Nines(0.999); math.Abs(got-3) > 1e-9 {
t.Fatalf("got %v", got)
}
}Example 2: back-of-the-envelope as a tested function
The napkin math from Latency, throughput as code, so the assumptions are written down and a change to one input updates every derived number.
// Package estimate is a back-of-the-envelope calculator for the URL shortener
// sketch. Every input is an assumption, not a measurement.
package estimate
import (
"math"
"time"
)
// Inputs are the assumptions written down before any design starts.
type Inputs struct {
NewLinksPerMonth float64 // writes
ReadWriteRatio float64 // redirects per created link
PeakFactor float64 // peak rate divided by average rate
BytesPerLink float64 // code + URL + metadata
RetentionYears float64 // how long links live
Latency time.Duration // server time per redirect
}
// Result is what the design is sized against.
type Result struct {
WritesPerSecond float64
ReadsPerSecond float64
PeakReads float64
TotalLinks float64
StorageBytes float64
CodeLength int // base62 characters needed
InFlightAtPeak float64 // Little's law: rate x latency
}
const secondsPerMonth = 30 * 24 * 3600
// Compute applies the arithmetic. Little's law (in-flight = rate x time in
// system) gives the concurrency the servers must hold at peak.
func Compute(in Inputs) Result {
writes := in.NewLinksPerMonth / secondsPerMonth
reads := writes * in.ReadWriteRatio
peak := reads * in.PeakFactor
total := in.NewLinksPerMonth * 12 * in.RetentionYears
return Result{
WritesPerSecond: writes,
ReadsPerSecond: reads,
PeakReads: peak,
TotalLinks: total,
StorageBytes: total * in.BytesPerLink,
CodeLength: int(math.Ceil(math.Log(total) / math.Log(62))),
InFlightAtPeak: peak * in.Latency.Seconds(),
}
}package estimate
import (
"math"
"testing"
"time"
)
func TestShortenerSketch(t *testing.T) {
r := Compute(Inputs{
NewLinksPerMonth: 100e6,
ReadWriteRatio: 100,
PeakFactor: 5,
BytesPerLink: 500,
RetentionYears: 5,
Latency: 20 * time.Millisecond,
})
check := func(name string, got, want, tol float64) {
t.Helper()
if math.Abs(got-want) > tol {
t.Errorf("%s: got %.2f, want %.2f", name, got, want)
}
}
check("writes/s", r.WritesPerSecond, 38.6, 0.1)
check("reads/s", r.ReadsPerSecond, 3858, 1)
check("peak reads/s", r.PeakReads, 19290, 1)
check("total links", r.TotalLinks, 6e9, 1)
check("storage TB", r.StorageBytes/1e12, 3, 0.001)
check("in flight", r.InFlightAtPeak, 385.8, 0.1)
if r.CodeLength != 6 {
t.Errorf("code length: got %d, want 6", r.CodeLength)
}
}Example 3: the URL shortener, first sketch
One process, an in-memory store, base62 codes from a counter, a cache-aside read path, and POST /links plus GET /{code}. It is the smallest thing that satisfies the functional requirements and shows where each non-functional requirement will push.
// Package shortener is the first sketch of a URL shortener: one process, an
// in-memory store, a cache-aside read path and two HTTP endpoints.
package shortener
import (
"context"
"errors"
"net/url"
"strings"
"sync"
"sync/atomic"
)
const alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
// Encode writes n in base62. IDs from a counter are unique, so codes never collide.
func Encode(n uint64) string {
if n == 0 {
return string(alphabet[0])
}
var b []byte
for ; n > 0; n /= 62 {
b = append(b, alphabet[n%62])
}
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
return string(b)
}
// Decode is the inverse of Encode.
func Decode(s string) (uint64, error) {
var n uint64
for _, r := range s {
i := strings.IndexRune(alphabet, r)
if i < 0 {
return 0, errors.New("shortener: invalid character in code")
}
n = n*62 + uint64(i)
}
return n, nil
}
// ErrNotFound means the code was never issued.
var ErrNotFound = errors.New("shortener: code not found")
// Store is the durable part. In production this is a database table.
type Store interface {
Save(ctx context.Context, code, target string) error
Load(ctx context.Context, code string) (string, error)
}
// MemoryStore is a Store for tests and for the first sketch.
type MemoryStore struct {
mu sync.RWMutex
links map[string]string
}
func NewMemoryStore() *MemoryStore { return &MemoryStore{links: map[string]string{}} }
func (m *MemoryStore) Save(_ context.Context, code, target string) error {
m.mu.Lock()
defer m.mu.Unlock()
m.links[code] = target
return nil
}
func (m *MemoryStore) Load(_ context.Context, code string) (string, error) {
m.mu.RLock()
defer m.mu.RUnlock()
target, ok := m.links[code]
if !ok {
return "", ErrNotFound
}
return target, nil
}
// Service issues codes and resolves them. The cache sits in front of the store
// (cache-aside): read the cache, on a miss read the store and fill the cache.
type Service struct {
store Store
next atomic.Uint64 // stand-in for a database sequence or an ID service
mu sync.RWMutex
cache map[string]string
}
func NewService(store Store) *Service {
return &Service{store: store, cache: map[string]string{}}
}
// ValidateTarget accepts absolute http and https URLs of reasonable length.
func ValidateTarget(raw string) error {
if len(raw) == 0 || len(raw) > 2048 {
return errors.New("shortener: url must be 1 to 2048 bytes")
}
u, err := url.Parse(raw)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
return errors.New("shortener: url must be absolute http or https")
}
return nil
}
// Shorten stores target under a fresh code.
func (s *Service) Shorten(ctx context.Context, target string) (string, error) {
if err := ValidateTarget(target); err != nil {
return "", err
}
code := Encode(s.next.Add(1))
if err := s.store.Save(ctx, code, target); err != nil {
return "", err
}
return code, nil
}
// Resolve returns the target for code, using the cache first.
func (s *Service) Resolve(ctx context.Context, code string) (string, error) {
s.mu.RLock()
target, hit := s.cache[code]
s.mu.RUnlock()
if hit {
return target, nil
}
target, err := s.store.Load(ctx, code)
if err != nil {
return "", err
}
s.mu.Lock()
s.cache[code] = target
s.mu.Unlock()
return target, nil
}package shortener
import (
"encoding/json"
"errors"
"net/http"
)
// Handler wires the two endpoints of the sketch:
//
// POST /links {"url": "https://example.com/a/very/long/path"} -> 201 {"code": "1"}
// GET /{code} -> 302 Location: target
func Handler(s *Service) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("POST /links", func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 4096)
var in struct {
URL string `json:"url"`
}
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
http.Error(w, "invalid JSON body", http.StatusBadRequest)
return
}
code, err := s.Shorten(r.Context(), in.URL)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(map[string]string{"code": code})
})
mux.HandleFunc("GET /{code}", func(w http.ResponseWriter, r *http.Request) {
target, err := s.Resolve(r.Context(), r.PathValue("code"))
switch {
case errors.Is(err, ErrNotFound):
http.NotFound(w, r)
case err != nil:
http.Error(w, "temporarily unavailable", http.StatusServiceUnavailable)
default:
// 302, not 301: browsers cache a 301 for good, and the service would
// lose the ability to count, expire or change the link.
http.Redirect(w, r, target, http.StatusFound)
}
})
return mux
}package shortener
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
)
type countingStore struct {
Store
loads atomic.Int64
}
func (c *countingStore) Load(ctx context.Context, code string) (string, error) {
c.loads.Add(1)
return c.Store.Load(ctx, code)
}
func TestBase62RoundTrip(t *testing.T) {
for _, n := range []uint64{0, 1, 61, 62, 3844, 6_000_000_000} {
got, err := Decode(Encode(n))
if err != nil || got != n {
t.Fatalf("n=%d: got %d err=%v", n, got, err)
}
}
if got := Encode(6_000_000_000); len(got) > 6 {
t.Fatalf("6 billion links need at most 6 characters, got %q", got)
}
}
func TestCreateThenRedirect(t *testing.T) {
srv := Handler(NewService(NewMemoryStore()))
create := httptest.NewRecorder()
srv.ServeHTTP(create, httptest.NewRequest("POST", "/links", strings.NewReader(`{"url":"https://example.com/docs/a/very/long/path"}`)))
if create.Code != http.StatusCreated {
t.Fatalf("create: %d %s", create.Code, create.Body)
}
if !strings.Contains(create.Body.String(), `"code":"1"`) {
t.Fatalf("unexpected body %s", create.Body)
}
get := httptest.NewRecorder()
srv.ServeHTTP(get, httptest.NewRequest("GET", "/1", nil))
if get.Code != http.StatusFound || get.Header().Get("Location") != "https://example.com/docs/a/very/long/path" {
t.Fatalf("redirect: %d %q", get.Code, get.Header().Get("Location"))
}
}
func TestRejectsBadInput(t *testing.T) {
srv := Handler(NewService(NewMemoryStore()))
for _, body := range []string{`{"url":"javascript:alert(1)"}`, `{"url":"/relative"}`, `not json`, `{"url":""}`} {
rec := httptest.NewRecorder()
srv.ServeHTTP(rec, httptest.NewRequest("POST", "/links", strings.NewReader(body)))
if rec.Code != http.StatusBadRequest {
t.Errorf("%s: got %d, want 400", body, rec.Code)
}
}
}
func TestUnknownCodeIs404(t *testing.T) {
srv := Handler(NewService(NewMemoryStore()))
rec := httptest.NewRecorder()
srv.ServeHTTP(rec, httptest.NewRequest("GET", "/zzz", nil))
if rec.Code != http.StatusNotFound {
t.Fatalf("got %d", rec.Code)
}
}
func TestCacheAsideReadsStoreOnce(t *testing.T) {
store := &countingStore{Store: NewMemoryStore()}
svc := NewService(store)
code, err := svc.Shorten(context.Background(), "https://example.com/x")
if err != nil {
t.Fatal(err)
}
for i := 0; i < 100; i++ {
if _, err := svc.Resolve(context.Background(), code); err != nil {
t.Fatal(err)
}
}
if got := store.loads.Load(); got != 1 {
t.Fatalf("store read %d times, want 1", got)
}
}// Command shortener runs the first sketch on localhost.
package main
import (
"log"
"net/http"
"time"
"academy/what-is-system-design/shortener"
)
func main() {
svc := shortener.NewService(shortener.NewMemoryStore())
srv := &http.Server{
Addr: "127.0.0.1:8080",
Handler: shortener.Handler(svc),
ReadHeaderTimeout: 2 * time.Second, // never leave a server with no read deadline
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
}
log.Println("listening on", srv.Addr)
log.Fatal(srv.ListenAndServe())
}The Go angle
- Go's
net/httpserves each request in its own goroutine, so a plainhttp.ListenAndServealready handles thousands of concurrent connections; the limits you hit first are in your own code (shared maps need a lock, asService.cacheshows) and in dependencies. - The server mux supports method and wildcard patterns (
"GET /{code}",r.PathValue("code")) since Go 1.22, which is why the sketch needs no router library. - Always set deadlines. The standard library's
http.Clientdocuments "A Timeout of zero means no timeout", andcontext.DeadlineExceededis what a passed deadline looks like to callers. The chapter Timeouts, Retries & Jitter builds on this. httptest.NewRecordermakes handler tests fast and dependency-free, which is how the sketch's tests run without a socket.- A stateless Go binary is trivially horizontally scalable; the in-memory
cacheand counter in the sketch are exactly the state that would have to move to Redis and a database sequence first.
Laravel
Example: the same shortener in Laravel 13
A migration, an Eloquent model, a controller with Cache::remember as the cache-aside read path, a queued job that counts clicks off the critical path, and routes with a constrained catch-all.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('short_links', function (Blueprint $table) {
$table->id(); // the sequence the code is derived from
$table->string('target', 2048);
$table->unsignedBigInteger('clicks')->default(0);
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('short_links');
}
};<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ShortLink extends Model
{
protected $fillable = ['target'];
}<?php
namespace App\Support;
use InvalidArgumentException;
final class Base62
{
private const ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
/** Encode a non-negative integer. IDs from a database sequence are unique, so codes never collide. */
public static function encode(int $n): string
{
if ($n < 0) {
throw new InvalidArgumentException('n must not be negative');
}
if ($n === 0) {
return self::ALPHABET[0];
}
$out = '';
while ($n > 0) {
$out = self::ALPHABET[$n % 62] . $out;
$n = intdiv($n, 62);
}
return $out;
}
public static function decode(string $code): int
{
$n = 0;
foreach (str_split($code) as $char) {
$i = strpos(self::ALPHABET, $char);
if ($i === false) {
throw new InvalidArgumentException('invalid character in code');
}
$n = $n * 62 + $i;
}
return $n;
}
}<?php
namespace App\Http\Controllers;
use App\Jobs\RecordClick;
use App\Models\ShortLink;
use App\Support\Base62;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
class ShortLinkController extends Controller
{
// POST /links {"url": "https://example.com/a/very/long/path"} -> 201 {"code": "1"}
public function store(Request $request): JsonResponse
{
$data = $request->validate([
'url' => ['required', 'url:http,https', 'max:2048'],
]);
$link = ShortLink::create(['target' => $data['url']]);
return response()->json(['code' => Base62::encode($link->id)], 201);
}
// GET /{code} -> 302 Location: target
public function show(string $code): RedirectResponse
{
$id = Base62::decode($code);
// Cache-aside: the first read fills the cache, later reads skip the database.
$target = Cache::remember("link:{$id}", 3600, fn () => ShortLink::find($id)?->target);
abort_if($target === null, 404);
RecordClick::dispatch($id);
// 302, not 301: a browser keeps a 301 forever, so the service loses control of the link.
return redirect()->away($target, 302);
}
}<?php
namespace App\Jobs;
use App\Models\ShortLink;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Foundation\Queue\Queueable;
// Counting clicks is not on the redirect's critical path: the queue absorbs
// the write, and a slow or failed counter never slows or breaks a redirect.
class RecordClick implements ShouldQueue
{
use Dispatchable, Queueable;
public function __construct(public int $linkId)
{
}
public function handle(): void
{
ShortLink::whereKey($this->linkId)->increment('clicks');
}
}<?php
use App\Http\Controllers\ShortLinkController;
use Illuminate\Support\Facades\Route;
Route::post('/links', [ShortLinkController::class, 'store']);
// The constraint keeps this catch-all from swallowing other routes.
Route::get('/{code}', [ShortLinkController::class, 'show'])->where('code', '[0-9A-Za-z]{1,10}');The Laravel angle
- Cache. The Laravel 13 cache documentation describes
Cache::rememberfor the "retrieve, and if absent compute and store" pattern, which is cache-aside in one call. The store behind it (file,database,redis,memcached) is a configuration choice, so the same code runs on one server or on a shared Redis. - Queues. Laravel's queue documentation lists the drivers "included with the framework, including the database, Amazon SQS, Redis, and Beanstalkd drivers". A job implementing
ShouldQueueis the message-queue building block with almost no code, and it moves slow work off the request. - Octane. "Laravel Octane supercharges your application's performance by serving your application using high-powered application servers, including FrankenPHP, Open Swoole, Swoole, and RoadRunner. Octane boots your application once, keeps it in memory, and then feeds it requests at supersonic speeds." That raises throughput per server; it also makes statelessness a rule, because anything stored in a static property or singleton now survives between requests.
- Statelessness. Move sessions and cache to Redis or the database (
SESSION_DRIVER,CACHE_STORE) and uploads to object storage, so any app server can serve any request and the load balancer needs no stickiness. - Where it stops. The 302 redirect, the
url:http,httpsvalidation rule and the route constraint are small safeguards; real systems add rate limiting (Rate Limiting) and abuse handling.
Solving the classic problems
The URL shortener sketch, end to end
This is the whole method in miniature, in the order the 4-step approach will formalise: scope, estimate, high-level design, decisions.
Step 1: scope. Functional: create a short link for a long URL; follow a short link to its target; (optionally) count clicks. Out of scope for the first pass: custom aliases, accounts, link expiry, abuse detection. Non-functional: redirects are fast and highly available; creation can be slower; links are never lost; 99.9% availability.
Step 2: estimate (assumptions, not facts). From the napkin math: about 39 writes/s, about 3,860 reads/s on average and 19,300 at peak, about 3 TB over five years, 6 base62 characters enough for six billion links, about 386 requests in flight at peak.
Step 3: high-level design.
The read path is the product: load balancer, stateless app servers, a cache for hot codes, the database on a miss. Writes are rare and go straight to the database. Click counting goes through a queue to a worker so a slow counter can never slow or break a redirect.
Step 4: decisions and trade-offs.
| Decision | Choice | Alternative | Trade-off |
|---|---|---|---|
| Code generation | Base62 of a database sequence | Random 6-7 chars | Sequence is collision-free but guessable and a bottleneck at huge write rates; random needs collision handling |
| Redirect status | 302 | 301 | 302 keeps control and counts; 301 saves load but browsers keep it forever (RFC 9110) |
| Storage | PostgreSQL, one table | DynamoDB or Cassandra | 39 writes/s needs no sharding; keep the simple store until numbers say otherwise |
| Cache | Cache-aside, TTL one hour | Write-through | Reads dominate; links rarely change; stale target for up to an hour is acceptable |
| Counting | Queue + worker | Increment in the request | Counts are eventually consistent; redirects never wait on them |
| Availability | Two or more app servers in two zones; DB with standby | Single node | Costs about double; needed for 99.9% |
| Consistency | Read-your-write for creation (read primary right after create) | All reads from replicas | A fresh link must work immediately |
-- PostgreSQL: the whole persistent model of the sketch
CREATE TABLE short_links (
id BIGSERIAL PRIMARY KEY, -- the sequence the code is derived from
target VARCHAR(2048) NOT NULL,
clicks BIGINT NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- the redirect read, served from cache on all but the first request per code
SELECT target FROM short_links WHERE id = $1; -- id decoded from the base62 code
-- the counter worker (batched updates would reduce write load further)
UPDATE short_links SET clicks = clicks + 1 WHERE id = $1;What this sketch deliberately leaves out: hot keys (one viral link hammering one cache shard), key-guessing and enumeration, expiry and deletion, multi-region, abuse and phishing. Each is a later chapter, and each is the right question to ask next.
A single point of failure found by walking the path
Take the request path of any system and, for every box, ask what happens if it vanishes this second. In the first shortener diagram the load balancer, the database and the cache are each one box. Fix in order of damage: the database gets a standby, the load balancer becomes a pair or a managed service (AWS ALB is itself multi-zone), the cache is treated as optional (on failure the app reads the database, with a limit on how hard it may fall back, or it will take the database down).
| Box | If it dies | Fix | Residual risk |
|---|---|---|---|
| Load balancer | Total outage | Managed LB across zones, or an HAProxy/NGINX pair with VRRP | Config pushed to both |
| App server | Capacity drops | N+1 servers, health checks | Bad deploy hits all |
| Cache | Latency up, database load up | Cache is optional; protect the database with limits | Cold-start stampede |
| Database primary | Writes fail | Standby with automatic failover | Replication lag, failover time |
| Queue | Counts delayed | Replicated queue, drop counts if it is gone | Lost counts acceptable |
"Faster" without measuring
A team caches everything and the system gets slower and stale. The fix is the loop the whole path teaches: write the SLI, measure the tail, find the dominant cost with a trace, change one thing, measure again. Observability provides the instruments.
It worked in development
A design that meets its numbers with one user can collapse at scale: unbounded queries, per-request disk writes, sessions in local memory. The fix is estimation plus a load test with realistic data volume and a failure test (kill a server during the test). Chaos Engineering & Game Days makes the failure test routine.
Tour of the path
Every other chapter, in learning-path order, with the one question it answers.
| Chapter | The question it answers |
|---|---|
| The 4-Step Approach | How do I turn this sketch into a repeatable method: scope, estimate, design, decide? |
| Latency Budgets & Tail Latency | How is a latency target split across hops, and why does p99 rule? |
| The Client-Server Model | What exactly happens when one machine asks another for something? |
| IP, DNS, GeoDNS & TTL | How do names become addresses, and how can DNS steer traffic? |
| Forward vs Reverse Proxies | What sits between client and server, and for whom does it act? |
| TCP & UDP | When do I want reliable ordered streams, and when datagrams? |
| HTTP Evolution | What changed from HTTP/1.1 to HTTP/2 and HTTP/3, and why does Keep-Alive matter? |
| Real-Time Communication | How do I push updates: polling, SSE or WebSockets, and how do I scale connections? |
| REST API Design | What makes an HTTP API predictable, idempotent and versionable? |
| GraphQL | When does a query language beat fixed endpoints, and what is the N+1 trap? |
| gRPC & Protocol Buffers | When do I pick typed binary RPC over REST or GraphQL? |
| API Versioning & Evolution | How do I change an API without breaking clients? |
| Web Sessions, Cookies & CORS | How does a stateless server know who you are? |
| Scaling Strategies | When do I scale up, out or diagonally, and how does autoscaling decide? |
| Load Balancing | Which algorithm, layer 4 or 7, health checks and affinity? |
| Rate Limiting | How do token bucket, leaky bucket and windows protect a service? |
| CDNs | What belongs on the edge, push or pull, and how does a cache hierarchy work? |
| Caching | Which cache pattern, how to invalidate, and how to survive a stampede? |
| Object Storage & File Systems | Where do big files live, and how do presigned URLs work? |
| Write Buffering & Sharded Counters | How do I absorb hot writes and counters? |
| CAP, PACELC & Tunable Consistency | What really happens in a partition, and what is the latency trade-off otherwise? |
| Consistency Models | What is the difference between linearizable, serializable, causal and eventual? |
| ACID vs BASE | Which guarantees do I keep, and which do I trade for scale? |
| Replication Topologies | Leader-follower, multi-leader or leaderless quorums, and who resolves conflicts? |
| Sharding at System Level | How do I pick a partition key and handle hot partitions and rebalancing? |
| Choosing a Database | How do I model the queries first and then pick SQL, NoSQL, Redis or DynamoDB? |
| Cascading Failures | How does one slow service take down all the others? |
| Timeouts, Retries & Jitter | How do I retry without making an outage worse? |
| Circuit Breaker | How do I stop calling something that is failing? |
| Bulkheads & Graceful Degradation | How do I contain a failure and keep the core working? |
| Load Shedding | What do I drop first when demand exceeds capacity? |
| API Idempotency | How do keys make a retried request safe? |
| Distributed Locking | When is a lock safe, and what are fencing tokens? |
| Leader Election | How do I make exactly one node active? |
| Gossip Protocols | How do nodes learn about each other and about failures? |
| Vector Clocks & Causality | How do I order events without a shared clock? |
| Merkle Trees & Anti-Entropy | How do replicas find and repair differences cheaply? |
| CRDTs | How can replicas merge concurrent updates without coordination? |
| Geospatial Indexing | How do geohash, quadtree and R-tree answer "what is near me"? |
| Top-K & Heavy Hitters | How do I count the most frequent items in a stream? |
| Strangler Fig Migration | How do I replace a live system step by step? |
| Security Foundations | How do attackers think, and what do CIA and STRIDE tell me? |
| Authentication | How do passwords, MFA, sessions and tokens fit together? |
| JWT Deep Dive | What is in a token, and how is it verified or misused? |
| OAuth 2.0, OIDC & SSO | How does delegated login work? |
| Authorization Models | RBAC, ABAC, ReBAC and zero trust: who may do what? |
| Cryptography in Practice | How do TLS, PKI and secrets management work together? |
| OWASP Top 10 | Which web attacks recur, and what stops them? |
| DDoS & Network Security | How do firewalls, VPCs and segmentation limit the blast radius? |
| Mutual TLS | How do services prove who they are to each other? |
| Secure SDLC & Incident Response | How do I build security in and respond to a breach? |
| Observability | Logs, metrics and traces: what do I see and when? |
| Alerting That Actually Works | Which alerts should wake a human? |
| Chaos Engineering | How do I test failure on purpose? |
| Containers & Kubernetes | How are services packaged, scheduled, scaled and healed? |
| Service Mesh & Sidecar | What does a mesh add to service-to-service traffic? |
| Serverless & Event-Driven Compute | When do functions beat servers? |
| Capacity Planning & Disaster Recovery | How much is enough, and how do I recover from losing a region? |
| Payment Processing | How do idempotency, fraud checks and PCI shape payments? |
| Search Systems | How do scoring, Elasticsearch and typeahead work? |
| ML Systems | How are models deployed, served and fed features? |
| Feeds: Fan-Out | Fan-out on write or on read for a timeline? |
| Case Study: Uber | How do location, matching and pricing fit together? |
| Case Study: Netflix | What does a streaming platform look like end to end? |
| Case Study: Amazon | How does an e-commerce giant divide its services? |
| Case Study: WhatsApp | How is messaging delivered to billions? |
| Case Study: X / Twitter | How is a timeline assembled at scale? |
| Case Study: YouTube | How is video uploaded, transcoded and streamed? |
| Case Study: OpenAI | What does serving large models require? |
| Case Study: LinkedIn | How do feeds, graphs and messaging scale? |
| Case Study: Discord | How do chat and presence work at scale? |
| Case Study: Ticketing | How does the 4-step method run on a full problem? |
Two audiences: interview vs real life
The same method answers two different questions, and mixing them up causes bad designs and bad interviews.
| Aspect | Interview | Real project |
|---|---|---|
| Time | 35 to 45 minutes | Weeks of discussion, then years of operation |
| Requirements | Vague on purpose; you must ask | Exist in tickets, contracts, traffic graphs |
| Numbers | Invented but must be stated | Measured from production |
| Constraints | Few; everything is open | Team, budget, legacy, compliance |
| Goal | Show structured thinking and trade-off vocabulary | A system people can run for years |
| Good answer | Scope, estimate, boxes, deep dive on two areas, failure modes | A smaller design plus a migration plan |
| Common trap | Drawing every fashionable box | Designing for the scale you hope for |
| What ends it | A clock | An incident, an invoice or a new requirement |
The shared skill: state assumptions, justify each choice by a requirement or a number, and name what you gave up. In an interview say it aloud; in a project write it in the ADR.
Choosing
Which first move for which situation
| Situation | First move | Extra technique | Reason |
|---|---|---|---|
| New product, unknown load | One stateless app + one PostgreSQL, one standby | Measure from day one | Cheapest design that can be fixed later |
| Reads dominate, same items repeatedly | Add a cache (Redis) | CDN for static parts | Read amplification is solved by memory |
| Slow work in the request path | Move it to a queue and worker | Idempotent consumers | The user should not wait for email or reports |
| One database cannot hold the writes | Vertical first, then partition or shard | Choose the key from the access pattern | Sharding is irreversible-ish |
| Global users, high latency | CDN and regional read replicas | GeoDNS | Speed of light sets a floor |
| Strict correctness (money, stock) | Single writer, transactions | Idempotency keys, an append-only ledger | One wrong number costs more than latency |
| Always-write requirement (cart, log) | Leaderless or multi-leader store | Conflict resolution | Dynamo-style availability |
| Spiky or tiny workload | Serverless functions | Budget for cold starts | Pay per use |
| Many teams, one codebase hurts | Modular monolith, then services | Strangler fig | Split by business boundary, not by layer |
Which consistency for which data
| Data | Needs | Reason | Example mechanism |
|---|---|---|---|
| Account balance | Strong | Wrong number is worse than a delay | Single primary, serializable or row locks |
| Inventory at checkout | Strong at the final step | Overselling | Conditional update |
| Product page | Eventual | A few seconds old is fine | Cache with TTL |
| Like counter | Eventual | Approximate is fine | Sharded counters, async |
| Short link target | Read-your-write once, then eventual | The creator must see it; others can wait | Read primary after create |
In architecture: from a single process to a distributed system
How the same vocabulary shows up as the system grows.
Monolith: one process, one database
Everything is in one deployable: the shortener's controller, cache calls and job dispatch run in one Laravel or Go process on one machine with one PostgreSQL. Availability is the machine's; consistency is trivial (one database); latency is a function call plus a query. This is the right first design when the numbers are small. The quality attributes are met by the absence of distribution. The Go sketch (shortener.Handler) is exactly this design.
Modular monolith: boundaries without the network
The shortener splits into modules with their own tables and public interfaces: links (create, resolve), analytics (clicks), abuse (reports). They still deploy together and call each other in process, but ownership is explicit, so a later extraction is a move, not a rewrite. System design at this stage is mostly deciding the module boundaries and which module owns which table. See Modular Monolith.
Microservices: every arrow is a decision
links becomes a service that must answer in 20 ms; analytics becomes a service behind a queue; abuse becomes a service that scans asynchronously. Each arrow is now a network call with a timeout, a retry policy and a failure mode. Availability multiplies down the chain (three services at 99.9% give 99.7%); the click path must use asynchronous events so analytics being down never fails a redirect. Fowler and Lewis list both the gains (decentralised governance and data, independent deployment) and the price (every call must be designed for failure) as characteristics of the style. Read Microservices Architecture, Service Boundaries and Service Communication before splitting.
Distributed data: replicas, caches, regions
Once the data is in replicas, a cache and several regions, consistency stops being free. A user creates a link in Frankfurt and the replica in Virginia has not caught up: the first redirect returns 404 (replication lag). Fixes: read the primary right after create, route the creator to the primary region for a few seconds, or make link creation globally consistent (Spanner-class cost). A cache in each region means a purge must reach all of them. This is where CAP, PACELC, Replication Topologies and Eventual Consistency in Databases take over.
Scaling path: 1x, 10x, 100x
| Load | Design | What breaks first | Next move |
|---|---|---|---|
| 1x: 40 writes/s, 4k reads/s | One app tier of 2 servers, one PostgreSQL with standby, Redis cache | The cache stampede after a restart | Warm the cache, add a lock |
| 10x: 400 writes/s, 40k reads/s | More app servers, 2 read replicas, CDN in front, queue for clicks | Replication lag, a hot link | Read-your-write rule, per-key cache protection |
| 100x: 4,000 writes/s, 400k reads/s | Sharded store (DynamoDB, Cassandra or sharded PostgreSQL), regional deployments, edge cache | Cross-region consistency, rebalancing | Sharding at system level, consistent hashing |
Each step is triggered by a measured number, not by anxiety, and each makes the design harder to operate.
Lab: the sketch, with numbers
Experiments 1 and 3 are single-process Go programs and were run on this machine. Experiments 2 and 5 are arithmetic you can check by hand or by editing the tests. Experiment 4 needs Redis and Laravel and is labelled "expected, not run".
Experiment 1: run the tests and read them as requirements. Run on this machine; durations vary.
cd docs/snippets/system-design/what-is-system-design/go
go test -v ./...
# --- PASS: TestShortenerSketch
# ok academy/what-is-system-design/estimate
# --- PASS: TestDowntimeBudgetMatchesSRETable
# --- PASS: TestSerialThreeDependencies
# --- PASS: TestParallelTwoReplicas
# --- PASS: TestNines
# ok academy/what-is-system-design/nines
# --- PASS: TestBase62RoundTrip
# --- PASS: TestCreateThenRedirect
# --- PASS: TestRejectsBadInput
# --- PASS: TestUnknownCodeIs404
# --- PASS: TestCacheAsideReadsStoreOnce
# ok academy/what-is-system-design/shortenerExperiment 2: change one assumption and watch the numbers move. In estimate_test.go set ReadWriteRatio to 1000 and Latency to 100 ms. Average reads become about 38,600/s, peak about 193,000/s and in-flight work about 19,300: the design question flips from "one database" to "a cache is mandatory".
Experiment 3: show why the code is 302 and not 301. Run on this machine (the server binds 127.0.0.1:8080 only):
# terminal 1
go run ./cmd/shortener
# 2026/11/26 02:43:55 listening on 127.0.0.1:8080
# terminal 2
curl -s -XPOST 127.0.0.1:8080/links -d '{"url":"https://example.com/a/very/long/path"}'
# {"code":"1"}
curl -si 127.0.0.1:8080/1 | head -3
# HTTP/1.1 302 Found
# Content-Type: text/html; charset=utf-8
# Location: https://example.com/a/very/long/path
curl -si 127.0.0.1:8080/zzz | head -1
# HTTP/1.1 404 Not Found
curl -si -XPOST 127.0.0.1:8080/links -d '{"url":"javascript:alert(1)"}' | sed -n '1p;$p'
# HTTP/1.1 400 Bad Request
# shortener: url must be absolute http or httpsExperiment 4: kill the cache and measure the database. Expected, not run; with the Laravel version, run a load test at 5,000 requests/s with CACHE_STORE=redis, note database queries per second (near zero after warm-up), then flush Redis (redis-cli FLUSHALL) and watch queries spike to the request rate for a few seconds before the cache refills. The spike is the cache stampede; Caching shows the fixes.
Experiment 5: compute your own nines. Using nines.Serial and nines.Parallel, model: load balancer 99.99%, two app servers 99.9% each, database 99.95%. Expected result by hand: 0.9999 x (1 - 0.001^2) x 0.9995, about 99.94%. The database is the weakest link, so adding a third app server changes nothing and a database standby changes everything.
Common misconceptions
| Belief | Reality |
|---|---|
| System design is drawing boxes | The boxes follow from requirements, numbers and trade-offs |
| More nines is always better | Each nine costs about ten times more; stop where users stop noticing |
| CAP means pick two of three | Partitions happen; you choose between consistency and availability only during one |
| Add servers and it scales | Only if the work is divisible and the state is shared safely |
| A replica is a backup | A replica copies a bad delete instantly |
| Microservices are the modern default | They are a cost paid for team independence and independent scaling |
| The average latency is what users feel | Users feel the tail; a page with many calls hits p99 often |
| A cache fixes a slow database | It hides repeated reads; invalidation and cold start are new problems |
| Redundancy guarantees availability | Not if the copies fail together (same deploy, zone or bug) |
| Serverless means no servers to think about | It means someone else runs them; limits, cold starts and cost remain |
| The interview answer is the real design | Real design starts from measured data and existing constraints |
| 99.99% in an SLA means 99.99% in practice | The SLA is a contract with exclusions; measure your own SLI |
Cheat sheet
| Topic | What to remember |
|---|---|
| Definition | Requirements to components, data flows and trade-offs, with numbers |
| Requirements | Functional says what; non-functional says how well, with number, percentile and period |
| Nines | 99.9% is 8.76 h/year; 99.99% is 52.56 min; 99.999% is 5.26 min |
| Serial availability | Multiply: three 99.9% give 99.7% |
| Parallel availability | 1 - product of unavailabilities, if independent |
| Latency vs throughput | Time per request vs requests per second; Little's law ties them |
| Tail | Watch p99, not the mean |
| CAP | Only a partition forces the choice; otherwise latency vs consistency |
| Durability | Acknowledge after stable write; define RPO and RTO; test restores |
| Scale | Stateless app tier first; the database is usually the limit |
| Blocks | Load balancer, cache, CDN, queue, database, replication, sharding |
| SLI/SLO/SLA | Measure, target, contract; SLO tighter than SLA |
| Napkin math | 1 month is about 2.6 million seconds; 1 day about 86,400 s |
| Redirect code | 302 keeps control; 301 is cached by browsers |
| Method | Scope, estimate, design, decide; write the trade-off down |
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 — What is the difference between a functional and a non-functional requirement? Give a URL shortener example of each. Must-know
Answer
Answer: Functional: "a user can create a short link and follow it". Non-functional: "99.9% of redirects succeed and p99 is under 100 ms". The non-functional ones shape the architecture.
2 — How much downtime per year does 99.99% allow, and who published that figure? Good to know
Answer
Answer: About 52.56 minutes. The Google SRE book gives it as the example of a 99.99% target.
3 — Three services in series each have 99.9% availability. What does the user get, and why? Must-know
Answer
Answer: About 99.7%, because every service must work: 0.999 x 0.999 x 0.999 = 0.997. That is roughly 26 hours of downtime a year.
4 — Why is "two replicas at 99.9% each give 99.9999%" an upper bound? Important
Answer
Answer: It assumes the replicas fail independently. A shared deploy, a shared database, one zone or a common bug couples them, and the load balancer in front is also part of the chain.
5 — Explain CAP in one sentence without saying "pick two". Must-know
Answer
Answer: Network partitions happen in any distributed system; during one, a replica must either refuse requests (staying consistent) or answer with possibly stale data (staying available).
6 — Why does the shortener use 302 and not 301? Important
Answer
Answer: RFC 9110 describes 301 as a permanent move that clients may remember, so browsers stop asking the service; the service then cannot count clicks or change the target. 302 says the move is temporary.
7 — What is Little's law and what does it say about 19,300 requests/s at 20 ms? Important
Answer
Answer: Average in flight = arrival rate x time in system. 19,300 x 0.020 is about 386 requests in flight, so the servers must hold that much concurrency.
8 — Name two forces that pushed the industry from three-tier monoliths to microservices. Important
Answer
Answer: Commodity hardware and the failure of single-core speed to keep rising (so scaling out), the web-scale papers (Dynamo, Bigtable, MapReduce), rentable cloud servers, containers and Kubernetes, and the wish for independent team deployment.
9 — Is a replica a backup? Why? Must-know
Answer
Answer: No. A replica applies every change, including a mistaken DELETE. Backups with point-in-time recovery protect against operator error.
10 — What is the difference between an SLO and an SLA? Must-know
Answer
Answer: An SLO is an internal target for a measured SLI; an SLA is a contract with consequences. The SLO is usually stricter so you react before the contract is breached.
11 — Why must an application tier be stateless to scale horizontally, and what moves out? Must-know
Answer
Answer: Any server must be able to serve any request. Sessions, uploads and caches move to shared stores such as Redis, a database or object storage.
12 — In an interview and in real life, what is the same and what differs? Important
Answer
Answer: Same: state assumptions, justify with requirements and numbers, record trade-offs. Different: the interview invents numbers and has a clock; real work measures, has constraints and lives for years.
Glossary
| Term | Meaning |
|---|---|
| System design | Defining components, data flows and trade-offs so a system meets its requirements |
| Requirement | A statement of what a system must do or how well |
| Functional requirement | Behaviour and data rules (what) |
| Non-functional requirement | Measurable quality (how well): latency, availability, cost |
| Availability | Fraction of time or requests the system works |
| Nines | Count of leading 9s in an availability percentage |
| Reliability | Continues to do the right thing despite faults |
| Fault tolerance | Continues to serve despite a component failure |
| Redundancy | Spare components or copies |
| Single point of failure (SPOF) | A component whose failure stops the system |
| Latency | Time one request takes |
| Throughput | Work completed per unit time |
| p99 | The latency 99% of requests are under |
| Little's law | In flight = arrival rate x time in system |
| Consistency | Whether readers see the latest write |
| CAP | During a partition choose consistency or availability |
| Partition tolerance | Working despite lost messages between nodes |
| Eventual consistency | Replicas converge if writes stop |
| Durability | Acknowledged data survives failures |
| RPO / RTO | Acceptable data loss / acceptable downtime after a failure |
| Scalability | Capacity grows with added resources |
| Elasticity | Resources follow load automatically |
| Horizontal scaling | Adding machines |
| Vertical scaling | Using a bigger machine |
| Stateless | Instances keep no per-client state between requests |
| Stateful | Instances hold data others lack |
| Load balancer | Spreads requests across servers |
| Cache | Fast copy of data for reuse |
| CDN | Globally distributed cache near users |
| Message queue | Durable buffer between producer and consumer |
| Database | Durable queryable state |
| Replication | Copies of data on several nodes |
| Sharding | Splitting data across nodes by key |
| SLI / SLO / SLA | Measurement / target / contract |
| Error budget | Allowed unreliability implied by the SLO |
| Trade-off | Gaining one quality costs another |
| Back-of-the-envelope | Order-of-magnitude arithmetic before design |
| Three-tier | Presentation, application, data tiers |
| SOA | Service Oriented Architecture: services with published contracts |
| Microservices | Small, independently deployable services |
| Serverless | Code run on managed platforms with per-use billing |
| Edge | Compute and cache near users |
| Moore's law | Transistor count doubling trend; single-core speed stopped following it |
| Dynamo | Amazon's available key-value store (2007) |
| Bigtable | Google's wide-column storage system (2006) |
| MapReduce | Google's batch processing model (2004) |
| Spanner | Google's globally consistent database (2012) |
| Kubernetes | Container orchestrator |
References
- DeCandia et al., Dynamo: Amazon's Highly Available Key-value Store, SOSP 2007: PDF and commentary.
- Chang et al., Bigtable: A Distributed Storage System for Structured Data, OSDI 2006: PDF and abstract page.
- Dean and Ghemawat, MapReduce: Simplified Data Processing on Large Clusters, OSDI 2004: PDF and abstract page.
- Corbett et al., Spanner: Google's Globally-Distributed Database, OSDI 2012: PDF and abstract page.
- Dean and Barroso, The Tail at Scale, CACM 2013: abstract page.
- Google SRE Book: Embracing Risk and Service Level Objectives.
- Kleppmann, Designing Data-Intensive Applications (reliability, scalability, maintainability): book site.
- Fowler and Lewis, Microservices; Fowler, Service Oriented Ambiguity; Fowler, Serverless Architectures.
- Hohpe, The Architect Elevator.
- NIST SP 800-145, The NIST Definition of Cloud Computing.
- Latency numbers: Latency Numbers Every Programmer Should Know (credit to Jeff Dean and Peter Norvig in the gist).
- IETF, RFC 9110 HTTP Semantics.
- Laravel 13: Cache, Queues, Octane, Validation, Routing, Responses.
- Go: net/http, net/http/httptest, context.