Courses / System Design Interview / Chapter 4
Module 1 · Foundations · Chapter 4 of 49
Back-of-the-Envelope Estimates
Builds on The System Design Interview: How It Runs and How to Answer and Non-Functional Requirements: Availability, Scale, Latency and More. Next up: Building Blocks: The Parts Every Design Reuses.
Part 1 · Numbers worth knowing
Why estimate at all
A back-of-the-envelope estimate is a quick calculation from stated assumptions, accurate to within a factor of two or ten. Its job is to tell you which design is possible, not to predict the exact load.
Whether one database server is enough, whether a photo store needs terabytes or petabytes, whether a network link can carry the traffic: each answer changes the architecture, and each is settled by arithmetic you can do in a minute. The arithmetic needs a few numbers you carry in your head.
Start with sizes. A kilobyte is about a thousand bytes, a megabyte a million, a gigabyte a billion, a terabyte a thousand billion, and a petabyte a thousand terabytes. Strictly, a binary kilobyte is 2 to the power 10, which is 1,024 bytes, but for estimates the difference of a few percent does not matter. In Indian grouping, a million is ten lakh and a hundred million is ten crore.
Then time. A day has 86,400 seconds, which you can round to 1 lakh (10 to the power 5) for mental arithmetic. A month of 30 days has about 26 lakh seconds, and a year has about 3.15 crore. Dividing a daily count by 1 lakh gives a per-second figure that is within about 15% of the exact one.
| Quantity | Value to remember |
|---|---|
| Seconds in a day | 86,400 (round to 1 lakh for quick sums) |
| Seconds in a 30-day month | about 26 lakh |
| Seconds in a year | about 3.15 crore |
| 1 KB, 1 MB, 1 GB, 1 TB | about 10^3, 10^6, 10^9, 10^12 bytes |
| 2^10, 2^20, 2^30 | 1,024, about a million, about a billion |
The latency ladder
The second set of numbers is how long common operations take. Peter Norvig's page "Teach Yourself Programming in Ten Years" lists approximate timings for a typical PC: fetching from the processor's first-level cache takes about 0.5 nanoseconds, a fetch from main memory about 100 nanoseconds, reading a megabyte sequentially from memory about 250,000 nanoseconds, a disk seek about 8 milliseconds, reading a megabyte sequentially from disk about 20 milliseconds, and a packet from the United States to Europe and back about 150 milliseconds.
Colin Scott's interactive page extends these numbers across years. It lists a round trip inside one data centre as about 500 microseconds, and a round trip between California and the Netherlands as about 150 milliseconds. Hardware improves, so memory, disks and processors have moved since these tables were first drawn. The distances have not: light in fibre still takes time, so the long-distance figure stays put.
What you should keep from the ladder is the ratios. A main-memory fetch is tens of thousands of times faster than a disk seek (100 nanoseconds against 8 milliseconds). A trip across a data centre is thousands of times slower than a memory read. A trip between continents is hundreds of times slower than a trip inside a data centre. Designs follow those ratios: caches keep hot data in memory, and a CDN (content delivery network) keeps copies near users.
The ladder measured on this machine
The snippet measures four rungs here: a dictionary lookup in Python, copying 1 MB into a buffer that already exists, reading a 1 MB file, and a round trip to a server on the same machine over the loopback network. Its last column repeats the published figure for the closest rung.
import os, socket, sys, tempfile, threading, time print("python", sys.version.split()[0]) def per_op(fn, n): t = time.perf_counter() for _ in range(n): fn() return (time.perf_counter() - t) / n * 1e9 # ns per call d = {i: i for i in range(1000)} buf = bytearray(1_000_000) dst = bytearray(1_000_000) path = os.path.join(tempfile.gettempdir(), "est_1mb.bin") with open(path, "wb") as f: f.write(buf) def copy_mb(): dst[:] = buf # copy into a buffer that exists def read_file(): with open(path, "rb") as f: f.read()
srv = socket.socket() srv.bind(("127.0.0.1", 55440)) srv.listen() def echo(): c, _ = srv.accept() while data := c.recv(64): c.sendall(data) threading.Thread(target=echo, daemon=True).start() cli = socket.create_connection(("127.0.0.1", 55440)) def trip(): cli.sendall(b"x") cli.recv(64) rows = [ ("dict lookup", per_op(lambda: d[500], 200000), "memory 100"), ("copy 1 MB in memory", per_op(copy_mb, 200), "250,000"), ("read 1 MB file", per_op(read_file, 200), "20,000,000"), ("localhost round trip", per_op(trip, 5000), "500,000"), ] print(f"{'':<22}{'this machine':>14} published") for name, ns, ref in rows: print(f"{name:<22}{ns:>11,.0f} ns {ref} ns") os.remove(path)
python 3.12.10 this machine published dict lookup 46 ns memory 100 ns copy 1 MB in memory 19,490 ns 250,000 ns read 1 MB file 305,687 ns 20,000,000 ns localhost round trip 43,118 ns 500,000 ns
A real run; every number varies from run to run.
None of these match the table, and none should. The dictionary lookup includes Python's interpreter overhead, so it is far from a bare memory read. Copying 1 MB took about 19.5 microseconds against the published 250: memory bandwidth has grown a great deal since the table was written, and a 1 MB buffer that was just used can still sit in the processor's cache. The file read took about 306 microseconds, not 20 milliseconds, because the file was just written and the operating system served it from memory, not from the disk. The loopback round trip never touches a network card, which is why it is far below the 500 microseconds quoted for a trip within a data centre.
Part 2 · Requests per second, average and peak
From users to requests
The first number most designs need is how many requests per second the system must handle. It is built from three assumptions: how many users act in a day, how many requests each makes, and how much busier the busiest moment is than the average.
The steps are short. Multiply daily users by requests per user to get requests per day. Divide by 86,400 to get the average per second. Multiply by a peak factor to get the peak per second, which is what you design for, because a system that copes with the average but fails at the peak is down when users most want it.
The peak factor is an assumption, and you should say so. Steady services may peak at two or three times their average. A results website, an exam portal, a ticket sale or a live match can peak at tens or hundreds of times, because everyone arrives at the same minute.
A results-day website
Take a university results site. Assume 12 lakh students visit on results day, each causing about five requests (the page, a style file, a script, two data calls). Results go up at 10 am and the visits bunch into the hour or so after that, so the peak is taken as twenty times the day's average.
Design for about: 1,400 /s (then add headroom)
Read it as steps
From 12 lakh students to an average rate and a peak rate for a results website
The scene is the arithmetic of the next snippet, step by step.
The estimator as code
def rps(daily_users, actions_per_user, peak_factor): per_day = daily_users * actions_per_user average = per_day / 86_400 return per_day, average, average * peak_factor # results day: 12 lakh students open the site, 5 requests each; visits # bunch after 10 am, so the peak is assumed to be 20x the average per_day, avg, peak = rps(1_200_000, 5, 20) print(f"requests per day: {per_day:,.0f}") print(f"average: {avg:,.0f} per second") print(f"peak (20x): {peak:,.0f} per second") # check the factor: how long would the day's requests last at the peak? minutes = per_day / peak / 60 print(f"all requests at the peak rate: {minutes:.0f} minutes") rush = per_day / 2 / 600 # if half arrive in the first 10 minutes print(f"half in 10 minutes: {rush:,.0f} per second, {rush / avg:.0f}x")
requests per day: 6,000,000 average: 69 per second peak (20x): 1,389 per second all requests at the peak rate: 72 minutes half in 10 minutes: 5,000 per second, 72x
A real run.
The average is about 69 requests a second, which a single small server could serve. The peak, 1,389 a second, is twenty times higher, and that is the number that decides the number of servers. Rounding for mental arithmetic gives the same picture: 60 lakh requests divided by 1 lakh is 60 a second, and 60 times 20 is 1,200, within 15% of the exact 1,389.
Two refinements are common. First, split reads from writes, because they scale differently: a results site is almost all reads, while a chat app has many writes. Second, check the peak factor against a real source when you have one, such as last year's traffic graph. If you do not, state the factor out loud so that it can be challenged.
The last two lines of the run test the peak factor itself. At 1,389 requests a second, the whole day's 60 lakh requests would be served in 72 minutes. So a factor of 20 describes a rush that lasts a little over an hour. If half the students instead arrive in the first ten minutes, those ten minutes carry 5,000 requests a second, 72 times the average. The factor and the story behind it must agree. If they do not, the story usually wins, because it is the thing you know about the users.
A last check is to turn the answer back into users. 1,389 requests a second at five requests per student means about 278 students starting a visit every second at the peak. That is easy to picture, and it is the kind of figure someone can say is too high or too low.
Part 3 · Storage over time
Items, size, retention and copies
Storage estimates follow one chain: how many items arrive, how big each is, how long you keep them, and how many copies you hold. Multiply the four together.
Each factor hides a decision. The size of an item includes more than the item itself: a photo is stored as an original and as smaller versions for thumbnails. Retention is a product choice: keep forever, keep seven years, keep 30 days. Copies are a reliability choice: a service that stores three copies of each item to survive hardware failure uses three times the space.
Leave out what you cannot estimate and say so. Database indexes, overhead and growth in the number of users all add more, and a real plan includes a margin. In an estimate, the first aim is the right unit: gigabytes, terabytes or petabytes. That tells you whether one machine, a rack or a fleet is involved.
A photo app over five years
Assume a photo app receives 20 lakh uploads a day. Each photo is stored as a 2 MB original plus 150 KB of thumbnails, kept for five years, with three copies of everything.
Total to store: 23.5 PB (before indexes and growth)
Read it as steps
From 20 lakh uploads a day to petabytes of storage with three copies
The next snippet performs the same chain, with a small helper that prints sizes in decimal units.
The calculation, run
def human(n): for unit in ("B", "KB", "MB", "GB", "TB", "PB"): if n < 1000: return f"{n:,.1f} {unit}" n /= 1000 return f"{n:,.1f} EB" uploads_per_day = 2_000_000 # 20 lakh photos a day original, thumbs = 2_000_000, 150_000 # bytes per photo years, replicas = 5, 3 per_photo = original + thumbs per_day = uploads_per_day * per_photo total = per_day * 365 * years print("photos in 5 years:", f"{uploads_per_day * 365 * years:,}") print("per photo:", human(per_photo), "| per day:", human(per_day)) print("stored once:", human(total)) print(f"with {replicas} copies:", human(total * replicas)) # what two changes would save, five years, all copies small = uploads_per_day * (original + 50_000) * 365 * years print("thumbnails at 50 KB saves:", human((total - small) * replicas)) print("2 copies instead of 3 saves:", human(total))
photos in 5 years: 3,650,000,000 per photo: 2.1 MB | per day: 4.3 TB stored once: 7.8 PB with 3 copies: 23.5 PB thumbnails at 50 KB saves: 1.1 PB 2 copies instead of 3 saves: 7.8 PB
A real run. Units are decimal: 1 KB is 1,000 bytes.
The run confirms the scene: 3,650,000,000 photos, which is 365 crore, at 2.15 MB each (printed rounded as 2.1) is 7.8 petabytes stored once and 23.5 petabytes with three copies. That is not a single database. It is a fleet of storage machines, and the number alone tells you the original photos should go to an object store and not a relational table.
The estimate also shows where the money goes. The thumbnails are 150 KB of the 2.15 MB, under 7% of the total. Shrinking originals or keeping fewer copies of old photos saves far more than optimising thumbnails. An estimate points to the part worth optimising.
The last two lines of the run put numbers on it. Cutting thumbnails from 150 KB to 50 KB saves 1.1 petabytes over five years. Keeping two copies instead of three saves 7.8 petabytes, about seven times as much. When you look for savings, start with the factor that multiplies everything.
Growth is the other thing to state. If uploads double every year, the five-year total is far larger than five times the first year. State whether you are assuming flat or growing numbers, and give the total for the case you chose.
Three common ways to cut the total remain. A tier puts old, rarely read data on cheaper, slower storage. Erasure coding, which a later chapter on blob storage covers, splits data into pieces plus a few extra parity pieces, so that lost pieces can be rebuilt. A layout with 10 data pieces and 4 parity pieces stores 1.4 times the data instead of 3 times, and survives the loss of any 4 pieces. Compression helps for text and logs, but photos are usually stored in formats that are already compressed, so it gains little here.
Part 4 · Bandwidth and server counts
From requests to network and machines
Two more estimates follow from the request rate. Bandwidth is how much data per second the network must carry, and the server count is how many machines are needed to serve the peak.
Bandwidth is the peak request rate multiplied by the size of an average response. Networks are quoted in bits per second, while sizes are in bytes, so multiply by eight. Confusing the two is a common slip, and it is off by a factor of eight. Outbound traffic is usually larger than inbound, because requests are small and responses are big, so check the direction that carries the data.
The server count is the peak rate divided by what one server can handle. The per-server figure should come from a load test of your own code. The scalability lesson in the non-functional chapter shows how: it measured requests per second for one worker and for four on this machine. Without a test, pick a figure, say it is assumed, and be ready to change it. Treat it as a guess until a test replaces it with a measurement, and keep the guess conservative: a low figure gives you more servers than you need, while a high one leaves you short.
You can sanity-check a per-server figure with Little's law from the non-functional chapter: requests completed per second equal the requests in progress divided by the time each one takes. A server that works on 16 requests at once and spends 20 ms on each completes about 16 / 0.02 = 800 requests a second. If the same requests take 100 ms because a database call is slow, the same server manages only 160, so a slow dependency cuts capacity as surely as a slower server.
Never plan to run servers at their limit. Keep headroom so that traffic bursts and the loss of one server do not overload the rest. The failover example in the non-functional chapter showed servers pushed to 120% by one failure. The examples in this course plan for 60% of the measured capacity at peak. The right figure depends on how fast you can add servers and how large a burst you expect.
The calculation, run
The snippet takes a peak of 20,000 requests a second, an average response of 50 KB, an assumed capacity of 800 requests a second per server, and 60% utilisation at peak.
import math peak_rps = 20_000 # from the request estimate response = 50_000 # 50 KB average response per_server = 800 # requests/s one server sustains (assumed) headroom = 0.6 # run servers at 60% of that at peak mbps = peak_rps * response * 8 / 1e6 print(f"outbound at peak: {mbps:,.0f} Mbit/s") print(f" = {mbps / 1000:.1f} Gbit/s") usable = per_server * headroom servers = math.ceil(peak_rps / usable) print(f"servers: ceil({peak_rps:,} / {usable:.0f}) = {servers}") print(f"with one spare per 10: {servers + math.ceil(servers / 10)}")
outbound at peak: 8,000 Mbit/s = 8.0 Gbit/s servers: ceil(20,000 / 480) = 42 with one spare per 10: 47
A real run.
The outbound traffic is 8 gigabits a second, eight times what a 1 Gbit/s network port can carry, so it must be spread across many servers and links. Each server is planned to handle 480 requests a second (60% of 800), so 20,000 divided by 480 rounds up to 42 servers. Adding a spare for every ten servers brings it to 47.
The ceil matters. Rounding down leaves the system short, and 41.7 servers does not exist. Always round up capacity.
| Term | Meaning |
|---|---|
| Peak factor | How many times busier the busiest moment is than the average |
| Headroom | Capacity kept unused so that bursts and failures do not cause overload |
| Bandwidth | Data carried per second, quoted in bits |
| Load test | Driving a service with synthetic requests to measure what it can sustain |
For the same 50 KB responses at 20,000 a second, a colleague says a 2 Gbit/s link is enough because the traffic is "1,000 a second". What went wrong?
Part 5 · A worked estimate, end to end
The problem and the assumptions
A complete estimate has four parts: a stated scenario, a list of assumptions, the calculation, and a sanity check. We will estimate a live cricket score service during a one-day international final.
The assumptions, each of which can be challenged: 2 crore viewers have the app open at the same moment; each app asks for the latest score every 10 seconds; one score update is about 1 KB compressed; a CDN answers 99.9% of requests from its edge copies; an origin server can usefully handle 800 requests a second and is run at 60% of that; and a match produces about 600 events of about 1 KB each, one per ball, since a one-day match has up to 50 overs of 6 balls for each side.
Most of the work is choosing these numbers sensibly. The arithmetic afterwards is mechanical. If someone disagrees with the answer, they can change an assumption and see the effect, which is why the list comes first.
The calculation
import math viewers = 20_000_000 # 2 crore watching at the same moment poll_s = 10 # each app asks for the score every 10 s payload = 1_000 # bytes per score update, compressed hit_ratio = 0.999 # share served by the CDN edge per_server = 800 * 0.6 # usable requests/s per origin server balls, event_bytes = 600, 1_000 # events per match, size of each edge_rps = viewers / poll_s gbit = edge_rps * payload * 8 / 1e9 print(f"edge requests: {edge_rps:,.0f} per second") print(f"edge bandwidth: {gbit:,.1f} Gbit/s") for hit in (hit_ratio, 0.99): # the assumption, then a worse one origin = edge_rps * (1 - hit) servers = math.ceil(origin / per_server) rate = f"origin {origin:,.0f}/s" print(f"hit ratio {hit:.1%}: {rate}, {servers} servers") print(f"match data: {balls * event_bytes / 1e3:,.0f} KB per match")
edge requests: 2,000,000 per second edge bandwidth: 16.0 Gbit/s hit ratio 99.9%: origin 2,000/s, 5 servers hit ratio 99.0%: origin 20,000/s, 42 servers match data: 600 KB per match
A real run.
Read the output top to bottom. At the edge there are 20 lakh requests a second, carrying 16 gigabits a second of responses. If every one of those reached the origin, no reasonable fleet could cope. With 99.9% answered from the edge, the origin sees 2,000 requests a second and five servers suffice at 60% utilisation. The next line repeats that with a hit ratio of 99%: the origin load grows tenfold to 20,000 a second and the fleet to 42 servers. The data the match produces is only 600 KB, so storage is not a concern.
The estimate shows where the design must put effort. The score data is tiny and changes only every few seconds, so the design is about distribution: serving the same small answer to millions of phones. The decision it supports is clear. Put a content delivery network in front of the origin and make the response cacheable for a few seconds.
The hit ratio is itself something you can estimate. If the score is cached for one second and served from, say, 200 edge locations, and each location sends a single request to the origin when its copy expires, the origin sees about 200 requests a second however many viewers there are. That is under what even the 99.9% assumption gave. The figure holds only if each edge merges the requests that arrive while its copy is being refreshed; if it does not, every one of those requests reaches the origin. Note also that 16 Gbit/s counts only the 1 KB body. Each response carries headers too, so the real figure is higher.
Checking and common mistakes
A sanity check compares the answer with something you know. Here, 20 lakh requests a second is large but not absurd for 2 crore people watching at once, each polling every 10 seconds. If the answer had been 2,000 crore, you would suspect a slip of units, such as reading a per-minute figure as per-second.
- Mixing bits and bytes. Convert before comparing against a network link.
- Using the average, not the peak. Capacity must cover the busiest moment.
- Forgetting copies. Storage multiplies by the number of replicas.
- False precision. 1,389 requests a second should be spoken as about 1,400. The assumptions are not accurate to four digits.
- Skipping the unit. A bare "20,000" means nothing; write requests per second, or megabytes.
Finish an estimate with a decision: what the number implies for the design. The results site needs a few servers and a cache. The photo app needs an object store. The score service needs a CDN. An estimate that ends without a decision was not needed.
In the run, 99.9% of requests are served at the edge. What changes if the hit ratio is only 99%?
- The origin sees 10 times more: 20,000 requests a second, and the run shows the fleet growing from 5 to 42 servers.
- A small change in the hit ratio is a large change in origin load, so the assumption should be checked.
Why does the estimate end with a design decision?
- A number is only useful if it changes what you build.
- The edge load pointed to a content delivery network, and the match data size ruled out storage as a concern.
All chapters · Previous: Non-Functional Requirements: Availability, Scale, Latency and More