Skip to content

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 forGo to
The whole page in four tablesEverything in one minute
Why system design exists as a disciplineWhy it exists
Mainframe to serverless, with the forces behind each shiftWhere it comes from
What system design is, and what it is notDefinition
Functional vs non-functional requirementsRequirements
Nines, uptime, serial and parallel availabilityAvailability, Nines arithmetic
Reliability, fault tolerance, redundancy, SPOFReliability
Latency, throughput, tail, napkin mathLatency and throughput, Numbers
Consistency, CAP, partition toleranceConsistency
Durability, RPO, RTODurability
Scalability, elasticity, stateless vs statefulScalability
Load balancer, cache, CDN, queue, database, replication, shardingBuilding blocks
SLI, SLO, SLA, error budgetService levels
Cost and trade-offsCost, Trade-offs
A first complete designURL shortener sketch
CodeGo, Laravel
Every other chapter in one sentenceTour of the path
Interview vs real lifeTwo audiences
Monolith to distributed systemIn architecture
Practice with numbersLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

What system design is, next to its neighbours.

DisciplineQuestion it answersTypical unitTypical artefactChapter
Software designHow is the code inside one program shaped?Class, module, functionUML, interfaces, patternsArchitecture vs Design
Software architectureWhich structural decisions are costly to change?Component, style, quality attributeADRs, views, fitness functionsWhat Is Software Architecture
System designHow do components, data and traffic fit together so the whole meets its numbers?Service, store, queue, regionDiagram + estimates + trade-off tableThis path
Infrastructure and operationsHow is it deployed, watched and recovered?Cluster, pipeline, runbookTerraform, dashboards, on-callContainers & Kubernetes

The eras.

EraTypical shapeForce that created itPrice paid
Mainframe (1960s-70s)One big machine, dumb terminalsComputers were rare and expensiveScale means buying a bigger machine
Client-server (1980s)Rich client talks to a database serverCheap PCs and LANsLogic scattered over desktops, painful deploys
Three-tier web (late 1990s)Browser, app server, databaseThe browser as a zero-install clientOne database becomes the bottleneck
SOA (2000s)Services behind a busIntegrating many enterprise systemsHeavy middleware and standards
Cloud and microservices (2006-2015 on)Fleets of small services on commodity serversMoore's law slowing for one core, cloud rental, Dynamo/Bigtable/MapReduce, containers, KubernetesDistributed-systems failure modes everywhere
Serverless and edge (2014 on)Functions and caches near the userPay per use, latency to the userCold starts, limits, vendor shapes

The vocabulary.

TermOne lineA number to remember
AvailabilityFraction of time (or requests) the system works99.99% allows 52.56 minutes down a year
ReliabilityDoes the right thing, even with faultsMeasured as failure rate, MTBF
Fault toleranceKeeps serving through a component failureNeeds redundancy plus failover
LatencyTime for one requestSame-datacenter round trip is about 500 microseconds
ThroughputRequests or bytes per unit timeLittle's law: in flight = rate x latency
ConsistencyDo readers see the latest write?Linearizable vs eventual
DurabilityOnce acknowledged, data survivesCounted in copies and years, not nines of uptime
ScalabilityGrows by adding resourcesHorizontal needs stateless or sharded state
ElasticityGrows and shrinks automatically with loadAutoscaling reaction time in seconds to minutes
CostMoney per request or per monthOften the constraint that decides
Requirementsfunctional +non-functionalSpeedlatency, throughputStay upavailability, reliability,fault toleranceCorrectconsistency, durabilityGrow and payscalability, elasticity, costTrade-offsCAP: C or A in a partitionlatency vs consistencyredundancy vs costsimple vs scalableNo free lunchevery gain is paid forsomewhere elseMeasured bySLI: the numberSLO: the targetSLA: the contract

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.

