Scaling and performance
Foundations F12. What to say when the interviewer asks "how does this scale?": throughput vs latency and why targets are percentiles, why latency explodes as servers near 100% busy, how fan-out turns a rare slow call into the common case, scaling up vs out with stateless servers, why ten servers aren't ten times faster, finding the bottleneck and making each request cheaper, what autoscaling can't do, and how to shed load under overload. Each idea is told as a story you'll remember, with a lab that shows p99 rising with utilisation, fan-out and a surge.
Start here
"How does this scale?" comes up in every round, and "add more servers" is the answer that loses points. Interviewers want to hear what you measure (a percentile, not an average), how latency behaves as servers get busy, why fan-out makes rare slow calls common, when one bigger machine beats ten small ones, why ten servers are never ten times faster, how to find the real bottleneck, what autoscaling can and can't do, and what the system does when load goes past everything you planned.
This page covers those eight ideas. Caching, replication and sharding, and queues have their own pages; this one is about the arithmetic underneath all of them. Timeouts, circuit breakers and failover are on the reliability page that follows.
Long-weekend Friday at the Khalapur toll plaza
It's 6 pm on the Friday before a long weekend, and half of Mumbai is driving to Pune and Lonavala. Everything on this page happens at one toll plaza on the Expressway:
- The plaza clears a few thousand cars an hour, but you only care how long your car waits, and the unlucky car behind a truck paying in cash waits far longer than the average. (latency, throughput, percentiles)
- Each booth takes about 10 seconds a car. Cars arrive a little slower than that, so the booths "keep up", and still the queues stretch back a kilometre. (utilisation and queueing)
- Your family is in five cars. You agreed to meet at the food mall after the toll, so everyone waits for the slowest car. (tail latency and fan-out)
- You can make a booth faster or open more booths. Any booth can serve any car, because the FASTag balance lives at the bank, not in the booth. (scale up, scale out, stateless)
- Twenty booths, but after the plaza the road narrows into the ghat. (why scaling isn't linear)
- FASTag cut the time per car instead of adding booths. (find the bottleneck, make the work cheaper)
- Extra staff live twenty minutes away; by the time they arrive, the queue has doubled. (autoscaling and lead time)
- When the queue passes the yellow line 100 m back, cars go through free. (load shedding and graceful degradation)
The plaza on this page is a teaching story; the FASTag and 100-metre figures are real and cited.
Latency, throughput and percentiles
Throughput is how much work the system finishes per second; latency is how long one request takes; and latency is a distribution, so you state it as a percentile (p99 under 200 ms), never as an average.
Cars per hour vs your wait
The plaza manager is proud: 4,000 cars an hour, average wait two minutes. That's throughput, and an average.
You don't experience either. You experience your wait. And tonight one lane has a truck whose driver is paying in cash and arguing about the change. The twenty cars behind it wait fifteen minutes. The average barely moves, because thousands of other cars sailed through.
If the manager reported "99 out of 100 cars wait under 6 minutes", that number would jump the moment one lane jams. That's why you ask for the percentile.
- Throughput: requests (or bytes, or jobs) finished per second. Latency: time for one request, measured from the caller's side. They are linked but different: a system can have high throughput and terrible latency (a full queue) or low latency and low throughput (one fast worker).
- Percentiles: p50 (median) is the typical request; p99 is the slowest 1 in 100; p99.9 the slowest 1 in 1,000. Averages hide the tail and its changes.
- Why the tail matters: the slowest requests often belong to your heaviest users (biggest carts, most data), and with fan-out (below) the tail becomes what most users see.
Measure it right:
- Use histograms and compute percentiles from merged histograms; you can't average the p99s of ten servers into a fleet p99.
- Measure at the client or load balancer, so queueing time is included.
- Load-test at a fixed arrival rate (open loop). A tester that waits for each reply before sending the next slows down exactly when the server stalls, and hides the stall.
State targets per operation: "p99 under 200 ms for reads at 10,000 a second", with the load stated, because latency depends on load.
Google's SRE book makes the case with a real example: "although a typical request is served in about 50 ms, 5% of requests are 20 times slower", and "a simple average can obscure these tail latencies, as well as changes in them." Its guidance: "we generally prefer to work with percentiles rather than the mean", with the 99th or 99.9th percentile showing "a plausible worst-case value" and the median the typical case.
- p99 vs p99.9: a higher percentile catches more of the bad experiences but needs far more samples to be stable and is much harder to meet; pick it per operation, not one for everything.
- Throughput vs latency: batching and big queues raise throughput but add waiting; for user-facing calls, latency wins; for background jobs, throughput does.
I'll set the target as p99 under 200 ms for the read API at 10,000 requests a second, measured at the load balancer, and keep throughput and latency as separate numbers.
Saying "average latency 50 ms" as a requirement, or averaging per-server p99s into a dashboard number. Both hide exactly the requests users complain about.
Utilisation and queueing: why 90% busy is slow
Latency stays flat while servers have spare time, then climbs steeply as utilisation nears 100%, because random arrivals queue; one shared line and bigger pools push that bend later.
The booth that "keeps up"
A booth takes 10 seconds a car. Cars arrive about every 11 seconds on average, so on paper the booth is 91% busy and keeps up.
But cars don't arrive every 11 seconds. Sometimes three come together, then nobody for half a minute. The booth can't serve the idle half-minute later, so the bunches pile up. At 91% busy, the average car waits about ten times its own 10 seconds.
Now look at the lanes. Each lane has its own line, and you picked yours. The next lane is moving, but you can't switch. A bank-style single line feeding all the booths would have kept every booth busy and nobody stuck behind the cash payer.
- Utilisation ρ = arrival rate × work per request ÷ number of workers. At 100% the queue grows without limit; well below 100% it still exists, because arrivals are bursty.
- The classic single-server curve (random arrivals, random work, M/M/1): average time = work ÷ (1 − ρ). At 50% busy that's 2× the work time, at 80% 5×, at 90% 10×, at 99% 100×. The exact numbers depend on how variable the work is; the shape (flat, then a cliff) doesn't.
- Pooling: c workers sharing one line (M/M/c) wait far less than c separate lines at the same utilisation, because no worker idles while a request waits elsewhere. Big pools can run hotter than small ones; that's why a rule like "never above 70%" is a starting point, not a law.
- Little's law (L = λ × W) ties it together: as latency rises, requests in flight rise with it, filling threads, connections and memory, which slows things further (see back-of-envelope estimation).
- Practical rules: plan to the utilisation where your p99 crosses its target (measure that point in a load test), keep queues short so overload turns into fast rejections instead of slow successes, and remember that utilisation must leave room for a lost zone and a deploy.
Google's SRE book gives the cost of a long queue: with a queue 10 times the thread pool and 100 ms per request, a full queue adds about 1.1 seconds of latency, most of it waiting. Its advice is to keep queues small relative to the thread pool ("e.g., 50% or less") so servers reject early, and notes that Gmail uses queueless servers.
The lab below makes the curve concrete: 80 workers sharing one line at 90% busy give a p99 of 93 ms for 20 ms of work; the same 80 workers with separate lines give 921 ms (both rounded, from the standard queueing formulas).
- Run hotter: fewer machines, lower cost, but less room for bursts, slower recovery after a failure, and a p99 that jumps with small traffic changes.
- Run cooler: stable latency and headroom for failures, but you pay for idle capacity; autoscaling narrows the gap for stateless tiers, not for databases.
I'll size the API tier so it runs about 60% busy at peak: the p99 curve is still flat there, and we can lose a zone without crossing 90%.
Treating 95% CPU as "efficient". Near 100%, latency is dominated by waiting, and one burst or one lost server tips it into timeouts and retries.
Tail latency and fan-out
When one request waits for many parallel calls, it is as slow as the slowest, so a 1-in-100 slow call hits most requests at high fan-out; fix it with fewer calls, hedged requests and partial results, not just more servers.
Five cars, one food mall
Your family is driving to Lonavala in five cars. You've agreed to stop together at the food mall after the toll. Each car has a small chance of getting the slow lane, the truck with the cash payer.
With one car, that chance is small. With five, it's about five times bigger, and when it happens all five cars wait. On a school trip with fifty buses, some bus almost always gets the slow lane. The trip is as slow as the slowest car.
At the food mall, your cousin has a trick of his own. He orders the same vada pav at two counters, takes whichever comes first and cancels the other. One extra order now and then, and he never waits for the slow counter.
- With fan-out f and each call slow with probability p, the chance a request hits at least one slow call is 1 − (1 − p)^f. At p = 1%: 1 call → 1%, 10 calls → 10%, 100 calls → 63%.
- Where fan-out comes from: search over many shards, a page built from many services, scatter-gather reads, microservice chains (a chain adds latencies; a fan-out takes the maximum).
- Causes of slow calls are usually not the code: garbage collection pauses, a noisy neighbour, a background compaction, a queue behind a burst, a cold cache.
Fixes, in order of cost:
- Cut the fan-out: batch look-ups, co-locate data, precompute the page.
- Set per-call timeouts from the end-to-end deadline, and return partial results ("good enough" search results, a page without one widget).
- Hedged requests: if a call hasn't returned by about its p95, send a second copy to another replica and use whichever answers first; tied requests queue the call on two replicas (about a millisecond apart), and whichever starts it first tells the other to drop it. Only for idempotent reads.
Then, and only then, add capacity.
Dean and Barroso's "The Tail at Scale" (Google, CACM 2013): if a server typically responds in 10 ms but has a p99 of one second, a request that fans out to 100 such servers will take more than one second 63% of the time. In a Google service they measured, the p99 for one random leaf was 10 ms, but for all leaves to finish it was 140 ms.
Their fix in practice: in a Bigtable benchmark reading 1,000 keys spread over 100 servers, sending a hedged request after 10 ms cut the p99.9 for retrieving all 1,000 values from 1,800 ms to 74 ms, for just 2% more requests.
- Hedging cuts the tail cheaply but adds load; trigger it late (around the p95), cap it, and never hedge non-idempotent writes.
- Partial results keep latency bounded but need a product decision on what may be missing.
The feed calls 40 services in parallel, so per-call p99 isn't enough: I'll budget each call against the page's deadline, hedge reads that pass their p95, and render without a widget that misses it.
Setting every service's target to the page's target. At high fan-out, each service needs a much stricter tail (p99.9 or better) for the page to meet its p99.
Scale up, scale out, and keep servers stateless
Scale up (a bigger machine) first, because it is simple and modern hardware is huge; scale out (more machines) when you need more than one box or can't afford to lose one, which only works if any server can handle any request.
A faster booth or more booths
The plaza can buy a faster booth: a better scanner, a second attendant. That's scaling up. It's easy (nothing about the lanes changes) but there's a limit to how fast one booth gets, and if that booth's barrier jams, the lane is dead.
Or it can open more booths. That's scaling out. It only works because any booth can serve any car: the FASTag balance is at the bank, the rate card is on the wall. If each attendant kept his regulars' monthly passes in his own drawer, those cars would have to queue at his booth, and when he went for chai they couldn't pass at all.
- Scale up (vertical): more CPU, RAM, faster disks on one machine. No code changes, no coordination. Limits: the biggest machine you can buy, cost that rises steeply at the top, and one machine as a single point of failure (keep a standby).
- Scale out (horizontal): more machines behind a load balancer. Near-unlimited for stateless tiers, survives losing a machine, and lets you autoscale. Costs: a load balancer, deploys across many machines, and every piece of shared state must live somewhere else.
- Stateless servers: sessions, carts and uploads go to a shared store (Redis, a database, object storage), so any server can take any request and losing one loses nothing. Sticky sessions are a crutch: uneven load and painful failover.
- How the balancer spreads load matters (lab below): round robin and random ignore how busy each server is; least-request with power of two choices (pick two servers at random, send to the less busy) gets close to one shared line at almost no cost.
- Databases are the hard part: scale them up first, then add read replicas, and shard only when the numbers force it (see replication and sharding).
Stack Overflow is the classic scale-up example. In February 2016 it served about 209 million HTTP requests a day, which ran about 505 million SQL queries, on 11 web servers and a two-server SQL Server cluster for Stack Overflow itself (384 GB of RAM each), with SQL CPU "almost always at 5–10%" (Nick Craver, Feb and Mar 2016).
Envoy's least-request balancer is a public example of power of two choices: with equal weights it picks two random healthy hosts and sends the request to the one with fewer active requests (Envoy docs). Mitzenmacher's 2001 paper showed that two choices instead of one give "exponential improvements" in the time a request spends in the system.
- Up: simplest and often cheapest at moderate scale, but a hard ceiling and a big blast radius. Out: no ceiling for stateless work and better fault tolerance, but more moving parts and shared state to manage.
- Least-request balancing beats round robin when request costs vary, but needs live load information (or a cheap estimate) at the balancer.
The API servers are stateless (sessions in Redis), so they scale out behind least-request balancing. The database starts as one large primary with a replica; at 5–10K writes a second that's comfortable, and I'd shard only past that.
Sharding the database or reaching for microservices at a load one well-sized machine handles. Say the number that one box can do first.
Try it: Where does latency go as load rises?
Pick a workload and see four things move with your numbers: how busy the tier is, one call's p99 as utilisation rises (one shared line vs a line per worker), what fan-out does to the page's p99, and what a surge does before new instances are ready. The verdict flips across the presets: healthy, a small pool on the cliff, random balancing, a fan-out tail no server count can fix, and a flash sale that outruns autoscaling.
A product-details API: 2,000 requests a second, 20 ms of work each, 10 instances running 8 requests at a time, least-busy balancing. Target: p99 under 150 ms. A 1.5× bump is normal in the evening.
| What we're sizing | Number | How we got it | So we decide |
|---|---|---|---|
| 1 · How busy the tier is | |||
| UtilisationUtilisation is the share of time workers are busy. It is the one number that tells you where you are on the latency curve. | 50% | workers = 10 instances × 8 = 80; one worker finishes 1,000 ÷ 20 = 50 a second capacity = 80 × 50 = 4.0K requests/s → utilisation = 2.0K ÷ 4.0K = 50% in flight at once (Little's law, L = λ × W): 2.0K/s × 20 ms = 40 | Healthy headroom: most requests start work as soon as they arrive. |
| 2 · Latency of one call | |||
| p99 of one callLatency stays flat for a while, then bends up sharply as utilisation nears 100%. A shared line (least-busy balancing) bends much later than separate lines, and big pools bend later than small ones. | 92 ms | one shared line: a request waits only if all 80 workers are busy; Erlang C says that happens to 0% of requests average = 20 ms (work alone: 20 ms); median = 14 ms; p99 = 92 ms p99 at the same utilisation with the other spread: 184 ms 50% → 92 ms · 70% → 92 ms · 80% → 92 ms · 90% → 93 ms · 95% → 95 ms · 99% → 148 ms | Plan utilisation from this curve, not from a rule of thumb: find where your p99 crosses the target. |
| 3 · The user's request: fan-out | |||
| p99 the user seesWith fan-out, the rare slow call stops being rare: at 40 calls, about a third of page loads include one. The page is as slow as its slowest call. | 92 ms | the request waits for the slowest of 1 call: share of requests with at least one call slower than one call's p99 = 1 − 0.99^1 = 1% user p99 = the time t where P(one call ≤ t)^1 = 0.99 → 92 ms (target 150 ms) floor with unlimited servers (no waiting, work alone): 92 ms → target met with 41 workers = 6 instances | Inside the target. |
| 4 · A sudden surge | |||
| At 1.5× trafficAutoscaling reacts after the load arrives. If the surge is faster than boot time, the gap is a queue, and a queue past the client timeout is an outage. | 75% busy | 2.0K × 1.5 = 3.0K/s against 4.0K/s capacity capacity covers the surge, so nothing piles up while autoscaling reacts autoscaler (Kubernetes HPA rule): ceil(10 × 75% ÷ 60%) = 13 instances | Reactive autoscaling is enough for a surge this size. |
| 5 · Verdict for this workload | |||
| What you get | Healthy: inside the target with headroom50% busy, p99 92 ms against a 150 ms target. A 1.5× surge takes it to 75%, which it can ride out while autoscaling adds instances. Watch p99 and utilisation together: the curve in step 2 shows where it starts to bend. | ||
Try: on Product API, raise requests to 3,600 (90% busy) and see the p99 barely move with one shared line, then switch to Random. On Small pool, double the instances. On Fan-out 40, set parallel calls to 5. On Flash sale, set boot time to 0 (warm spares). Model: random arrivals and random (exponential) work per request, steady state, no retries or timeouts; real systems have burstier traffic and slow outliers this model doesn't capture, so treat the numbers as rounded teaching values.
Why ten servers aren't ten times faster
Any part of the work that can't be split (a shared database, a lock, a single queue) caps the speed-up, and coordination between servers can make adding more slow things down; find the shared piece before you add servers.
Twenty booths, one ghat
The plaza opens twenty booths, and for a kilometre the traffic flies. Then the Expressway narrows into the Khandala ghat, three lanes up the hill. Twenty booths can't push more cars up the ghat than it takes; they just move the jam two kilometres down the road.
It gets worse. A stolen-car alert comes in, and every booth must phone every other booth to check whether the car has passed. With four booths that's a few calls. With twenty, the attendants spend more time on the phone than collecting tolls.
- Amdahl's law: if a share s of the work is serial, the best speed-up on N machines is 1 ÷ (s + (1 − s) ÷ N), and never more than 1 ÷ s. With 5% serial: 10 machines give about 6.9×, and no number of machines gives more than 20×.
- Universal Scalability Law (Gunther) adds a second cost, coherence: servers keeping each other in sync. Capacity C(N) = N ÷ (1 + α(N − 1) + βN(N − 1)). With contention α = 0.05 and coherence β = 0.0005 (illustrative), 10 servers give about 6.7×, the peak is about 11× at roughly 44 servers, and 100 servers give only about 9×: adding servers makes it slower.
Where the serial part hides in real designs:
- One primary database every request writes to.
- A global lock, a single counter, or one hot key.
- Connections: 50 app instances × a pool of 20 = 1,000 connections against a database that defaults to 100. A connection pooler (PgBouncer) or smaller pools fix it.
- Coordination: cache invalidations broadcast to every node, chatty consensus, cross-shard transactions.
So: scale the stateless tier freely, but always name the shared resource behind it and its limit.
PostgreSQL's max_connections defaults to typically 100 connections, and every connection is a backend process with its own memory; a widely used configuration reference advises that "if you need more than 200 connections, you should probably be making more use of connection pooling" (third party, postgresqlco.nf).
Gunther's paper derives the peak: throughput is highest at N* = √((1 − α) ÷ β) and becomes "retrograde" after it (arXiv, Aug 2008).
- Removing a serial part (sharding the database, partitioning a lock) raises the ceiling but adds complexity; do it only for the resource the numbers say is the cap.
- Coordination buys correctness (one source of truth); every broadcast or consensus round you add costs scalability.
Adding API servers won't help past this point: every request writes to one primary. I'll put PgBouncer in front so 200 instances share 100 connections, batch the writes, and shard the orders table only if writes pass what one primary can take.
Drawing an autoscaling group in front of one database and calling it scalable. Interviewers will ask what the database does when you have 10× the servers.
Find the bottleneck, then make each request cheaper
Before adding capacity, find the one resource that saturates first (check utilisation, saturation and errors for each), then cut the work per request: fewer round trips, batching, caching, precomputing, and moving work off the request path.
FASTag instead of more booths
The old fix for toll queues was more booths. But the slow part wasn't the number of booths; it was what happened in each one: stop, find cash, count change, print a receipt, lift the barrier.
FASTag changed the work, not the booths. A tag on the windscreen is read as the car rolls up, the bank deducts the toll, the barrier lifts. Same booths, same road, and the wait collapsed.
Before deciding what to fix, someone had to stand at the plaza and ask: is the jam at the booth, at the barrier, or on the road after it?
- USE method (Brendan Gregg): "for every resource, check utilization, saturation, and errors": CPU, memory, disk, network, connection pools, thread pools, locks, downstream quotas. The resource that is saturated (has work queued) is the bottleneck; fixing anything else changes nothing.
Then look at where one request's time goes (a trace waterfall or a profile). Common wins, roughly in order:
- Round trips: the N+1 query (load 50 orders, then one query per order) becomes one query with a join or an IN list; batch API calls.
- Batching: write 500 rows in one statement, send one message with 100 events.
- Caching and precomputing: compute the feed or the totals once on write, not on every read.
- Off the request path: emails, thumbnails, indexing go to a queue; the user waits only for what they need.
- Payload size: fetch only the columns and fields you need; compress large responses.
Optimise the critical path, the longest chain of dependent steps; speeding up something that runs in parallel with a slower step saves nothing.
India's Ministry of Road Transport told the Lok Sabha on 10 August 2023 that, according to a study it cited, "average waiting time at fee plazas has been reduced from 734 Seconds to 47 Seconds" after FASTag: about 15× less, from changing the work per car rather than adding booths.
In software, the same move is batching round trips. GraphQL's DataLoader library "will coalesce all individual loads which occur within a single frame of execution" into one call to your batch function, turning N look-ups into one.
- Precomputing makes reads cheap but writes heavier and the data slightly stale; batching raises throughput but adds a little wait to each item.
- Optimising code is cheaper than buying servers only when it's the bottleneck; profile before rewriting.
Before scaling, I'd check which resource saturates first. Here each feed request makes 50 database round trips; batching them into one query cuts the database load 50× and the latency by most of a second, which is cheaper than any number of new servers.
Adding servers to fix a slow query, or caching to hide an N+1 pattern. Name the bottleneck resource and the work per request first.
Autoscaling: rules, signals and lead time
Autoscaling adds instances when a metric passes a target, but it reacts after the load arrives and new instances take time to be ready, so pre-scale for known peaks, keep headroom for sudden ones, and scale on the signal that actually saturates.
Staff who live twenty minutes away
At 6 pm the plaza manager sees the queue growing and calls in extra staff. They live twenty minutes away. By the time they've parked, logged in and opened their booths, the queue is twice as long, and it takes an hour to clear.
The manager who has done this before doesn't wait for the queue. She checks last year's long-weekend Friday, sees the rush starts at 5:30, and has the extra staff seated by 5:15. The phone call is only for surprises.
- Reactive (target tracking): the Kubernetes HPA rule is desiredReplicas = ceil(currentReplicas × currentMetric ÷ targetMetric). At 50 replicas, 90% CPU against a 75% target: ceil(50 × 90 ÷ 75) = 60. Small differences are ignored (a tolerance), and scale-down waits so it doesn't flap.
- Lead time is the catch: metric collection, the decision, booting, warming caches and passing health checks can take a minute or more. A surge faster than that becomes a queue (lab step 4).
- Pick the right signal: CPU works for CPU-bound services. For I/O-bound ones, use requests in flight, queue depth or lag (see queues and event streams). For GPUs and LLM serving, use batch or queue occupancy, not CPU.
- Predictive and scheduled: forecast daily and weekly cycles, and pre-scale for known events (a sale, a match, results day). Keep a minimum that covers a lost zone.
- Warm capacity: warm pools, pre-pulled images and small start-up times shrink the lead time; serverless cold starts are the same problem at a smaller scale.
- What doesn't autoscale quickly: databases, caches (new nodes start cold), anything with state, and your downstream quotas.
Disney+ Hotstar is the Indian example. In 2018 Hotstar's Akash Saxena wrote that, given the time autoscaling takes, it is useless for sudden spikes: they estimate peak concurrency and scale up ahead of the event, using "ladders" of capacity per service. At AWS re:Invent 2019, describing a record 25.3 million concurrent viewers, the team explained that traffic could grow by over a million users a minute while scaling reacted in about 90 seconds and an application took about a minute to boot, so they pre-warmed before the match and scaled up ahead of demand on request count or platform concurrency (session report, third party).
AWS's predictive scaling shows the cyclical version: it needs at least 24 hours of history, forecasts capacity hourly for the next 48 hours, and can launch instances ahead of each hour so they are ready in time.
- Reactive scaling is cheap and simple but always late; pre-scaling is on time but costs idle capacity and needs a forecast.
- Aggressive scale-up with slow scale-down absorbs spikes but costs more; aggressive scale-down saves money and invites flapping.
The API autoscales on requests in flight per pod, with a floor that survives losing a zone. For the 8 pm sale, I'll pre-scale to the forecast peak at 7:45, because a new pod takes about 90 seconds to be ready and the spike arrives in under one.
"We'll just autoscale" as the answer to a flash spike. Say the lead time, compare it with how fast the load rises, and say what happens in the gap.
Overload: shed load, degrade gracefully, and budget retries
When demand exceeds capacity, the goal is to keep finishing useful work: reject the excess early and cheaply, drop low-priority work first, turn off non-essential features, and stop retries from multiplying the load.
The yellow line 100 metres back
Every toll lane has a yellow line painted 100 metres before the booth. If the queue goes past it, the barriers open and cars go through without paying until the queue is back behind the line.
The plaza gives up some money to keep the highway moving. Without the rule, the queue would spill onto the Expressway, cars would brake and change lanes, and the jam would spread kilometres back, hurting everyone, including the toll collector.
Notice what the plaza drops: the part it can do without (collecting from a few cars), never the part that matters (letting cars through).
- Under overload, throughput can collapse: requests wait so long that clients time out, so the server spends its time on work nobody is waiting for. What matters is goodput, useful work finished in time.
- Load shedding: when a server is past its limit (requests in flight, queue time, CPU), reject new requests fast (HTTP 429 or 503) instead of queueing them. A fast "no" beats a slow "yes" that times out. Rejecting still costs something, so reject as early and as cheaply as possible.
- Priority: label requests (checkout over recommendations, user traffic over batch) and shed the lowest first.
- Graceful degradation: serve a cached or simpler answer, turn off personalisation, hide a widget, accept writes into a queue.
- Bounded queues and deadlines: a short queue, and a deadline passed down the call chain, so nobody works on a request whose caller has given up.
- Retries multiply load: three layers that each try 4 times can turn one user action into 4 × 4 × 4 = 64 calls on the database. Retry at one layer, with backoff and jitter, under a retry budget.
- Client-side throttling: clients that see many rejections start failing some requests locally, so the backend isn't spending its capacity on saying no.
NHAI's guideline of May 2021 is the real version of the story: service time of no more than 10 seconds per vehicle, no queue longer than 100 metres, a yellow line at 100 metres in each lane, and vehicles "allowed to pass without paying toll" while the queue is past it (reported 28 May 2021).
Google's SRE book gives the software numbers: each request gets at most three attempts, and each client keeps retries under 10% of requests, which cuts retry growth from nearly 3× to about 1.1×. Its client-side throttling starts rejecting locally once requests reach twice the accepted ones (K = 2), and it labels requests CRITICAL_PLUS, CRITICAL, SHEDDABLE_PLUS and SHEDDABLE so the right ones go first. Hotstar's 2019 talk lists turning off recommendations and personalisation during a live match to keep streaming and payments running (session report, third party).
- Shedding keeps the system up for most users but fails some requests on purpose; without it, everyone gets slow, then everyone fails.
- Degraded features (no recommendations) are a product decision; agree on the order before the incident, not during it.
Each API server caps requests in flight; past that it returns 503 with Retry-After, shedding recommendation calls before checkout. Clients retry once with jittered backoff under a 10% retry budget, and only the edge retries, not every layer.
Letting every layer retry three times with no budget. During an overload, retries are the load that keeps it overloaded.
Remember it
One line per idea. Read this the night before.
- Cars per hour vs your wait: throughput and latency are different numbers, and latency is a percentile at a stated load.
- The booth that "keeps up": near 100% busy, waiting dominates; one shared line and bigger pools bend the curve later.
- Five cars, one food mall: a request is as slow as its slowest call; at 100-way fan-out, a 1% tail hits 63%.
- A faster booth or more booths: scale up first; scale out stateless servers, with least-request balancing.
- Twenty booths, one ghat: the serial part (one database, one lock, connections) caps the speed-up, and coordination can reverse it.
- FASTag instead of more booths: find the saturated resource, then cut the work per request.
- Staff twenty minutes away: autoscaling is late by its lead time; pre-scale known peaks, scale on the signal that saturates.
- The yellow line: under overload, reject early, drop the least important work, and budget retries.
Check yourself
Answer out loud, then open.
Your API's average latency is 40 ms and the dashboard looks fine, but users complain that the app is slow. What do you check, and how?
The average hides the tail. Check:
- p99 and p99.9 per endpoint, from histograms merged across servers (not averaged per-server percentiles).
- Latency measured at the load balancer or client, so time spent waiting in queues is included.
- Who is in the tail: often the heaviest users (big carts, many items) or requests that fan out.
- Whether the tail moves with load: if p99 jumps at busy hours, it's queueing (utilisation); if it's there all day, it's the work itself (a slow query, GC pauses, a slow dependency).
Say it I'd set the target as a percentile at a stated load, and alert on p99, not the mean.
A service runs 20 ms of work per request on 8 workers and handles 360 requests a second. The team says it has 10% headroom. Is it fine?
Utilisation = 360 × 0.02 ÷ 8 = 90%. With only 8 workers, that's the steep part of the curve:
- About 70% of requests find all workers busy and wait.
- The p99 is around 140 ms for 20 ms of work (from the M/M/c formulas, rounded).
- A 10% burst takes it to ~100%, where the queue grows without limit.
Options: add workers (10 workers gives a p99 under 100 ms), make each request cheaper, or both. Big pools can run hotter than small ones; 8 workers can't.
A search page queries 100 shards in parallel. Each shard's p99 is 50 ms, and the page's p99 target is 100 ms. What happens, and what do you do?
The page waits for the slowest shard, so it sees 1 − 0.99^100 ≈ 63% of requests with at least one shard past its p99. The page's p99 is set by each shard's p99.99, which is far higher than 50 ms.
Fixes:
- Hedge: if a shard hasn't answered by its p95, send the query to another replica of that shard; use the first answer (reads are idempotent).
- Return partial results after a deadline (most users won't notice one missing shard).
- Reduce fan-out: fewer, bigger shards, or a first tier that only queries likely shards.
- Make each shard's tail tighter (separate background compaction, keep queues short).
When would you scale up instead of out?
Scale up when one machine can carry the load with headroom:
- Databases and other stateful systems, where scaling out means sharding (application changes, cross-shard queries).
- Moderate scale: Stack Overflow ran about 500 million SQL queries a day on a two-server cluster in 2016.
- When simplicity matters more than the last bit of cost efficiency.
Scale out when:
- The tier is stateless (add servers behind a load balancer, autoscale).
- You need more than the biggest machine, or can't afford one machine as a single point of failure.
Say it scale up first for state, scale out for stateless work.
You doubled the API servers from 50 to 100 but throughput went up only 10%. Why might that be, and what do you look for?
Something shared is the bottleneck, so the serial part caps the speed-up (Amdahl), or coordination is eating the gains (USL).
Look for:
- The database: CPU, locks, connection count. 100 instances × 20 connections = 2,000 against a limit of a few hundred; put a pooler in front.
- A hot key, a global lock, one counter or one queue partition.
- A downstream service or quota that's now saturated.
- Coordination traffic that grows with servers (broadcast invalidations, membership chatter).
Then fix that resource (pooling, batching, sharding the hot table) rather than adding more servers.
A flash sale starts at 8 pm and traffic will jump 5× within a minute. New pods take 90 seconds to be ready. Is autoscaling on CPU enough?
No. Reactive scaling sees the load only after it arrives, and it needs at least 90 seconds plus metric and decision time. During that gap the tier is ~5× over capacity, so requests pile up and time out, and retries make it worse.
Instead:
- Pre-scale to the forecast peak before 8 pm (scheduled or predictive scaling), with the database and caches warmed too.
- Keep the reactive autoscaler for surprises, scaling on requests in flight rather than CPU.
- Have load shedding and degraded modes ready: protect checkout, drop recommendations.
- Check the shared limits (database connections, payment-provider quotas) at 5×.
During an incident, the database is at 100% and every layer is retrying. What do you change so it can recover?
Retries are now part of the load: three layers × 4 attempts each is up to 64 database calls per user action.
Change:
- Retry at one layer only (the edge or the client), with exponential backoff and jitter.
- A retry budget: retries at most ~10% of requests per client.
- Deadlines passed down the chain, so servers drop work whose caller has given up.
- Load shedding: cap requests in flight, return 503 or 429 with Retry-After fast, lowest priority first.
- Client-side throttling, so clients stop sending what will be rejected anyway.
Say it I'd make overload produce fast rejections for some users, not timeouts for all of them.
Where you'll use this in the series
- Back-of-envelope estimation · Little's law and servers = peak ÷ (capacity × utilisation)
- How a request travels · load balancers and connection pools
- Caching · cutting work per request, and cold caches after scaling out
- Replication and sharding · what to do when the database is the serial part
- Queues and event streams · moving work off the request path, and scaling consumers on lag
- Rate limiter · per-caller limits before overload, and what a 429 means
- Uber: from tap to pickup · stateless tiers, fan-out to nearby drivers, surge traffic
- Reliability and disaster recovery · timeouts, circuit breakers and failover
- LLM serving platform (ChatGPT-style) · GPU utilisation, batching vs latency, and autoscaling on queue depth (coming)
Sources
- Validity of the single processor approach to achieving large scale computing capabilities, Gene Amdahl, AFIPS (1967)
- The power of two choices in randomized load balancing, Michael Mitzenmacher, IEEE TPDS (2001)
- A General Theory of Computational Scalability Based on Rational Functions, Neil J. Gunther, arXiv (Aug 2008)
- The Tail at Scale, Jeffrey Dean and Luiz André Barroso, Communications of the ACM (Feb 2013)
- Service Level Objectives, Google SRE book, ch. 4 (2016)
- Handling Overload, Google SRE book, ch. 21 (2016)
- Addressing Cascading Failures, Google SRE book, ch. 22 (2016)
- Stack Overflow: The Architecture, 2016 Edition, Nick Craver (Feb 2016)
- Stack Overflow: The Hardware, 2016 Edition, Nick Craver (Mar 2016)
- Scaling Is Not An Accident, Akash Saxena, Hotstar (2018)
- How Hotstar dealt with 25 million concurrent viewers, re:Invent 2019 CMY302 session report, Classmethod (Dec 2019, third party)
- NHAI guidelines to ensure service time of not more than 10 seconds, The Hitavada (28 May 2021)
- Lok Sabha starred question 302 on FASTag waiting time, Ministry of Road Transport and Highways (10 Aug 2023)
- The USE Method, Brendan Gregg (checked Oct 2026)
- Horizontal Pod Autoscaling, Kubernetes docs (checked Oct 2026)
- Kubernetes v1.33: HorizontalPodAutoscaler configurable tolerance, Kubernetes blog (Apr 2025)
- How predictive scaling works, Amazon EC2 Auto Scaling docs (checked Oct 2026)
- Supported load balancers (least request, P2C), Envoy docs (checked Oct 2026)
- Connections and authentication (max_connections), PostgreSQL docs (checked Oct 2026)
- max_connections, postgresqlco.nf (third party, checked Oct 2026)
- DataLoader README, graphql/dataloader on GitHub (checked Oct 2026)
- System design core concepts, Hello Interview (third party, used to cross-check interview expectations)
Checked October 2026. Theory comes from the papers listed (Amdahl 1967, Mitzenmacher 2001, Gunther 2008, Dean & Barroso 2013) and the Google SRE book (2016); product behaviour from the Kubernetes, AWS, Envoy and PostgreSQL docs; company figures are as published on the dates shown (Stack Overflow 2016, Hotstar 2018 and 2019, NHAI 2021, MoRTH 2023) and may have changed since. The Hotstar 2019 talk is cited through a third-party session report. The lab uses standard queueing formulas (M/M/1, M/M/c) with rounded teaching values.
System Design Mastermind · Foundations
Series homeAll of Foundations
18 publishedStart here: the concepts every design uses, each told as a story you'll remember.
How a request travels: DNS, load balancers, gateways and open connections
Name → address (DNS) → open a secure line once and reuse it (TCP, TLS) → nearby copies for static files (CDN) → spread and guard the work (load balancer, gateway) → find colleagues inside (discovery) → keep a line open for live updates.
The interview framework: requirements, numbers and scope before boxes
Agree what users must do (three core requirements) → put numbers on how well (p99 latency, availability, durability, staleness) → say what's out of scope → sketch the simple end-to-end design → go deep only where a number breaks it.
Back-of-envelope estimation: from users to servers in one minute
Users × actions ÷ 86,400 (≈10⁵) = average per second → × peak factor → split reads and writes → storage = count × size × time × copies → bandwidth × 8 bits → in flight = rate × latency → servers = peak ÷ (capacity × 60%) + 2 spares.
APIs and real-time communication: REST, gRPC, retries, webhooks and live updates
Nouns + HTTP verbs (user from the token) → REST outside, gRPC inside → cursor pagination → POST with an Idempotency-Key, retries with backoff and jitter → add, don't change → poll for rare updates, SSE for one-way live, WebSockets for both ways → webhooks are at-least-once → thin connection gateways with resume and push fallback.
Databases: data models, indexes and transactions
Relational by default (each fact once, keys, constraints) → key-value / document / wide-column / graph only for a named access pattern → B-tree for reads, LSM for heavy writes → composite index with equality columns first, then the sort → one transaction per local change, made durable by the write-ahead log → know your isolation level → win races with a conditional write and a unique constraint.
Replication and sharding: copying and splitting your data
Copies scale reads and survive failures (leader + followers); splits scale writes and size (shards). Replicate first; shard only when data size or write rate outgrows one leader → pick the shard key from the main query → hash it into many fixed slots so growth moves ~1/(N+1) → name your hot key and your one cross-shard query.
Caching: hit ratios, invalidation and stampedes
Cache what is read far more than it changes → say the expected hit ratio and size the database for the misses → cache-aside with a TTL; on writes, update the database then delete the key → coalesce misses on hot keys and jitter TTLs → plan for the cache failing or restarting empty, because by then the system depends on it.
Consistency, CAP and quorums: what replicas promise
Say what each operation needs, not what the system is: strong (linearizable) for money, stock, seats and uniqueness; read-your-writes for a user's own data; eventual for counts, feeds and pages → during a partition, strong operations fail on the minority side, the rest keep serving (CAP) → on a normal day, strong costs a round trip to a quorum (PACELC) → with N copies, W + R > N makes reads overlap the latest write, but it isn't linearizability.
Coordination: clocks, leaders, locks and consensus
Don't order events across machines by wall-clock time; let one leader assign the order → elect that leader by majority vote with increasing terms, so a split network can't elect two → give it a lease so a dead leader is replaced without anyone proving it died → and a fencing token the storage checks, so a paused old leader can't do harm → use consensus (Raft) for the few decisions that must be agreed, not for every request.
Queues and event streams
Put a queue between work that can wait and the caller, so a spike becomes lag instead of an outage → use a task queue for jobs and an event log (Kafka) when many consumers need every event, replay or per-key order → key by the entity whose order matters and size partitions for peak consumers → deliver at least once and make consumers idempotent → retry a few times with backoff, then dead-letter → scale on lag → publish through an outbox, never "save, then publish".
Idempotency, exactly-once and sagas
Treat a timeout as unknown, never as failed → make writes idempotent by design (set, don't add; client IDs; conditional writes) → for the rest, an idempotency key per intent, stored with the result in the same transaction as the effect → consumers deduplicate by message ID in the same transaction → exactly-once holds only inside one boundary → across services, use a saga of local steps with compensations, not 2PC → compensable steps first, the pivot (capture payment) next, retryable steps last, on a durable orchestrator.
Scaling and performance
State latency as a percentile at a stated load → size each tier to the utilisation where its p99 is still flat (pooled, least-request balancing lets you run hotter) → budget fan-out calls against the page deadline, hedge stragglers → scale up first, scale out stateless tiers → name the shared resource (database, lock, connections) that caps the speed-up → find the saturated resource and cut work per request → pre-scale known peaks, autoscale on the signal that saturates → under overload, shed the lowest-priority work fast and budget retries.
Reliability and disaster recovery
Turn the target into a downtime budget → cut hard dependencies, because chains multiply → spread copies across zones (cells for blast radius) → timeouts from the deadline, one layer of jittered retries under a budget → circuit breakers with fallbacks and a bulkhead per dependency → fast, non-flapping health checks (readiness checks dependencies, liveness doesn't) → statically stable: spare capacity already running, config cached → PITR plus tested restores, because replicas copy mistakes → the cheapest DR strategy that meets RTO and RPO, drilled.
Observability and safe deployments
Metrics to notice, traces to locate, logs to explain (joined by a trace ID) → watch latency percentiles, traffic, errors and saturation → set an SLO per user journey and treat 1 − SLO as an error budget → page on burn rate over two windows, not on CPU → canary every change on a slice with automated analysis against a baseline → keep every version compatible with its neighbours (expand, migrate, contract) so rollback is always possible → ship dark behind flags, and stage config like code → when it breaks: one commander, mitigate first, blameless postmortem.
Security essentials for system design
Prove who the caller is (slow salted hashes, MFA, passkeys, rate-limited login) → carry identity in short-lived signed tokens with revocable refresh tokens, or in sessions you look up → delegate with OAuth code flow + PKCE, sign in with OpenID Connect → check this user against this object on every request, least privilege for people and services, audit logs → TLS 1.3 at the edge, mTLS inside, no trust from network location → envelope encryption with a KMS, secrets in a vault, tokenise what you needn't keep → treat all input as data (parameterise, encode, CSRF tokens, no user-chosen fetches) → absorb floods and abuse at the edge.
Search, feeds and geo building blocks
Search: analyse text into terms → inverted index of sorted postings → BM25 or hybrid (BM25 + vectors via RRF) retrieval of ~1,000 candidates → learned ranker → shards with replicas, fed from the database by CDC, refreshed every second. Typeahead: precomputed top-k per prefix in memory. Feeds: push IDs into followers' timelines, pull celebrities at read time, hydrate, filter, rank, page with cursors. Geo: index by cell (geohash, S2, H3), search the cell plus neighbours, exact distance on the few candidates.
Data pipelines: batch and stream
Pick batch or stream by how fresh each output must be. Get data in with log-based CDC (snapshot, then the WAL) and schemas that evolve safely; land raw events as Parquet in lakehouse tables partitioned by date. Batch jobs map, shuffle and reduce one partition and overwrite it, so retries and backfills are safe. Stream jobs window by event time, fire on watermarks, decide whether late events wait, correct or drop, and checkpoint state with offsets for exactly-once effect, with transactional or idempotent sinks. Reprocess by replaying retained data (Kappa) rather than keeping two codebases (Lambda).
AI foundations: inference, RAG and agents
Latency is time to first token (prefill reads the prompt, compute-bound) plus output tokens × time per token (decode, memory-bound), so stream answers and limit by tokens. GPU memory is weights plus a KV cache per request; long prompts, not users, fill it. Continuous batching shares each weight read across many requests, cutting cost per token by 10× or more until time per token hits its target. Route easy requests to small models, cache shared prompt prefixes, quantize carefully. RAG retrieves, reranks and cites a few permission-filtered chunks; agents are tool-calling loops with budgets, idempotent tools and approval for irreversible steps. Evaluate every change on an eval set, and design so a model fooled by prompt injection still can't do damage.