Courses / System Design Interview / Chapter 3
Module 1 · Foundations · Chapter 3 of 49
Non-Functional Requirements: Availability, Scale, Latency and More
Builds on The System Design Interview: How It Runs and How to Answer and Core Concepts: RPCs, Consistency, Failures and Time. Next up: Back-of-the-Envelope Estimates.
Part 1 · Availability and the nines
What availability measures
A system can do the right thing and still be useless if it is down when users need it. Availability is the share of time, or of requests, during which a service works as promised.
Two definitions are in common use. Time-based availability is the fraction of a period, usually a month or a year, in which the service is up. AWS's reliability documentation defines it as the percentage of time a workload is available for use, and advises against excluding planned maintenance from the total, because users still want the service then. Request-based availability counts requests instead: the share of requests that succeed. Google's site reliability book argues for this one in globally distributed services, because a service that is partly broken for some users is never entirely up or entirely down. Its example: a service handling 25 lakh requests a day with a 99.99% target can return up to 250 errors in a day and still meet the target.
People shorten targets to the "number of nines": 99.9% is three nines, 99.99% is four. Each extra nine cuts the allowed downtime by a factor of ten, and costs more. AWS's guidance is to find the real need before choosing, because each higher level demands stricter testing, automated recovery from every kind of failure, and slower, more careful change.
The two definitions can disagree. Suppose a shop is down for 30 minutes at 3 a.m. and for another 30 minutes during a festival sale. Time-based availability treats both outages the same, because each is 30 minutes. Request-based availability counts far more failed requests for the sale-day outage, which is closer to the harm done. When you state a target, say which definition you mean and over what window, such as a rolling 30 days.
Three terms from the same book keep the discussion precise. A service level indicator (SLI) is the measurement itself, such as the share of requests that succeed. A service level objective (SLO) is the target for that measurement, such as 99.9% over 30 days. A service level agreement (SLA) is a contract with users that says what happens, often a refund, when an objective is missed. Teams usually set the internal SLO tighter than the SLA, so they get a warning before they owe anyone money.
How much downtime a target allows
The conversion is a one-line calculation: downtime allowed is (100 minus the target) percent of the period. The snippet prints it for a year, a 30-day month and a day, and then repeats the request-based example.
YEAR_MIN = 365 * 24 * 60 def fmt(minutes): if minutes >= 60 * 24: return f"{minutes / (60 * 24):.1f} days" if minutes >= 60: return f"{minutes / 60:.1f} hours" if minutes >= 1: return f"{minutes:.1f} min" return f"{minutes * 60:.1f} s" print("target per year per 30 days per day") for pct in (99, 99.9, 99.95, 99.99, 99.999): down = (100 - pct) / 100 print(f"{pct:<8}{fmt(YEAR_MIN * down):>12}" f"{fmt(30 * 24 * 60 * down):>14}{fmt(24 * 60 * down):>10}") # request-based: errors allowed in a day requests, target = 2_500_000, 0.9999 print("errors allowed per day:", round(requests * (1 - target)))
target per year per 30 days per day 99 3.6 days 7.2 hours 14.4 min 99.9 8.8 hours 43.2 min 1.4 min 99.95 4.4 hours 21.6 min 43.2 s 99.99 52.6 min 4.3 min 8.6 s 99.999 5.3 min 25.9 s 0.9 s errors allowed per day: 250
A real run. A year here is 365 days.
Check one row against the published numbers. The site reliability book says 99.99% allows 52.56 minutes of downtime in a year; the run prints 52.6. AWS's table gives 8 hours 45 minutes for 99.9%, which is the 8.8 hours printed. The request example matches too: 25 lakh requests at 99.99% leaves room for 250 errors.
Read the table as a budget. At 99.99% you have about four minutes a month. A single slow deployment or a database failover that takes five minutes uses it all. That is why high targets force automation: a human cannot notice, diagnose and fix a problem in that time.
A service promises 99.9% monthly availability. Roughly how long can it be fully down in a 30-day month?
- About 43 minutes, from the run: 43.2 minutes for 99.9% over 30 days.
- Going to 99.99% cuts that to about four minutes.
Why can request-based availability suit a global service better than uptime?
- A failure often affects only some users or some requests, so "up or down" is too coarse.
Part 2 · Reliability: MTBF and MTTR
Failing less and recovering faster
Reliability is the ability of a system to keep working correctly over time. Availability asks whether the service is there; reliability asks whether it keeps doing the right thing and how often it breaks.
Two numbers describe how a component behaves. MTBF, mean time between failures, is the average working time between one failure and the next. MTTR, mean time to recover (or repair), is the average time from a failure to being back in service. AWS's reliability documentation gives a way to estimate availability from them: availability is MTBF divided by the sum of MTBF and MTTR. Its example, an MTBF of 150 days and an MTTR of one hour, comes to about 99.97%.
The formula shows that two levers exist. You can fail less often, which raises MTBF, or you can recover faster, which lowers MTTR. Failing less is expensive and has a floor, because hardware, software and people all fail eventually. Recovering faster is often cheaper: automatic restarts, health checks and tested rollbacks all shrink MTTR. Good monitoring helps too, because a failure that nobody notices for an hour has an MTTR of at least an hour before any repair begins.
It helps to split MTTR into its stages: the time to detect the failure, the time to diagnose it, the time to fix it, and the time to confirm the fix. Each stage has its own remedy. Alerts on user-facing errors shorten detection. Dashboards and logs that point at the failing part shorten diagnosis. A rollback that one command performs shortens the fix. In many incidents the fix itself is quick and most of the time goes on noticing and understanding.
The formula over sample values
def availability(mtbf_hours, mttr_hours): return mtbf_hours / (mtbf_hours + mttr_hours) cases = [ ("fails every 150 days, 1 h to fix", 150 * 24, 1), ("fails every 59 s, 1 s to fix", 59 / 3600, 1 / 3600), ("fails every 30 days, 10 h to fix", 30 * 24, 10), ("fails every 30 days, 1 h to fix", 30 * 24, 1), ("fails every 30 days, 6 min to fix", 30 * 24, 0.1), ("fails every 300 days, 10 h to fix", 300 * 24, 10), ] for label, mtbf, mttr in cases: a = availability(mtbf, mttr) down_min = (1 - a) * 365 * 24 * 60 print(f"{label:<35} {a * 100:.4f}% {down_min:,.0f} min/year")
fails every 150 days, 1 h to fix 99.9722% 146 min/year fails every 59 s, 1 s to fix 98.3333% 8,760 min/year fails every 30 days, 10 h to fix 98.6301% 7,200 min/year fails every 30 days, 1 h to fix 99.8613% 729 min/year fails every 30 days, 6 min to fix 99.9861% 73 min/year fails every 300 days, 10 h to fix 99.8613% 729 min/year
A real run, in hours converted to minutes per year.
The first row reproduces the AWS example: 99.9722%, about 146 minutes of downtime a year. The three rows after the 59-second case hold MTBF at 30 days and cut the repair time from 10 hours to 1 hour to 6 minutes. Availability climbs from 98.63% to 99.86% to 99.99%.
The last row is the useful comparison. A component that fails ten times less often (every 300 days instead of 30) but takes 10 hours to fix has the same availability, 99.8613%, as one that fails every 30 days and takes 1 hour to fix. A tenfold cut in repair time is worth as much as a tenfold gain in reliability, and is usually easier to get.
A service that crashes and restarts itself within a second, every minute, has an MTBF of 59 seconds and an MTTR of one second. The formula gives 98.33%, which is under two nines, and users would see errors all the time. The second row of the run shows it. Fast automatic recovery does not make up for failing often.
The formula is an estimate. It treats failures as independent and the averages as typical. A rare long outage and many short ones can share an MTBF and MTTR and feel very different to users, so do not use it for a promise to customers without checking real incident history.
| Term | Meaning |
|---|
Part 3 · Scalability
Making a system bigger
Scalability is how well a system keeps its performance as load grows. A service that handles 100 users and fails at 10,000 does not scale.
There are two ways to add capacity. Vertical scaling (scaling up) moves the service to a bigger machine with more processing power, memory or disk. It is simple, because nothing in the program changes, but machines have a ceiling and a single big machine is a single point of failure. Horizontal scaling (scaling out) adds more machines and spreads the work across them. It has no fixed ceiling and survives the loss of one machine, but the work must be divisible.
Scaling up is often the right first step, because it changes nothing in the code and one machine is simpler to run than ten. It stops being enough when the biggest affordable machine is too small, or when one machine going down is not acceptable. Scaling out also allows auto-scaling: adding servers when load rises and removing them when it falls, so you pay for the peak only while it lasts.
Scaling reads and scaling writes are different problems. Reads can often be served by copies of the data, such as caches and replicas, so adding more of them adds capacity. Writes must usually reach one authoritative place, so they are harder to spread, and later chapters on partitioning and on counters that many users update show how.
The key to scaling out is making servers stateless: a server keeps no data between requests that another server would need. Any request can then go to any server, so a load balancer can spread traffic freely and you add capacity by adding servers. State, such as user accounts and orders, lives elsewhere, in a database or a cache that all servers share. This moves the hard problem rather than removing it: the shared store becomes the part that is hardest to scale, and in most systems it is the first bottleneck. Later chapters on databases and caches deal with it.
One worker or four
The snippet below builds the simplest version of scaling out. Each worker is a separate process with its own port that does a few milliseconds of computing work per request. The client sends 400 requests, 32 at a time, spreading them over the workers in turn. It runs once with one worker and once with four.
import asyncio, hashlib, multiprocessing as mp, sys, time PORTS = [55436, 55437, 55438, 55439] async def handle(reader, writer): await reader.readline() h = b"x" for _ in range(20000): # a few ms of work h = hashlib.sha256(h).digest() writer.write(h.hex()[:8].encode() + b"\n") await writer.drain() writer.close() def serve(port): async def main(): await asyncio.start_server(handle, "127.0.0.1", port) await asyncio.sleep(3600) asyncio.run(main())
async def one(port): r, w = await asyncio.open_connection("127.0.0.1", port) w.write(b"go\n") await r.readline() w.close() async def throughput(ports, total=400, conc=32): sem = asyncio.Semaphore(conc) async def job(i): async with sem: await one(ports[i % len(ports)]) t = time.perf_counter() await asyncio.gather(*(job(i) for i in range(total))) return total / (time.perf_counter() - t) if __name__ == "__main__": print("python", sys.version.split()[0]) procs = [mp.Process(target=serve, args=(p,)) for p in PORTS] for p in procs: p.start() time.sleep(1.5) for n in (1, 4): rate = asyncio.run(throughput(PORTS[:n])) print(f"{n} worker(s): {rate:6.0f} req/s") for p in procs: p.terminate()
python 3.12.10 1 worker(s): 75 req/s 4 worker(s): 269 req/s
A real run; the numbers vary with machine load.
On this machine, four workers handled about 3.6 times the requests per second of one. The exact numbers change from run to run; in repeated runs the ratio stayed between about 3.5 and 3.8. The gain is below four for two reasons: the client that generates the load runs on the same machine and takes some CPU, and process start-up and scheduling cost something. With a database shared by all workers, the gain would shrink further, because every worker would also wait on the same store.
The workers here are stateless. Any request goes to any port and gets a correct answer, which is the property that makes the spreading possible. Real services keep that property by pushing state out of the server, for example by storing a login session in a shared store and not in the memory of one process. If each worker had kept its own copy of a user's session, a request routed to the wrong port would fail.
Part 4 · Latency, throughput and the tail
Two different speeds
Latency is how long one request takes, from sending to receiving the reply. Throughput is how many requests the system completes per unit of time. They are related but not the same. A system with many parallel lanes can have high throughput and still make each request slow.
Reporting latency as an average is misleading. Google's site reliability book makes the point: a simple average can hide slow outliers, and its example has a typical request near 50 ms while 5% of requests are about 20 times slower. Use percentiles instead. The 50th percentile (p50, the median) is the time that half of requests beat. The 99th percentile (p99) is the time that 99% of requests beat, so one request in a hundred is slower. The slowest requests are called the tail, and p99 is the usual way to describe it.
Users feel the tail. Someone loading a page that makes several requests meets a slow one far more often than the per-request rate suggests.
Latency and throughput are tied together by Little's law: the average number of requests in the system equals the arrival rate times the average time each one spends there. A service receiving 1,000 requests a second that takes 0.2 s per request has about 200 requests in flight at any moment. That is why a slowdown can turn into an outage. If a dependency slows the same service to 2 s per request, it suddenly holds 2,000 requests in flight, and if it has only, say, 500 worker threads or connections, new requests start to queue or fail.
Percentiles from a sample
The snippet generates 1 lakh request times: most cluster near 20 ms, and one request in a hundred is slowed by a factor of twelve. It then prints the mean and three percentiles.
import random, statistics rng = random.Random(1) # 100,000 request times in ms: mostly near 20, with a slow tail sample = [rng.lognormvariate(3.0, 0.5) for _ in range(100_000)] for i in range(len(sample)): if rng.random() < 0.01: sample[i] *= 12 # 1 request in 100 is slow q = statistics.quantiles(sample, n=100) print(f"mean {statistics.mean(sample):6.1f} ms") print(f"p50 {q[49]:6.1f} ms") print(f"p95 {q[94]:6.1f} ms") print(f"p99 {q[98]:6.1f} ms")
mean 25.3 ms p50 20.2 ms p95 48.1 ms p99 101.3 ms
A real run; the seed makes it repeatable.
The mean is 25.3 ms and the median 20.2 ms, which looks fine. The p99 is 101.3 ms, five times the median. A dashboard that shows only the mean would miss the slow requests entirely.
How fan-out stretches the tail
Many requests are answered by calling several other servers and waiting for all of them. The number of calls is the fan-out. If each call is slow with probability 0.01, a request that makes n calls is slow if any call is, which happens with probability 1 minus 0.99 to the power n. That is 1% for one call, about 9.6% for ten, and 63.4% for a hundred.
The second half of the snippet confirms it by simulation: it builds pages that wait for 100 calls each drawn from the same sample, and prints the median page time next to the single-call p99.
print("\nfan-out n: chance of waiting on at least one slow call") for n in (1, 10, 100): print(f" n={n:<4} {1 - 0.99 ** n:6.1%}") fan = 100 # one page calls 100 servers pages = [max(rng.choice(sample) for _ in range(fan)) for _ in range(2000)] pq = statistics.quantiles(pages, n=100) print(f"page time, fan-out {fan}: p50 {pq[49]:.0f} ms") print(f"single call p99 was {q[98]:.0f} ms")
fan-out n: chance of waiting on at least one slow call n=1 1.0% n=10 9.6% n=100 63.4% page time, fan-out 100: p50 181 ms single call p99 was 101 ms
The median page took 181 ms, above the 101 ms that only 1% of single calls exceeded. At this fan-out, the single-call tail becomes the typical case. Dean and Barroso make the general point in "The Tail at Scale": temporary slow episodes that do not matter in a moderate-sized system can dominate the performance of a large one. The probability formula above is simple arithmetic, not a claim from that paper.
Common remedies are to reduce fan-out, to set deadlines and return partial results, and to send a second copy of a slow request to another replica and use whichever answer comes first. That last one is called a hedged request. If the second copy is sent only after the first has waited longer than most requests take, only the slowest few are sent twice, so the extra load is small, and it cuts the tail because two replicas are rarely slow at the same moment. Later chapters return to these remedies.
Why is p99 better than the mean for a latency target?
- The mean hides slow outliers; in the run, mean 25.3 ms but p99 101.3 ms.
- p99 describes the slowest 1% that users notice.
Part 5 · Fault tolerance: redundancy in series and in parallel
Designing for parts that fail
Fault tolerance is the ability to keep serving when parts fail. The standard tool is redundancy: keep spare copies of components so that one failure does not stop the service. How much redundancy helps depends on how components are connected.
Components in series all have to work. A request that passes through a load balancer, an application server and a database fails if any one fails. AWS's documentation states the rule for such hard dependencies: the availability of the whole is the product of the availabilities of its parts. Three independent services at 99.99% each give 99.99% three times over, about 99.97%.
Components in parallel are redundant. The system fails only if all copies fail. The documentation gives the rule: take 100% minus the product of the failure rates. Two independent components at 99.9% each fail together with probability 0.1% times 0.1%, so the pair is available 99.9999% of the time.
Replicas beat the chain: 0.5 vs 158 min (downtime per year, from the run)
Read it as steps
A chain of three services loses availability; a pair of replicas gains it
The calculation, run
The snippet defines the two rules and applies them, then builds a realistic path: a balancer, two application servers in parallel and one database, followed by the same path with a replica database.
def series(*avail): total = 1.0 for a in avail: total *= a return total def parallel(*avail): fail = 1.0 for a in avail: fail *= 1 - a return 1 - fail def down(a): return f"{(1 - a) * 365 * 24 * 60:,.1f} min/year" three = series(0.9999, 0.9999, 0.9999) pair = parallel(0.999, 0.999) print(f"three 99.99% in a chain: {three:.6%} {down(three)}") print(f"two 99.9% side by side: {pair:.6%} {down(pair)}") # a request path: balancer -> 2 app servers -> database path = series(0.9999, parallel(0.999, 0.999), 0.9995) print(f"balancer, 2 apps, 1 db: {path:.6%} {down(path)}") path2 = series(0.9999, parallel(0.999, 0.999), parallel(0.9995, 0.9995)) print(f"same, with a replica db: {path2:.6%} {down(path2)}")
three 99.99% in a chain: 99.970003% 157.7 min/year two 99.9% side by side: 99.999900% 0.5 min/year balancer, 2 apps, 1 db: 99.939905% 315.9 min/year same, with a replica db: 99.989875% 53.2 min/year
A real run.
The first two rows match the AWS figures. The chain of three loses about 158 minutes a year; the replica pair loses half a minute. Now read the last two rows. A single database in series caps the whole path at 99.94%, no matter how many application servers you add. Replicating the database lifts the path to 99.99%.
Two cautions. The formulas assume failures are independent. Two replicas in the same rack, on the same power feed or running the same buggy release can fail together, so the real figure is worse. Cloud providers group data centres into separate locations with their own power and networking; AWS calls them Availability Zones, and its documentation uses redundant resources in different zones as its example of independent components. Placing replicas in different zones brings the independence assumption closer to true.
The second caution: a replica only helps if traffic actually moves to it when the first copy fails, which the next page takes up: spare capacity.
Capacity to survive a failure
Redundancy needs spare capacity. A balancer sends traffic to the servers that are healthy, so when one stops answering its work moves to the others. If they are already close to full, they fail as well.
The snippet assumes each server can handle 100 requests a second and 240 arrive. It shows the load per server with three servers and with four, before and after one fails.
CAPACITY = 100 # requests/s one server can handle TOTAL = 240 # requests/s arriving at the balancer for servers in (3, 4): for failed in (0, 1): load = TOTAL / (servers - failed) state = "ok" if load <= CAPACITY else "OVERLOADED" pct = load / CAPACITY print(f"{servers} servers, {failed} down: " f"{load:5.1f} req/s each ({pct:4.0%}) {state}")
3 servers, 0 down: 80.0 req/s each ( 80%) ok 3 servers, 1 down: 120.0 req/s each (120%) OVERLOADED 4 servers, 0 down: 60.0 req/s each ( 60%) ok 4 servers, 1 down: 80.0 req/s each ( 80%) ok
A real run.
Watch for the load each server carries before and after a failure
Read it as steps
Three servers share 240 requests a second; one fails and the other two exceed their capacity
Part 6 · Maintainability, and writing requirements as numbers
Maintainability
Maintainability is how easily people can keep a system running and change it. A system is built once and then run and changed for years, so this quality decides much of the long-term effort, even though it is easy to forget in a design. It has three practical sides. Operability means the people running the system can see what it is doing and fix problems, which needs metrics, logs and clear runbooks. Simplicity means a new engineer can understand it. Evolvability means it can be changed to meet new requirements without a rewrite.
Maintainability cannot be measured as neatly as latency, but you can still state it as a requirement: a deploy that takes under ten minutes, a rollback that takes under five, an on-call engineer who can find the failing component from a dashboard. Stating it makes the trade-off visible, for example when a clever optimisation makes a system harder to debug.
Non-functional requirements also pull against each other. Lower latency can mean more cache servers, which cost money and can serve stale data. Higher availability means more replicas, which cost money and make consistency harder. A design discussion is mostly about which requirement to favour for this product, and the next page shows how to write the targets down so that the choice is explicit.
Other qualities belong on the same list when the product needs them. Durability is the promise that stored data is not lost, which is separate from availability: a service can be down for an hour and lose nothing, or stay up and silently drop writes. Consistency says how fresh a read must be, using the models from the core concepts chapter. Cost is a requirement too, for example a ceiling on spend per thousand requests, and it often decides between two designs that both meet the other targets.
From a wish to a number
A non-functional requirement describes how well a system must work, as opposed to what it must do. Requirements like "fast", "scalable" and "highly available" cannot be designed against. A useful requirement has a number, a unit and a way to measure it.
| Vague | Stated as a number |
|---|---|
| The site must be fast | p99 latency under 300 ms for the home page, measured at the load balancer |
| It must handle lots of traffic | 5,000 requests per second at peak, about five times the average |
| It must be reliable | 99.9% of requests succeed, measured over 30 days |
| It must be easy to run | Roll back a bad release in under 5 minutes |
| Never lose an order | An acknowledged order survives the loss of any one data centre |
Once the target is a number, it implies a budget. The snippet turns the availability line of the table into an error budget, the amount of failure the target allows.
requirements = {
"peak load": "5,000 requests/s",
"availability": "99.9% of requests succeed, per 30 days",
"latency": "p99 under 300 ms",
}
peak, slo, days = 5000, 0.999, 30
avg = peak / 5 # assume peak is 5x the average
total = avg * 86_400 * days
print(f"requests in {days} days at the average rate: {total:,.0f}")
print(f"error budget (0.1%): {total * (1 - slo):,.0f} failed requests")
print(f"as full-outage time: {days * 24 * 60 * (1 - slo):.1f} minutes")
for k, v in requirements.items():
print(f"{k:<13} {v}")requests in 30 days at the average rate: 2,592,000,000 error budget (0.1%): 2,592,000 failed requests as full-outage time: 43.2 minutes peak load 5,000 requests/s availability 99.9% of requests succeed, per 30 days latency p99 under 300 ms
A real run; the average is assumed to be one fifth of the peak.
A 99.9% target over 30 days allows about 26 lakh failed requests, or 43.2 minutes of complete outage. That budget is what you spend on deployments, incidents and experiments. Each requirement in the table can be turned into a design check in the same way: the peak load sizes the servers, the availability target sizes the redundancy, and the latency target decides where caching is needed.
All chapters · Previous: Core Concepts: RPCs, Consistency, Failures and Time