BlockSolvesIntroducesChapter
Load balancerSpread requests, hide dead serversAnother hop, a part that must itself be redundantLoad Balancing
CacheRepeated reads are fast and cheapStaleness, invalidation, stampedesCaching
CDNStatic and cacheable content close to the userPurge delays, cache keysCDNs
Message queueAbsorb bursts, decouple producer and consumerDelay, duplicates, orderingMessaging Fundamentals
DatabaseDurable, queryable stateThe hardest thing to scaleChoosing a Database
ReplicationCopies for reads and failoverLag, conflictsReplication Topologies
ShardingSplit data across machinesHot keys, cross-shard queriesSharding at System Level
1960s-70s1980slate 1990s2000s2006-20152014 onwardMainframeone big machineClient-serverfat client, DB serverThree-tier webbrowser, app, databaseSOAservices behind a busCloud + microservicesfleets of small servicesServerless + edgefunctions near the userForce: scale upby buying a bigger boxForce: cheap PCs andnetworks on every deskForce: the browser asa zero-install clientForce: integrate manyenterprise systemsForce: commodity servers,Dynamo, Bigtable, KubernetesForce: pay per use,latency to the userWhat stays constant across every eraThe same questions return: where does state live, what happens when a part fails, how does it grow, what does it cost.Each shift moves the answer, and the trade-off, to a different place.

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 passWith one
Components appear as features arriveComponents 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 productionFailure modes are listed and each has an answer or an accepted risk
One favourite technology everywhereEach store, queue and cache is chosen for its access pattern
Cost surprises at the invoiceCost per request is part of the estimate
Arguments about tasteArguments 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 ​

  1. "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.
  2. "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.
  3. "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.

text
     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 user

The 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.

text
     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, runbooks

Real 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:

NeighbourWhere the boundary fallsUse it when
Software design (Architecture vs Design)Inside a process: classes, interfaces, patternsYou are choosing how to model the code
Software architecture (What Is Software Architecture)Structural decisions and quality-attribute priorities for the whole codebaseYou are choosing monolith, modular monolith or services
System design (this path)Running topology and numbers: stores, queues, caches, regions, capacityYou 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 roomYou 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.

text
     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 actionable

Real 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:

PracticeProduct or artefactChapter
Write requirements as testable sentencesA table like the one above4-Step Approach
Turn a quality into a numberSLI, SLOSLA, SLO, SLI & Error Budgets
Rank qualities that conflictQuality attribute scenarios, utility treeRequirements 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.

text
     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 seconds

Real 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 practiceHow it raises availabilityLimit
Redundant instances behind NGINX, HAProxy, Envoy, AWS ALBOne instance can dieThe balancer is a new single point of failure unless it is redundant too
Multiple availability zones (AWS, GCP)Survives a datacentre failureCross-zone traffic costs latency and money
PostgreSQL streaming replication with failover, Amazon AuroraA standby takes overFailover takes seconds to minutes; possible data loss if asynchronous
Health checks, auto-restart, Kubernetes self-healingDead processes replacedA crash loop caused by a bad deploy is replicated everywhere
Graceful degradationCore path survives when extras failNeeds 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.

text
     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 fires

Real 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:

MechanismProduct examplesWhat it protects against
Active-active replicasNGINX/HAProxy pairs, Kubernetes Deployments with N replicasOne process or host failure
Active-passive failoverPostgreSQL with Patroni, Redis Sentinel, keepalived VRRPPrimary failure, with a gap while failing over
Multi-zone / multi-regionAWS multi-AZ, GCP regional resources, Route 53 or Cloudflare traffic steeringDatacentre and region failure
Retries, timeouts, circuit breakersGo context deadlines, Laravel HTTP client timeout()Transient network faults, slow dependencies
Graceful degradationServe cached or partial dataA 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.

text
     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 links

Real 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:

ToolGives youNotes
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 msThe gist's own caveat: values are approximate, hardware changes them
Prometheus histograms, OpenTelemetryReal percentiles in productionAverages of percentiles are wrong; aggregate histograms
Load tools (k6, wrk, vegeta)Measured throughput vs latency curveTest the realistic mix, not just GET
Capacity EstimationThe methodWrite 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."

text
     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:

ProductDefault stanceKnob
PostgreSQL with one primaryConsistent for writes; replicas lag asynchronouslysynchronous_commit, synchronous standbys
Amazon DynamoDBEventually consistent reads by defaultConsistentRead per read
Apache CassandraTunable, usually APConsistency level per query (ONE, QUORUM, ALL)
Google SpannerExternal consistency, pays latencyRead staleness options
Redis (single instance)Consistent; replicas asynchronousWAIT 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).

text
     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:

ProductDurability mechanismWhere it is weak
PostgreSQL, MySQL/InnoDBWrite-ahead log with fsync, backups, PITRWeak if fsync or synchronous_commit is relaxed for speed
RedisRDB snapshots and AOF with appendfsync policyDefault policies can lose up to about a second or more
KafkaReplicated log; acks=all, min.insync.replicasacks=1 can lose acknowledged data on leader failure
Object storage (Amazon S3, GCS)Many copies across zonesDoes 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.

text
     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 consistency

Real 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:

ProductScaling leverNote
Kubernetes Horizontal Pod AutoscalerPods follow CPU or custom metricsNeeds stateless pods
AWS Auto Scaling Groups, GCP managed instance groupsVM count follows policyWarm-up time matters
AWS Lambda, Google Cloud Run, Cloudflare WorkersPer-request scalingCold starts, concurrency limits
Laravel OctaneKeeps the app booted in memory (FrankenPHP, Swoole, Open Swoole, RoadRunner) for more requests per serverState leaks between requests are now your problem
GoGoroutines per request in net/httpShared 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.

text
     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 path

Real 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:

BlockOpen source / softwareManaged
Load balancerNGINX, HAProxy, EnvoyAWS ALB/NLB, Google Cloud Load Balancing
CacheRedis, MemcachedAmazon ElastiCache, Google Memorystore
CDNVarnish (self-hosted edge cache)Cloudflare, Amazon CloudFront, Fastly
Message queue / logRabbitMQ, Apache KafkaAmazon SQS, Amazon MSK, Google Pub/Sub
DatabasePostgreSQL, MySQL, CassandraAmazon RDS, Aurora, DynamoDB, Spanner
Object storageMinIO, CephAmazon 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.

text
     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:

ToolRole
Prometheus with recording rules; GrafanaCompute and show SLIs
OpenTelemetryEmit 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.

text
     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 load

Real 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:

PracticeProductNote
Estimate unit cost earlyCloud pricing calculators (AWS, GCP)Prices change; cite the date
Right-size and autoscaleKubernetes HPA, AWS Auto ScalingCosts follow load
Reserve or commit for steady loadSavings plans, committed useTrade flexibility for price
Reduce egressCDN, compression, regional placementEgress 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.

text
     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 modes

Real 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:

PracticeArtefact
Record the decisionAn architecture decision record: context, decision, consequences (ADR and trade-offs)
Compare options on the same axesA 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".

CompositionFormulaExampleResult
Serial (all must work)A1 x A2 x ... x An3 x 99.9%99.7003%
Parallel (any one works)1 - (1 - A1)(1 - A2)...2 x 99.9%99.9999%
Serial then parallelmultiply the group resultsLB 99.99% x (2 app x 99.9%) x DB 99.95%about 99.94%
Retries (k independent attempts)1 - (1 - A)^k3 tries at 99%99.9999%
Serial: every part must work, so availability multipliesAPI 99.9%8.76 h down a yearAuth 99.9%8.76 h down a yearDatabase 99.9%8.76 h down a year0.999 x 0.999 x 0.999 = 99.70%about 26 h down a yearParallel: one working copy is enough, so unavailability multipliesLoadbalancerCopy A 99.9%zone 1Copy B 99.9%zone 21 - 0.001 x 0.001 = 99.9999%about 32 s down a year, if independentThe parallel number is a ceiling: a shared bug, deploy or region couples the copies, and the load balancer is itself a part of the chain.

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):

OperationTimeRelative idea
Main memory reference100 ns200x an L1 hit (0.5 ns)
Send 1 KB over a 1 Gbps network10 us
Read 4 KB randomly from SSD150 us
Read 1 MB sequentially from memory250 us
Round trip within the same datacentre500 us20x less than a disk seek
Read 1 MB sequentially from SSD1 ms4x memory
Disk seek10 ms
Read 1 MB sequentially from disk20 ms
Packet California to Netherlands and back150 msthe 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 ​

WhereSignalMeaning for design
HTTP 301Moved 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 302Found"the target resource resides temporarily under a different URI" (RFC 9110, 15.4.3); the shortener's choice
HTTP 404Not FoundUnknown code; do not cache forever or a later valid code is hidden
HTTP 502Bad GatewayThe proxy "received an invalid response from an inbound server"
HTTP 503Service Unavailable"temporary overload or scheduled maintenance"; may carry Retry-After; the correct overload signal
HTTP 504Gateway TimeoutThe proxy "did not receive a timely response from an upstream server"
Go context deadline exceededcontext.DeadlineExceededA 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.

go
// 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
}
go
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.

go
// 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(),
	}
}
go
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.

go
// 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
}
go
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
}
go
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)
	}
}
go
// 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/http serves each request in its own goroutine, so a plain http.ListenAndServe already handles thousands of concurrent connections; the limits you hit first are in your own code (shared maps need a lock, as Service.cache shows) 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.Client documents "A Timeout of zero means no timeout", and context.DeadlineExceeded is what a passed deadline looks like to callers. The chapter Timeouts, Retries & Jitter builds on this.
  • httptest.NewRecorder makes 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 cache and 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
<?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
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class ShortLink extends Model
{
    protected $fillable = ['target'];
}
php
<?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
<?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
<?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
<?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::remember for 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 ShouldQueue is 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,https validation 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.

Clientsbrowser, appLoad balancerhealth checksApp server 1statelessApp server 2statelessApp server Nadd more to scaleCachecode to URL, hotDatabasesource of truthMessage queueclick eventsReplicaread copy, failoverWorkercounts clicks async1 read2 miss3 eventRead path: LB, app, cache, database on a miss. Write path: LB, app, database. Counters never block a redirect.

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.

DecisionChoiceAlternativeTrade-off
Code generationBase62 of a database sequenceRandom 6-7 charsSequence is collision-free but guessable and a bottleneck at huge write rates; random needs collision handling
Redirect status302301302 keeps control and counts; 301 saves load but browsers keep it forever (RFC 9110)
StoragePostgreSQL, one tableDynamoDB or Cassandra39 writes/s needs no sharding; keep the simple store until numbers say otherwise
CacheCache-aside, TTL one hourWrite-throughReads dominate; links rarely change; stale target for up to an hour is acceptable
CountingQueue + workerIncrement in the requestCounts are eventually consistent; redirects never wait on them
AvailabilityTwo or more app servers in two zones; DB with standbySingle nodeCosts about double; needed for 99.9%
ConsistencyRead-your-write for creation (read primary right after create)All reads from replicasA fresh link must work immediately
sql
-- 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).

BoxIf it diesFixResidual risk
Load balancerTotal outageManaged LB across zones, or an HAProxy/NGINX pair with VRRPConfig pushed to both
App serverCapacity dropsN+1 servers, health checksBad deploy hits all
CacheLatency up, database load upCache is optional; protect the database with limitsCold-start stampede
Database primaryWrites failStandby with automatic failoverReplication lag, failover time
QueueCounts delayedReplicated queue, drop counts if it is goneLost 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.

ChapterThe question it answers
The 4-Step ApproachHow do I turn this sketch into a repeatable method: scope, estimate, design, decide?
Latency Budgets & Tail LatencyHow is a latency target split across hops, and why does p99 rule?
The Client-Server ModelWhat exactly happens when one machine asks another for something?
IP, DNS, GeoDNS & TTLHow do names become addresses, and how can DNS steer traffic?
Forward vs Reverse ProxiesWhat sits between client and server, and for whom does it act?
TCP & UDPWhen do I want reliable ordered streams, and when datagrams?
HTTP EvolutionWhat changed from HTTP/1.1 to HTTP/2 and HTTP/3, and why does Keep-Alive matter?
Real-Time CommunicationHow do I push updates: polling, SSE or WebSockets, and how do I scale connections?
REST API DesignWhat makes an HTTP API predictable, idempotent and versionable?
GraphQLWhen does a query language beat fixed endpoints, and what is the N+1 trap?
gRPC & Protocol BuffersWhen do I pick typed binary RPC over REST or GraphQL?
API Versioning & EvolutionHow do I change an API without breaking clients?
Web Sessions, Cookies & CORSHow does a stateless server know who you are?
Scaling StrategiesWhen do I scale up, out or diagonally, and how does autoscaling decide?
Load BalancingWhich algorithm, layer 4 or 7, health checks and affinity?
Rate LimitingHow do token bucket, leaky bucket and windows protect a service?
CDNsWhat belongs on the edge, push or pull, and how does a cache hierarchy work?
CachingWhich cache pattern, how to invalidate, and how to survive a stampede?
Object Storage & File SystemsWhere do big files live, and how do presigned URLs work?
Write Buffering & Sharded CountersHow do I absorb hot writes and counters?
CAP, PACELC & Tunable ConsistencyWhat really happens in a partition, and what is the latency trade-off otherwise?
Consistency ModelsWhat is the difference between linearizable, serializable, causal and eventual?
ACID vs BASEWhich guarantees do I keep, and which do I trade for scale?
Replication TopologiesLeader-follower, multi-leader or leaderless quorums, and who resolves conflicts?
Sharding at System LevelHow do I pick a partition key and handle hot partitions and rebalancing?
Choosing a DatabaseHow do I model the queries first and then pick SQL, NoSQL, Redis or DynamoDB?
Cascading FailuresHow does one slow service take down all the others?
Timeouts, Retries & JitterHow do I retry without making an outage worse?
Circuit BreakerHow do I stop calling something that is failing?
Bulkheads & Graceful DegradationHow do I contain a failure and keep the core working?
Load SheddingWhat do I drop first when demand exceeds capacity?
API IdempotencyHow do keys make a retried request safe?
Distributed LockingWhen is a lock safe, and what are fencing tokens?
Leader ElectionHow do I make exactly one node active?
Gossip ProtocolsHow do nodes learn about each other and about failures?
Vector Clocks & CausalityHow do I order events without a shared clock?
Merkle Trees & Anti-EntropyHow do replicas find and repair differences cheaply?
CRDTsHow can replicas merge concurrent updates without coordination?
Geospatial IndexingHow do geohash, quadtree and R-tree answer "what is near me"?
Top-K & Heavy HittersHow do I count the most frequent items in a stream?
Strangler Fig MigrationHow do I replace a live system step by step?
Security FoundationsHow do attackers think, and what do CIA and STRIDE tell me?
AuthenticationHow do passwords, MFA, sessions and tokens fit together?
JWT Deep DiveWhat is in a token, and how is it verified or misused?
OAuth 2.0, OIDC & SSOHow does delegated login work?
Authorization ModelsRBAC, ABAC, ReBAC and zero trust: who may do what?
Cryptography in PracticeHow do TLS, PKI and secrets management work together?
OWASP Top 10Which web attacks recur, and what stops them?
DDoS & Network SecurityHow do firewalls, VPCs and segmentation limit the blast radius?
Mutual TLSHow do services prove who they are to each other?
Secure SDLC & Incident ResponseHow do I build security in and respond to a breach?
ObservabilityLogs, metrics and traces: what do I see and when?
Alerting That Actually WorksWhich alerts should wake a human?
Chaos EngineeringHow do I test failure on purpose?
Containers & KubernetesHow are services packaged, scheduled, scaled and healed?
Service Mesh & SidecarWhat does a mesh add to service-to-service traffic?
Serverless & Event-Driven ComputeWhen do functions beat servers?
Capacity Planning & Disaster RecoveryHow much is enough, and how do I recover from losing a region?
Payment ProcessingHow do idempotency, fraud checks and PCI shape payments?
Search SystemsHow do scoring, Elasticsearch and typeahead work?
ML SystemsHow are models deployed, served and fed features?
Feeds: Fan-OutFan-out on write or on read for a timeline?
Case Study: UberHow do location, matching and pricing fit together?
Case Study: NetflixWhat does a streaming platform look like end to end?
Case Study: AmazonHow does an e-commerce giant divide its services?
Case Study: WhatsAppHow is messaging delivered to billions?
Case Study: X / TwitterHow is a timeline assembled at scale?
Case Study: YouTubeHow is video uploaded, transcoded and streamed?
Case Study: OpenAIWhat does serving large models require?
Case Study: LinkedInHow do feeds, graphs and messaging scale?
Case Study: DiscordHow do chat and presence work at scale?
Case Study: TicketingHow 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.

AspectInterviewReal project
Time35 to 45 minutesWeeks of discussion, then years of operation
RequirementsVague on purpose; you must askExist in tickets, contracts, traffic graphs
NumbersInvented but must be statedMeasured from production
ConstraintsFew; everything is openTeam, budget, legacy, compliance
GoalShow structured thinking and trade-off vocabularyA system people can run for years
Good answerScope, estimate, boxes, deep dive on two areas, failure modesA smaller design plus a migration plan
Common trapDrawing every fashionable boxDesigning for the scale you hope for
What ends itA clockAn 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 ​

SituationFirst moveExtra techniqueReason
New product, unknown loadOne stateless app + one PostgreSQL, one standbyMeasure from day oneCheapest design that can be fixed later
Reads dominate, same items repeatedlyAdd a cache (Redis)CDN for static partsRead amplification is solved by memory
Slow work in the request pathMove it to a queue and workerIdempotent consumersThe user should not wait for email or reports
One database cannot hold the writesVertical first, then partition or shardChoose the key from the access patternSharding is irreversible-ish
Global users, high latencyCDN and regional read replicasGeoDNSSpeed of light sets a floor
Strict correctness (money, stock)Single writer, transactionsIdempotency keys, an append-only ledgerOne wrong number costs more than latency
Always-write requirement (cart, log)Leaderless or multi-leader storeConflict resolutionDynamo-style availability
Spiky or tiny workloadServerless functionsBudget for cold startsPay per use
Many teams, one codebase hurtsModular monolith, then servicesStrangler figSplit by business boundary, not by layer

Which consistency for which data ​

DataNeedsReasonExample mechanism
Account balanceStrongWrong number is worse than a delaySingle primary, serializable or row locks
Inventory at checkoutStrong at the final stepOversellingConditional update
Product pageEventualA few seconds old is fineCache with TTL
Like counterEventualApproximate is fineSharded counters, async
Short link targetRead-your-write once, then eventualThe creator must see it; others can waitRead 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 ​

LoadDesignWhat breaks firstNext move
1x: 40 writes/s, 4k reads/sOne app tier of 2 servers, one PostgreSQL with standby, Redis cacheThe cache stampede after a restartWarm the cache, add a lock
10x: 400 writes/s, 40k reads/sMore app servers, 2 read replicas, CDN in front, queue for clicksReplication lag, a hot linkRead-your-write rule, per-key cache protection
100x: 4,000 writes/s, 400k reads/sSharded store (DynamoDB, Cassandra or sharded PostgreSQL), regional deployments, edge cacheCross-region consistency, rebalancingSharding 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.

bash
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/shortener

Experiment 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):

bash
# 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 https

Experiment 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 ​

BeliefReality
System design is drawing boxesThe boxes follow from requirements, numbers and trade-offs
More nines is always betterEach nine costs about ten times more; stop where users stop noticing
CAP means pick two of threePartitions happen; you choose between consistency and availability only during one
Add servers and it scalesOnly if the work is divisible and the state is shared safely
A replica is a backupA replica copies a bad delete instantly
Microservices are the modern defaultThey are a cost paid for team independence and independent scaling
The average latency is what users feelUsers feel the tail; a page with many calls hits p99 often
A cache fixes a slow databaseIt hides repeated reads; invalidation and cold start are new problems
Redundancy guarantees availabilityNot if the copies fail together (same deploy, zone or bug)
Serverless means no servers to think aboutIt means someone else runs them; limits, cold starts and cost remain
The interview answer is the real designReal design starts from measured data and existing constraints
99.99% in an SLA means 99.99% in practiceThe SLA is a contract with exclusions; measure your own SLI

Cheat sheet ​

TopicWhat to remember
DefinitionRequirements to components, data flows and trade-offs, with numbers
RequirementsFunctional says what; non-functional says how well, with number, percentile and period
Nines99.9% is 8.76 h/year; 99.99% is 52.56 min; 99.999% is 5.26 min
Serial availabilityMultiply: three 99.9% give 99.7%
Parallel availability1 - product of unavailabilities, if independent
Latency vs throughputTime per request vs requests per second; Little's law ties them
TailWatch p99, not the mean
CAPOnly a partition forces the choice; otherwise latency vs consistency
DurabilityAcknowledge after stable write; define RPO and RTO; test restores
ScaleStateless app tier first; the database is usually the limit
BlocksLoad balancer, cache, CDN, queue, database, replication, sharding
SLI/SLO/SLAMeasure, target, contract; SLO tighter than SLA
Napkin math1 month is about 2.6 million seconds; 1 day about 86,400 s
Redirect code302 keeps control; 301 is cached by browsers
MethodScope, estimate, design, decide; write the trade-off down

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
System designDefining components, data flows and trade-offs so a system meets its requirements
RequirementA statement of what a system must do or how well
Functional requirementBehaviour and data rules (what)
Non-functional requirementMeasurable quality (how well): latency, availability, cost
AvailabilityFraction of time or requests the system works
NinesCount of leading 9s in an availability percentage
ReliabilityContinues to do the right thing despite faults
Fault toleranceContinues to serve despite a component failure
RedundancySpare components or copies
Single point of failure (SPOF)A component whose failure stops the system
LatencyTime one request takes
ThroughputWork completed per unit time
p99The latency 99% of requests are under
Little's lawIn flight = arrival rate x time in system
ConsistencyWhether readers see the latest write
CAPDuring a partition choose consistency or availability
Partition toleranceWorking despite lost messages between nodes
Eventual consistencyReplicas converge if writes stop
DurabilityAcknowledged data survives failures
RPO / RTOAcceptable data loss / acceptable downtime after a failure
ScalabilityCapacity grows with added resources
ElasticityResources follow load automatically
Horizontal scalingAdding machines
Vertical scalingUsing a bigger machine
StatelessInstances keep no per-client state between requests
StatefulInstances hold data others lack
Load balancerSpreads requests across servers
CacheFast copy of data for reuse
CDNGlobally distributed cache near users
Message queueDurable buffer between producer and consumer
DatabaseDurable queryable state
ReplicationCopies of data on several nodes
ShardingSplitting data across nodes by key
SLI / SLO / SLAMeasurement / target / contract
Error budgetAllowed unreliability implied by the SLO
Trade-offGaining one quality costs another
Back-of-the-envelopeOrder-of-magnitude arithmetic before design
Three-tierPresentation, application, data tiers
SOAService Oriented Architecture: services with published contracts
MicroservicesSmall, independently deployable services
ServerlessCode run on managed platforms with per-use billing
EdgeCompute and cache near users
Moore's lawTransistor count doubling trend; single-core speed stopped following it
DynamoAmazon's available key-value store (2007)
BigtableGoogle's wide-column storage system (2006)
MapReduceGoogle's batch processing model (2004)
SpannerGoogle's globally consistent database (2012)
KubernetesContainer orchestrator

References ​

Built by Morteza Negahi