Estimation and Capacity Sizing Questions
Structured back-of-the-envelope estimation for engineering systems: decomposing a system's load into requests per second, storage, bandwidth, memory, connections and machine counts from stated assumptions, turning average load into a provisioned peak with headroom, sizing shards, partitions and nodes, estimating the infrastructure cost those resources imply (storage, egress, requests, compute), using latency and throughput reference numbers, arriving at a defensible order-of-magnitude answer, and sanity-checking it. The fast approximate reasoning probed in system-design and engineering screens. Market sizing, business-impact and general Fermi estimates, project effort and schedule estimation, business-case arithmetic, statistical inference, and the choice of scaling strategy are covered elsewhere.
Roughly how long does it take to read 1 GB sequentially from memory, from an SSD, from a spinning disk and over a 1 Gbps network, and to make a round trip within a data centre versus across a continent? Show how you would use those orders of magnitude to decide whether a design that reads a 1 GB file on every request can meet a 100 ms latency target.
Sample Answer
The idea in plain words
An order of magnitude is a factor of ten. A handful of rough reference numbers (how fast each kind of storage streams data, how long a message takes to cross a data centre or a continent) let you tell in seconds whether a design is plausible or hopeless. The one insight here: streaming 1 GB from an SSD is about 5 times slower than from memory, from a spinning disk about 67 times slower and over a 1 Gbps network about 85 times slower (the table below gives the figures). Memory itself takes 0.100 s for 1 GB, which is exactly the 100 ms target, so each of these ratios is at once "times slower than memory" and "times the budget". A design that moves 1 GB per request against a 100 ms target is only even arithmetically possible from memory, and then with no time left over.
All the figures below are rough orders of magnitude and are assumptions that vary with hardware and year, not measurements of any product. Units are decimal: 1 GB is 109 bytes, and 1 Gbps is 109 bits per second.
Method
- Write each reference rate in bytes per second. A byte is 8 bits, so a network quoted in bits must be divided by 8: 1 Gbps is 125 MB/s before overhead.
- Time to stream data is time=fixed cost before the first byte+sustained ratebytes where the fixed cost is an access time (a disk's seek, the time for the read head to move to the right spot, or a network round trip, a message going there and the reply coming back). With small numbers: reading 1 MB from an SSD takes 0.1 ms+1 MB/(2 GB/s)=0.1+0.5=0.6 ms.
- To judge a design, turn the latency target around: bytes you can move=(budget−other work−fixed cost)×rate
- Compare the data per request with that byte budget, and compare the required rate with what the machine or network offers.
Reference numbers used (assumptions with ranges)
| Medium | Sustained sequential rate | Fixed cost | Plausible range for the rate |
|---|---|---|---|
| Memory (RAM) | 10 GB/s | about 100 ns | 5 to 50 GB/s |
| SSD (NVMe, a fast flash interface; SATA is the older, slower one) | 2 GB/s | about 100 microseconds | 0.5 (older SATA) to 7 GB/s |
| Spinning disk | 150 MB/s | about 10 ms (seek) | 80 to 250 MB/s |
| 1 Gbps network | 125 MB/s line rate (the link's raw signalling speed), 117.7 MB/s after overhead | 0.5 ms in a data centre | fixed by the link |
Optional detail. Every packet carries labels around its data, so about 6 percent of the link carries labels rather than data and the usable rate is 117.7 MB/s instead of 125. The interview shortcut is 1 Gbps divided by 8 equals 125 MB/s, and no conclusion below depends on the difference. For those who want the arithmetic: the overhead is not a guess. A 1500-byte IP packet (1500 bytes is the usual maximum packet size, called the MTU) carries 1448 bytes of TCP data (20 bytes of IP header, 20 of TCP, 12 for TCP timestamps), and on the wire each packet also costs 38 bytes of Ethernet framing (14 header, 4 checksum, 8 preamble, 12 gap between frames), so 1448/1538=0.941 of the line rate is data.
Round trips: inside one data centre assume about 0.5 ms (range 0.1 to 1 ms). A round trip is a message going to the other side and the reply coming back. Across a continent, light in fibre travels about 200,000 km/s, so for an assumed 4,000 km (about the span of a large continent) the physical floor for a round trip is 2×4000/200,000=0.040 s, 40 ms. Real routes are longer than a straight line and pass through equipment, so assume 1.5 times that, 60 ms (range 40 to 100 ms).
Worked example, computed by a program
The program prints how long 1 GB takes on each medium, how much data fits in the budget after reserving 20 ms for the request's other work (an assumption), the round-trip counts, and a cross-check of each time against a hand-worked value.
# Rough orders of magnitude; real values vary by hardware and year.
GB = 1e9 # decimal gigabyte, in bytes
budget_s = 0.100 # given latency target
work_s = 0.020 # assumption: time reserved for parsing, computing, responding
media = { # name: (sustained sequential bytes/s, fixed cost before first byte in seconds)
"memory (RAM)": (10 * GB, 0.0000001), # assumption 10 GB/s (range 5 to 50), ~100 ns access
"SSD (NVMe)": (2 * GB, 0.0001), # assumption 2 GB/s (SATA ~0.5; range 0.5 to 7), ~100 us
"spinning disk": (0.150 * GB, 0.010), # assumption 150 MB/s (range 80 to 250), ~10 ms seek
}
payload = 1500 - 20 - 20 - 12 # TCP data in a 1500-byte IP packet (IP 20, TCP 20, TCP timestamps 12)
wire = 1500 + 14 + 4 + 8 + 12 # packet + Ethernet header, FCS, preamble, inter-frame gap
efficiency = payload / wire
net_bytes_s = 1e9 / 8 * efficiency # 1 Gbit/s line rate, decimal
media["1 Gbps network"] = (net_bytes_s, 0.0005) # + 0.5 ms in-data-centre round trip
print(f"1500-byte-MTU wire efficiency: {efficiency:.3f} -> {net_bytes_s/1e6:.1f} MB/s")
print(f"{'medium':<16}{'1 GB takes (s)':>15}{'x budget':>10}{'MB readable in budget minus work':>34}")
for name, (bw, fixed) in media.items():
t = GB / bw + fixed
fits = max(0.0, budget_s - work_s - fixed) * bw / 1e6
print(f"{name:<16}{t:>15.3f}{t/budget_s:>10.1f}{fits:>34.1f}")
rtt_dc = 0.0005
km, fibre_km_s, path_factor = 4000, 200_000, 1.5 # assumptions: distance, light speed in glass, route inflation
rtt_min = 2 * km / fibre_km_s
rtt_cont = rtt_min * path_factor
print(f"round trip in data centre: {rtt_dc*1e3:.1f} ms; across continent: >= {rtt_min*1e3:.0f} ms (physics), ~{rtt_cont*1e3:.0f} ms (x{path_factor} route)")
print(f"sequential round trips inside {budget_s*1e3:.0f} ms: data centre {int(budget_s//rtt_dc)}, continent {int(budget_s//rtt_cont)}")
print("bandwidth needed if every request reads 1 GB inside the budget:")
need_gb_s = GB / budget_s / GB
rate = 10
print(f" one request: {need_gb_s:.0f} GB/s = {need_gb_s*8:.0f} Gbit/s; at {rate} requests/s the service reads {rate*GB/1e9:.0f} GB/s in total")
# Hand-worked expected times: 1 GB / rate + fixed cost
expected = {"memory (RAM)": 0.100, "SSD (NVMe)": 0.500, "spinning disk": 6.677, "1 Gbps network": 8.498}
ok = all(abs(GB / bw + fixed - expected[name]) < 0.0005 for name, (bw, fixed) in media.items())
# Network again by a different route: 8e9 bits at (1e9 bit/s x efficiency), plus the round trip
ok = ok and abs(8e9 / (1e9 * efficiency) + rtt_dc - expected["1 Gbps network"]) < 0.0005
print("check (hand-worked times, network via bits):", "PASS" if ok else "FAIL")
Output:
1500-byte-MTU wire efficiency: 0.941 -> 117.7 MB/s
medium 1 GB takes (s) x budget MB readable in budget minus work
memory (RAM) 0.100 1.0 800.0
SSD (NVMe) 0.500 5.0 159.8
spinning disk 6.677 66.8 10.5
1 Gbps network 8.498 85.0 9.4
round trip in data centre: 0.5 ms; across continent: >= 40 ms (physics), ~60 ms (x1.5 route)
sequential round trips inside 100 ms: data centre 200, continent 1
bandwidth needed if every request reads 1 GB inside the budget:
one request: 10 GB/s = 80 Gbit/s; at 10 requests/s the service reads 10 GB/s in total
check (hand-worked times, network via bits): PASS
Reading the output:
- 1 GB sequentially. Memory 0.100 s, SSD 0.500 s, spinning disk 6.677 s (6.667 s of streaming plus the 10 ms seek), a 1 Gbps network 8.498 s. Against the 100 ms target that is 1.0, 5.0, 66.8 and 85.0 times the budget. (Ignoring protocol overhead the network figure would be the round 8.0 s.)
- Round trips. A data-centre round trip is 0.5 ms and a continental one 60 ms, a factor of 120. Inside 100 ms a design can make 200 sequential round trips within a data centre but only 1 across a continent, which is why chatty cross-continent protocols feel slow regardless of bandwidth.
Can reading 1 GB per request meet 100 ms?
No, and the numbers show it in three steps.
- Required rate. Moving 1 GB in 100 ms needs 1 GB/0.1 s=10 GB/s, which is 80 Gbit/s, for every single request.
- Compare with each medium. Only memory reaches 10 GB/s, and its 0.100 s consumes the entire budget with nothing left for the work itself. Reserving 20 ms for that work, the data readable inside the budget is 800 MB from memory, 159.8 MB from SSD, 10.5 MB from spinning disk and 9.4 MB over the network, so no medium carries a full 1 GB once the work is paid for, and memory alone does so only if the work takes no time. SSD falls short by a factor of about 6 (1000/159.8), spinning disk by about 95 (1000/10.5) and the network by about 106 (1000/9.4).
- Add load. Even from memory, at 10 requests per second the service streams 10 GB/s in total, which is all of the assumed memory bandwidth. Queueing would push real latency far over 100 ms well before that.
The judgment
Reject the per-request 1 GB read and change the design so each request touches only the bytes it needs. Practical moves, in the order to try them:
- Index and range reads. Keep a small index (a lookup table from key to position in the file) and read only the few kilobytes or megabytes a request needs (a range read: a request for just one byte range of a file). A 5 MB read over the network takes about 43 ms (5/117.7 s of streaming plus 0.5 ms), which fits with the 20 ms reserved for other work; a 1 MB read takes about 9 ms.
- Keep the hot data in memory once, shared by all requests (for example memory-mapped, meaning the file is presented to the program as if it were memory, so the operating system keeps it in its page cache, its own in-memory copy of recently read file contents), instead of reading it again per request.
- Move the computation to the data where the data lives, so a request ships a result rather than the file.
- Keep the call chain local. If requests must cross a continent, budget at most one sequential round trip and put data replicas near users.
What would flip the answer: a machine with far higher memory bandwidth (the range goes to 50 GB/s), a precomputed answer that makes the read unnecessary, or a looser target (a few seconds permits streaming from SSD).
Common mistakes
- Mixing bits and bytes: a 1 Gbps link moves 125 MB/s, not 1 GB/s.
- Quoting memory speed and ignoring that nothing is left for the actual work.
- Treating latency (time to the first byte) and throughput (bytes per second) as one number: a spinning disk's 10 ms seek matters for small reads and almost vanishes for 1 GB.
- Ignoring that many requests share the same memory, disk or link, so the totals are what saturate.
- Using a continental round trip as if it were the data-centre figure.
Running the code
Python 3.12, standard library only.
python latency_budget.py
You are asked to size a URL shortener before designing it: 100 million new short links a month and a read-to-write ratio of 100 to 1. Estimate the write and read requests per second at average and at peak, and the storage needed for five years of links. State every assumption and sanity-check the result.
Sample Answer
The idea in plain words
Sizing means turning a few stated numbers into the three quantities that shape a design: how many requests per second (RPS, requests arriving each second) the system must handle, how much data it must store, and how big the gap is between a normal moment and a peak. The one insight for a URL shortener is that it is a read-heavy system with a tiny write rate: 100 million new links a month sounds large, but it is only a few dozen writes per second, while the reads (people following a short link, which the service answers with a redirect) are 100 times more frequent and set the load on the serving path. Storage is the other half: each link is a small row, so even five years of links is a few terabytes.
Every input below is an assumption, labelled with a plausible range. None of it is a statistic about a real service.
Method, in the order you would do it
- Fix the time unit. A month is assumed to be 30 days, so it has 30×86,400=2,592,000 seconds (a day has 86,400 seconds). The calendar mean of 30.4 days changes every rate by about 1.3 percent, which is far below the uncertainty of the other inputs.
- Average write rate. writes per second=seconds per monthnew links per month
- Average read rate. The 100 to 1 ratio is read requests per write request, so reads per second=100×writes per second
- Peak rate. Traffic is not flat. The peak-to-average ratio (how much busier the busiest moment is than the mean) is an assumption: 3 here, with a range of 2 to 10 depending on how spiky the traffic is. peak=peak-to-average ratio×average
- Storage. bytes=links stored×bytes per record×copies kept where links stored is 100M×12×5 and copies kept is the replication factor (how many copies of each row are stored for durability).
- Sanity-check against a size that can be checked independently: the number of distinct short codes available, the bandwidth the reads imply, and what a single machine can hold.
Assumptions
| Input | Value | Plausible range | Note |
|---|---|---|---|
| New links per month | 100 million | given | |
| Read requests per write | 100 | given | redirects per link creation |
| Days per month | 30 | 30 to 30.4 | |
| Peak-to-average ratio | 3 | 2 to 10 | applied to reads and writes alike |
| Years retained | 5 | given | no expiry or deletion assumed |
| Bytes per record | 500 | 200 to 1000 | 7-character code, long URL (often 100 bytes or more), timestamps, owner id, index overhead |
| Copies kept | 3 | 2 to 3 | one primary plus two replicas (the primary is the copy of the database that accepts writes; replicas are copies of it that serve reads and keep the data if a machine is lost) |
| Short-code length | 7 | 6 to 8 | characters from a 62-symbol alphabet (a to z, A to Z, 0 to 9), which is what "base62" means: each character carries one of 62 values |
All sizes use decimal units: 1 TB is 1012 bytes.
Worked example, computed by a program
The program prints every intermediate quantity and a sensitivity table, then recomputes the average and peak rates, the link count and the storage (one copy and replicated) by a different route (links per day, exact fractions) and prints PASS or FAIL.
from fractions import Fraction
# Assumptions (ranges in comments)
new_links_per_month = 100_000_000 # given
read_write_ratio = 100 # given: 100 read requests per write request
days_per_month = 30 # assumption: 30 (30.4 is the calendar mean)
peak_multiple = 3 # assumption: peak = 3 x average (range 2 to 10)
years = 5 # given
bytes_per_record = 500 # assumption: code + long URL + timestamps + owner + index overhead (range 200 to 1000)
replicas = 3 # assumption: copies kept for durability (range 2 to 3)
code_len = 7 # assumption: base62 short code length
seconds_per_month = days_per_month * 86_400
write_avg = new_links_per_month / seconds_per_month
read_avg = write_avg * read_write_ratio
write_peak = write_avg * peak_multiple
read_peak = read_avg * peak_multiple
links_total = new_links_per_month * 12 * years
storage_bytes = links_total * bytes_per_record
storage_tb = storage_bytes / 1e12
stored_tb = storage_tb * replicas
keyspace = 62 ** code_len
print(f"seconds per month : {seconds_per_month:,}")
print(f"writes/s avg, peak : {write_avg:.1f}, {write_peak:.1f}")
print(f"reads/s avg, peak : {read_avg:,.0f}, {read_peak:,.0f}")
print(f"links in {years} years : {links_total:,}")
print(f"data (1 copy), TB : {storage_tb:.2f}")
print(f"data x{replicas} replicas, TB : {stored_tb:.2f}")
print(f"base62^{code_len} keyspace : {keyspace:,} used {100*links_total/keyspace:.3f}%")
print("sensitivity of stored TB (x3 replicas) to bytes per record:")
for b in (200, 500, 1000):
print(f" {b:>4} B/record -> {links_total*b*replicas/1e12:.1f} TB")
print("sensitivity of peak reads/s to peak multiple:")
for m in (2, 3, 10):
print(f" x{m:<2} -> {read_avg*m:,.0f}")
# Independent recomputation with exact fractions, via a per-day route
per_day = Fraction(new_links_per_month, days_per_month)
write_avg_b = per_day / 86_400
write_peak_b = write_avg_b * peak_multiple
read_avg_b = write_avg_b * read_write_ratio
read_peak_b = read_avg_b * peak_multiple
links_b = per_day * days_per_month * 12 * years
tb_b = links_b * bytes_per_record / Fraction(10**12)
ok = (abs(float(write_avg_b) - write_avg) < 1e-9
and abs(float(write_peak_b) - write_peak) < 1e-9
and abs(float(read_avg_b) - read_avg) < 1e-6
and abs(float(read_peak_b) - read_peak) < 1e-6
and links_b == links_total
and abs(float(tb_b) - storage_tb) < 1e-9
and abs(float(tb_b * replicas) - stored_tb) < 1e-9)
print("check (per-day route, exact fractions):", "PASS" if ok else "FAIL")
Output:
seconds per month : 2,592,000
writes/s avg, peak : 38.6, 115.7
reads/s avg, peak : 3,858, 11,574
links in 5 years : 6,000,000,000
data (1 copy), TB : 3.00
data x3 replicas, TB : 9.00
base62^7 keyspace : 3,521,614,606,208 used 0.170%
sensitivity of stored TB (x3 replicas) to bytes per record:
200 B/record -> 3.6 TB
500 B/record -> 9.0 TB
1000 B/record -> 18.0 TB
sensitivity of peak reads/s to peak multiple:
x2 -> 7,716
x3 -> 11,574
x10 -> 38,580
check (per-day route, exact fractions): PASS
Reading the output:
- Writes: 100,000,000 / 2,592,000 is 38.6 per second on average and 115.7 at the assumed peak of 3 times average.
- Reads: 100 times that, 3,858 per second on average and 11,574 at peak.
- Storage: 100M links a month for 60 months is 6,000,000,000 links. At 500 bytes each that is 3.00 TB for one copy and 9.00 TB with three copies.
Sanity checks
- Is 6 billion links possible with 7 characters? Seven symbols from a 62-symbol alphabet give 627=3,521,614,606,208 codes, so five years of links use 0.170 percent of the space. Six characters (626≈5.7×1010) would also fit, with about 10.6 percent of the space used.
- Is the read bandwidth sane? A redirect response is small. At an assumed 500 bytes: 11,574×500=5,787,000 bytes per second, which is about 5.8 MB/s or 46 Mbit/s (megabits, millions of bits, per second; multiply bytes by 8 to get bits). That is trivial for one network interface.
- Does the data fit on one machine? 3 TB for one copy fits on a single modern server's SSD storage, so storage alone does not force sharding (splitting data across machines by key). Replicas exist for durability and read capacity, not because the data is too big.
- Cache effect. The cache hit ratio is the share of requests answered from the cache (a fast in-memory copy of hot links). If an assumed 80 percent of redirects are hits, the database sees the other 20 percent of the peak: 0.2×11,574≈2,315 reads per second.
The judgment
The numbers say this service is easy to size and the design risk is elsewhere. Write capacity (about 116 per second at peak) is not a constraint for a single primary database (the copy that takes the writes). The read path (about 11,600 per second at peak) is best served from a cache in front of a replicated store, so the database tier sees a small fraction of it. Storage of roughly 3 TB (9 TB with three copies) is the number to plan disks around.
What changes the conclusion:
- A 10 times peak instead of 3 times raises peak reads to 38,580 per second (see the sensitivity lines) and makes the cache hit ratio (the share of reads the cache answers) the thing to design, not the database.
- Per-click analytics. If every redirect also writes a 100 byte analytics event, that adds 3,858×100 B≈385,800 bytes per second, about 33.3 GB per day (385,802 bytes per second times 86,400), which would dominate the link table over time. That is a separate store with different needs.
- Larger records (long URLs, tracking parameters) move storage linearly: 200 to 1000 bytes per record gives 3.6 to 18.0 TB with three copies.
Common mistakes
- Using 365 times 24 times 60 times 60 for a month, or dividing by seconds per day instead of seconds per month.
- Applying the 100 to 1 ratio to the wrong base: reads per second are 100 times writes per second (3,858 against 38.6 on average), not 100 times the 6 billion links stored.
- Quoting the average as if it were the peak, or the peak as if it were the average.
- Forgetting replication, or mixing TB and TiB (1 TiB, the binary terabyte of 10244 bytes, is 1.0995 TB) without saying which.
- Stopping at the arithmetic with no sanity check against the code space or one machine's capacity.
Running the code
Python 3.12, standard library only.
python url_shortener_sizing.py
Your service averages 2,000 requests per second over a day. Walk through how you would estimate the peak you must provision for, using the daily traffic curve, weekly and seasonal patterns and a launch-day spike, and turn that peak into a server count when one server handles 400 requests per second at the target latency.
Sample Answer
The idea in plain words
The average (2,000 requests per second, RPS) is not what you provision for. Servers must survive the busiest minute you expect, and that minute is the daily average multiplied by several independent effects: the shape of the day (the diurnal curve), the busiest day of the week, the busiest season, and a one-off launch. Each effect is a multiplier. You estimate each one, multiply them for the scenarios that can really coincide, then divide the resulting peak by what one server can sustain, and add headroom so a failure does not take you under.
Terms used below: the peak-to-average ratio is the busiest moment divided by the mean; headroom is capacity you keep unused on purpose; a zone is an independent failure domain (a data centre or a section of one); autoscaling adds servers automatically when load rises, but a new server takes minutes to start and warm up.
Method, in the order to do it
- Pin down what the 2,000 means. Is it the mean over 24 hours of a typical day, of a typical week, or of last Tuesday? Here it is taken as the mean over a typical week. If it was measured on a quiet day, every multiplier below is applied to the wrong base.
- Get the daily shape. With metrics available, take hourly request counts for four to eight weeks, divide each hour by that day's mean, and read the curve. Without data, assume a smooth curve. Here the multiplier for hour h is
where a is the swing (an assumption, plausible range 0.3 to 0.9) and hpeak is the busiest hour. The 24 cosine values add to zero, so m averages exactly 1 and the daily mean stays 2,000. With a=0.6 the evening peak hour runs at 1.6 times the mean and the overnight trough at 0.4. The formula draws a smooth wave that is highest at hpeak and lowest 12 hours later. With hpeak=20 (20:00) and a=0.6 it gives:
| Clock hour | 02:00 | 05:00 | 08:00 | 11:00 | 14:00 | 17:00 | 20:00 | 23:00 |
|---|---|---|---|---|---|---|---|---|
| m(h) | 1.00 | 0.58 | 0.40 | 0.58 | 1.00 | 1.42 | 1.60 | 1.42 |
For example at 14:00 the angle is 2π×(−6)/24=−π/2, whose cosine is 0, so m=1; at 08:00 it is −π, cosine −1, so m=1−0.6=0.4.
3. Add the minute-level burst. Hourly counts hide the busiest minute. Assume the busiest minute is 1.15 times its hour (range 1.05 to 1.5; measure it from minute-level data if you have it).
4. Layer the calendar. Assume the busiest weekday is 1.15 times the weekly average (range 1.05 to 1.3) and the busiest season is 1.3 times a normal week (range 1.1 to 2.0). All of these are assumptions to be replaced by your own history.
5. Treat the launch separately. A launch is a planned, short event. Assume it multiplies the traffic of the hour it lands in by 2 (range 1.5 to 5). It raises the fleet only when the launch hour, doubled, exceeds the ordinary busiest hour: 2m(h)>m(hpeak), which here means m(h)>0.8. On this curve that is every hour from 13:00 through 03:00 (so a launch at 14:00 still raises the peak, and a launch at 20:00 raises it most); a launch from 04:00 through 12:00 does not. Its timing is a decision, not a fact.
6. Combine and convert to servers. The peak is
and the fleet is
N=⌈cuRpeak⌉,Ntotal=⌈N⋅Z−1Z⌉The brackets ⌈x⌉ mean round up to the next whole number, because you cannot run 13.2 servers. The factor Z/(Z−1) comes from losing one zone: with Z=3 zones, the two surviving zones must carry all of the load, so each zone must be able to hold half of the base count N, and the total is 3×N/2=1.5N. For N=14 that is 21 servers, 7 per zone, and after losing a zone the remaining 14 still cover the peak.
Here rˉ=2000, c=400 RPS per server (given, at the target latency), u=0.8 is the share of that figure you plan to use (an assumption, range 0.6 to 0.9, for uneven load balancing and deploys), and Z=3 zones, so that losing one zone leaves N servers running. The burst factor corrects for coarse time buckets and u corrects for imperfect server behaviour, so they are different effects and are not double counting.
Worked example by hand
- Normal weekday peak: 2000×1.6=3200, then 3200×1.15=3680 (weekday), then 3680×1.15=4232 (burst). Servers: 4232/(400×0.8)=4232/320=13.2, so 14. With a zone lost: 14×3/2=21.
- Seasonal peak: 4232×1.3=5501.6, call it 5,502 RPS. Servers: 5502/320=17.2, so 18, and 18×1.5=27.
- Launch in the evening peak hour during the season: 5501.6×2=11003.2, so 11,003 RPS. Servers: 11003/320=34.4, so 35, and 35×1.5=52.5, so 53.
- Launch at 10:00 instead: the curve at 10:00 is 1+0.6cos(2π⋅(−10)/24)=0.48, and 0.48×2=0.96, below the evening's 1.6, so the launch hour is not the busiest hour and the fleet stays at the seasonal-peak size.
- Launch at 14:00 instead: the curve is 1.0, doubled it is 2.0, above the evening's 1.6, so the peak becomes 2000×2.0×1.15×1.3×1.15=6877 RPS. Servers: 6877/320=21.5, so 22, and 22×1.5=33. Moving a launch off the evening peak helps, but only a launch in the morning window (04:00 to 12:00) leaves the fleet unchanged.
The program below does the same with every input visible, checks that the curve averages 1.0 (the check fails if a constant is added to the curve, which would silently change the daily mean), prints which launch hours raise the peak, recomputes the seasonal row by direct multiplication, and varies one input at a time.
import math
# ---- Assumptions (each with a plausible range) ----
MEAN_RPS = 2000 # given: daily average, taken as a typical-week day
AMPLITUDE = 0.6 # diurnal swing around the mean, range 0.3 to 0.9
PEAK_HOUR = 20 # busiest hour of the day (local evening), range 12 to 22
BURST = 1.15 # busiest minute vs its hour average, range 1.05 to 1.5
WEEKLY = 1.15 # busiest weekday vs weekly average, range 1.05 to 1.3
SEASON = 1.30 # busiest season vs normal weeks, range 1.1 to 2.0
LAUNCH = 2.0 # launch hour traffic vs a normal hour, range 1.5 to 5
CAP_PER_SERVER = 400 # given: requests/s one server handles at target latency
UTIL = 0.80 # run servers at no more than 80% of that figure, range 0.6 to 0.9
ZONES = 3 # servers spread over 3 zones, survive losing one
def curve(h, amp=AMPLITUDE):
return 1 + amp * math.cos(2 * math.pi * (h - PEAK_HOUR) / 24)
def servers(rps, cap=CAP_PER_SERVER, util=UTIL):
need = math.ceil(rps / (cap * util)) # servers if every zone is healthy
total = math.ceil(need * ZONES / (ZONES - 1)) # enough left after losing one zone
return need, total
def peak_rps(amp=AMPLITUDE, weekly=WEEKLY, season=1.0, launch=1.0, launch_hour=PEAK_HOUR):
best = 0.0
for h in range(24):
m = curve(h, amp) * (launch if h == launch_hour else 1.0)
best = max(best, MEAN_RPS * m * weekly * season * BURST)
return best
# Check 1: the curve must average 1.0 or the daily mean is not 2000
mean_mult = sum(curve(h) for h in range(24)) / 24
assert abs(mean_mult - 1.0) < 1e-9, mean_mult
print(f"curve mean={mean_mult:.3f} min={min(curve(h) for h in range(24)):.2f} max={max(curve(h) for h in range(24)):.2f}")
scen = [
("normal weekday peak", peak_rps()),
("seasonal peak", peak_rps(season=SEASON)),
("launch at evening peak in season", peak_rps(season=SEASON, launch=LAUNCH)),
("launch at 10:00 in season", peak_rps(season=SEASON, launch=LAUNCH, launch_hour=10)),
("launch at 14:00 in season", peak_rps(season=SEASON, launch=LAUNCH, launch_hour=14)),
]
print(f"{'scenario':36s}{'peak rps':>10s}{'x mean':>8s}{'servers':>9s}{'with 1 zone lost':>18s}")
for name, r in scen:
need, total = servers(r)
print(f"{name:36s}{r:10.0f}{r/MEAN_RPS:8.2f}{need:9d}{total:18d}")
# A launch raises the fleet only if the launch hour, doubled, beats the ordinary busiest hour
raising = [h for h in range(24) if LAUNCH * curve(h) > curve(PEAK_HOUR)]
print("launch hours that raise the peak:", " ".join(f"{h:02d}" for h in raising))
# Check 2: independent recomputation of the seasonal-peak row, straight multiplication
direct = MEAN_RPS * (1 + AMPLITUDE) * WEEKLY * SEASON * BURST
assert abs(direct - scen[1][1]) < 1e-6, (direct, scen[1][1])
need = math.ceil(direct / (400 * 0.8)); total = math.ceil(need * 3 / 2)
assert (need, total) == servers(scen[1][1])
print(f"check: direct product {direct:.0f} rps, {need} servers, {total} with a zone lost")
# Sensitivity: change one input at a time on the launch-at-peak scenario
print("sensitivity (launch at evening peak in season), servers with a zone lost:")
base = servers(scen[2][1])[1]
tests = [
("amplitude 0.3 / 0.9", lambda: [servers(peak_rps(amp=a, season=SEASON, launch=LAUNCH))[1] for a in (0.3, 0.9)]),
("weekly 1.05 / 1.30", lambda: [servers(peak_rps(weekly=w, season=SEASON, launch=LAUNCH))[1] for w in (1.05, 1.30)]),
("season 1.1 / 2.0", lambda: [servers(peak_rps(season=s, launch=LAUNCH))[1] for s in (1.1, 2.0)]),
("launch 1.5 / 5", lambda: [servers(peak_rps(season=SEASON, launch=l))[1] for l in (1.5, 5)]),
("per-server rps 300 / 500", lambda: [servers(scen[2][1], cap=c)[1] for c in (300, 500)]),
]
print(f" base case: {base}")
for label, f in tests:
lo, hi = f()
print(f" {label:26s} -> {lo} / {hi}")
Output:
curve mean=1.000 min=0.40 max=1.60
scenario peak rps x mean servers with 1 zone lost
normal weekday peak 4232 2.12 14 21
seasonal peak 5502 2.75 18 27
launch at evening peak in season 11003 5.50 35 53
launch at 10:00 in season 5502 2.75 18 27
launch at 14:00 in season 6877 3.44 22 33
launch hours that raise the peak: 00 01 02 03 13 14 15 16 17 18 19 20 21 22 23
check: direct product 5502 rps, 18 servers, 27 with a zone lost
sensitivity (launch at evening peak in season), servers with a zone lost:
base case: 53
amplitude 0.3 / 0.9 -> 42 / 62
weekly 1.05 / 1.30 -> 48 / 59
season 1.1 / 2.0 -> 45 / 80
launch 1.5 / 5 -> 39 / 129
per-server rps 300 / 500 -> 69 / 42
Computed with Python 3.12 (standard library only).
What to recommend
Commit to this plan under the stated assumptions:
- Permanent fleet: 27 servers, sized for the seasonal peak with one zone lost. The normal-day peak needs only 21, so about six servers sit idle outside the season; that is the price of surviving the season and a zone failure together. Whether to buy that or to add servers when the season starts is a cost question; the season is predictable, so scheduled scale-up a few days ahead is the cheaper option.
- Launch: schedule it in the morning window and pre-scale anyway (add servers before the expected spike instead of reacting to it). Between 04:00 and 12:00 the doubled curve stays under the evening peak, so at 10:00 the model says 27 servers still cover it; a launch at 14:00 would need 33. But the 2x applies to a whole hour; a launch can front-load a spike (put most of the hour's extra traffic into its first minutes), which a model built on hourly means understates. If it must coincide with the evening peak, 53 servers are needed for the launch window only (35 servers, or 53 with a zone lost, against the 18 and 27 of the seasonal peak). Autoscaling cannot fill that gap on its own because a spike arrives in seconds and a new server takes minutes to start and warm up (load its code and fill its caches before it runs at full speed), so add the servers before the announcement and remove them afterwards.
- Validate the 400 per server figure with a load test at the target latency (state which percentile, such as the 99th: the latency that 99 percent of requests beat). The whole result moves with it: 300 per server gives 69 and 500 gives 42 in the sensitivity block.
The sensitivity block shows which assumption deserves the effort. With the launch landing at the peak, the launch multiplier moves the answer from 39 to 129 servers (a spread of 90) and the season factor from 45 to 80 (a spread of 35). The amplitude (42 to 62, a spread of 20) and the weekday factor (48 to 59, a spread of 11) move it less, and the per-server figure (42 to 69, a spread of 27) matters almost as much as the season, which is why it gets a load test. Spend the research time on the launch size, the season and the per-server capacity, not on the third digit of the daily curve.
What would change the plan: a measured daily curve that is flatter or sharper than the cosine; a user base spread over time zones, which flattens the curve because each region peaks at a different clock hour; a growth rate (provisioning for next quarter means multiplying everything by expected growth); a launch size taken from marketing's forecast rather than guessed.
Common mistakes
- Dividing the average by 400 (2000 / 400 = 5 servers) and stopping.
- Multiplying every worst case together without asking whether they coincide: launch, season, weekday and evening all at once is a stress scenario, not the expected peak, and the plan above treats it as a temporary one.
- Forgetting the burst and headroom, so the fleet runs at its limit at the busiest minute and the target latency is missed.
- Forgetting that failures remove capacity: a fleet sized exactly for peak has no room for losing a server or a zone.
- Using the average of a quiet period as the base.
Running the code
python peak.py
Save the program as peak.py. It needs only the Python 3.12 standard library (math) and no input files.
Estimate the annual storage and bandwidth cost for a global image service with 100M monthly active users, about 500 photos per user, an average original of 2MB, 3x replication, and thumbnails totalling 10% of the original size. Storage costs $0.02 per GB-month and egress to the CDN is $0.08 per GB. Show your calculations, tell me which assumptions matter most, and where you would look for savings.
Sample Answer
The idea in plain words
Two bills drive this: storage (paying every month to keep bytes on disk) and egress (paying for bytes that leave the storage system, here the bytes the content delivery network, CDN, pulls from your origin store when its cache does not already have a photo; the origin store is the main storage system that holds the master copies, and the CDN is a network of servers near users that keeps copies of popular files). The method is to count photos, multiply by bytes per photo, multiply by copies, then multiply by price. Storage grows with everything you ever keep, while egress only grows with what people look at and the CDN cannot serve from its cache. With these inputs the answer is lopsided: storage is about 99% of the cost.
Units used throughout: decimal, 1 GB = 1,000 MB and 1 PB (petabyte) = 1,000,000 GB. Binary units (GiB, the gibibyte, 1,024 x 1,024 x 1,024 bytes, about 7% larger than a decimal GB) would change the totals by a few percent.
Method
- Photos: 100M monthly active users (MAU) x 500 photos = 50 billion photos. This treats 500 as the average per MAU and ignores photos of inactive users (an assumption).
- Bytes per photo per copy: the 2 MB original plus thumbnails totalling 10% of it (0.2 MB) = 2.2 MB.
- Copies: replication factor 3 (every byte stored three times), applied to thumbnails too (an assumption).
- Storage cost:
- Egress cost: only bytes crossing from origin to CDN are billed at USD 0.08 per GB, and the question gives no viewing behaviour, so these are assumptions: each MAU views 600 thumbnails a month (each about 50 KB, since a photo's thumbnails total 0.2 MB across several sizes) and 15 full-size originals a month, and the CDN cache serves 90% of delivered bytes so only 10% reaches the origin (that 90% is the CDN hit ratio: the share of delivered bytes answered from cache without touching the origin store).
Worked example
- Logical data: 50×109×2.2 MB=110 PB.
- With 3 copies: 330 PB, which is 330×106 GB. At USD 0.02 per GB-month that is USD 6.6 million a month, USD 79.2 million a year.
- Delivered per MAU per month: 600×0.05+15×2=60 MB. Across 100M MAU that is 6 PB a month, 72 PB a year.
- Origin to CDN: 10% of 72 PB = 7.2 PB = 7.2×106 GB, times USD 0.08 = USD 576,000 a year.
The program recomputes the whole chain and varies the inputs one at a time.
# Annual storage and CDN-origin egress cost. Decimal units: 1 GB = 1,000 MB, 1 PB = 1,000,000 GB.
MAU = 100_000_000 # given
PHOTOS_PER_USER = 500 # given
ORIGINAL_MB = 2.0 # given
THUMB_FRACTION = 0.10 # given: thumbnails total 10% of the original size, per photo
REPLICAS = 3 # given; assumed to apply to thumbnails too
STORAGE_USD_GB_MONTH = 0.02 # given
EGRESS_USD_GB = 0.08 # given: origin to CDN
# assumptions below (not given)
THUMB_VIEWS = 600 # thumbnail views per MAU per month (plausible 200 to 2,000)
THUMB_SERVED_MB = 0.05 # one served thumbnail, about 50 KB (a photo's thumbnails total 0.2 MB)
FULL_VIEWS = 15 # full-size views per MAU per month (plausible 5 to 50)
CDN_HIT = 0.90 # share of delivered bytes served from CDN cache (plausible 0.5 to 0.97)
def costs(photos_per_user=PHOTOS_PER_USER, replicas=REPLICAS, hit=CDN_HIT,
thumb_views=THUMB_VIEWS, full_views=FULL_VIEWS):
photos = MAU * photos_per_user
per_photo_mb = ORIGINAL_MB * (1 + THUMB_FRACTION)
logical_gb = photos * per_photo_mb / 1000
stored_gb = logical_gb * replicas
storage_year = stored_gb * STORAGE_USD_GB_MONTH * 12
delivered_gb = MAU * (thumb_views * THUMB_SERVED_MB + full_views * ORIGINAL_MB) / 1000 * 12 # per year
origin_gb = delivered_gb * (1 - hit)
egress_year = origin_gb * EGRESS_USD_GB
return photos, logical_gb, stored_gb, storage_year, delivered_gb, origin_gb, egress_year
photos, logical, stored, st_cost, deliv, origin, eg_cost = costs()
print(f"photos stored : {photos:,.0f}")
print(f"logical size (PB) : {logical/1e6:,.1f}")
print(f"stored with 3x (PB) : {stored/1e6:,.1f}")
print(f"storage cost per year : USD {st_cost:,.0f}")
print(f"delivered per year (PB): {deliv/1e6:,.1f}")
print(f"origin to CDN (PB/yr) : {origin/1e6:,.2f}")
print(f"egress cost per year : USD {eg_cost:,.0f}")
print(f"total per year : USD {st_cost+eg_cost:,.0f} (storage share {st_cost/(st_cost+eg_cost):.1%})")
print("\nsensitivity (annual total, USD millions)")
base = st_cost + eg_cost
cases = {
"photos per user 250": dict(photos_per_user=250),
"photos per user 1000": dict(photos_per_user=1000),
"replicas 1.5 (erasure coded)": dict(replicas=1.5),
"CDN hit 0.5": dict(hit=0.5),
"CDN hit 0.0 (no CDN cache)": dict(hit=0.0),
"views 3x higher": dict(thumb_views=1800, full_views=45),
}
for name, kw in cases.items():
r = costs(**kw)
print(f"{name:30s} {(r[3]+r[6])/1e6:8.1f} ({(r[3]+r[6])/base:.2f}x base)")
# independent recomputation: per-user route, in MB and with explicit monthly steps
per_user_mb = PHOTOS_PER_USER * ORIGINAL_MB * 1.1 * REPLICAS
storage_check = MAU * per_user_mb / 1000 * 0.02 * 12
egress_check = sum(MAU * (THUMB_VIEWS*THUMB_SERVED_MB + FULL_VIEWS*ORIGINAL_MB) / 1000 * (1-CDN_HIT) * 0.08 for _ in range(12))
assert abs(storage_check - st_cost) < 1, "storage disagrees"
assert abs(egress_check - eg_cost) < 1, "egress disagrees"
# thumbnails must add exactly 10% on top of the originals
assert abs(st_cost / (MAU*PHOTOS_PER_USER*ORIGINAL_MB*REPLICAS/1000*0.02*12) - 1.1) < 1e-9
print("\nchecks passed")
Output:
photos stored : 50,000,000,000
logical size (PB) : 110.0
stored with 3x (PB) : 330.0
storage cost per year : USD 79,200,000
delivered per year (PB): 72.0
origin to CDN (PB/yr) : 7.20
egress cost per year : USD 576,000
total per year : USD 79,776,000 (storage share 99.3%)
sensitivity (annual total, USD millions)
photos per user 250 40.2 (0.50x base)
photos per user 1000 159.0 (1.99x base)
replicas 1.5 (erasure coded) 40.2 (0.50x base)
CDN hit 0.5 82.1 (1.03x base)
CDN hit 0.0 (no CDN cache) 85.0 (1.06x base)
views 3x higher 80.9 (1.01x base)
checks passed
Total: about USD 79.8 million a year under these assumptions, of which egress to the CDN is USD 0.58 million. This is a steady-state cost for a fully built-up library; in a growing service the first year is lower. Request fees, the CDN's own delivery bill to end users and retrieval fees are not in the question and are not included.
Which assumptions matter most
Ranked by the sensitivity table ("CDN hit 0.5" means only half of delivered bytes come from cache): photos per user and replication each move the total by a factor of about 2 (half the photos or half the copy overhead halves the bill), while the CDN hit ratio and the viewing rate barely register (even a 0% hit ratio adds only about 6%). Original size matters in proportion (a 1 MB average halves the storage bill). So the questions to ask first are: how many photos does an average user really keep, how many copies do we pay for, and what is the original size distribution. Of the four invented viewing inputs (600 thumbnail views, 50 KB per thumbnail, 15 full-size views, 90% hit ratio), ask product for the two view counts first: thumbnails and full-size views each contribute 30 of the 60 MB delivered per user per month, so those two set the delivered volume, while the hit ratio only scales what reaches the origin.
Where to look for savings
- Fewer physical copies: replacing three full copies with erasure coding (each file is split into data pieces plus extra parity pieces, which are computed check data that lets a lost piece be rebuilt, for example 6 data + 3 parity = 1.5x overhead) halves the raw bytes at the cost of rebuild work and slower reads.
- Cold tiering: most photos are rarely viewed. As an illustration, if 80% are cold (rarely read) and a colder storage class (a cheaper tier of the same storage service, built for rarely read data) costs half as much per GB-month, storage falls by 0.8×0.5=40% (about USD 31.7 million of 79.2 million). Colder classes usually add retrieval fees (a charge each time data is read back out) and minimum retention (a minimum number of days you pay for even if you delete sooner), so check the provider's price list.
- Thumbnails need not be triple-stored: they can be regenerated from originals. Keeping 1 copy instead of 3 removes 20 PB of the 30 PB of thumbnail copies, which is 20 million GB x USD 0.24 per GB-year = USD 4.8 million a year (about 6%).
- Smaller originals: re-encoding on upload or deleting duplicates reduces the base that everything multiplies.
- Egress is not where the money is here, so improving the CDN hit ratio is worth doing for latency, not for this bill.
Common mistakes
- Forgetting the replication multiplier, or applying it to storage but not to thumbnails without saying so.
- Mixing GB and GiB, or per-month and per-year prices.
- Putting all the effort into egress optimisation when the sensitivity table shows it is under 1% of the bill.
- Quoting the egress figure without stating the viewing assumptions it rests on.
Running the code
Python 3.12, standard library only. Save the listing as image_cost.py and run python image_cost.py. It ends with checks passed when an independent per-user recomputation matches and thumbnails add exactly 10%; setting THUMB_FRACTION = 0.00 makes the final check fail.
Estimate the peak outbound bandwidth and the monthly data egress for a video streaming service with 5 million daily viewers who each watch about an hour a day across a mix of resolutions. Show how the bitrate mix and the evening peak change the answer, and what the egress figure implies for serving it from a CDN.
Sample Answer
The idea in plain words
Egress is data leaving your servers toward viewers, and it is what you serve and (usually) what you pay for. For video it comes from one product: viewing time multiplied by bitrate, the number of bits per second the player receives (a sharper picture needs more bits per second).
The one insight is that the bitrate mix sets the volume (total data per month) while the shape of the day sets the peak (how many bits per second you must be able to push at the busiest moment), and the two are sized separately. A CDN (content delivery network: servers placed near viewers that keep copies of popular video so it does not travel from your own servers each time) then decides how much of that peak your own origin servers actually see. Two names recur below: the origin is your own servers, which hold the master copy of every video, and an edge server is one of the CDN's cache machines placed near viewers, answering most requests so the origin does not have to.
Every input below is an assumption with a plausible range, not a statistic about a real service.
Method
- Viewer-seconds per day (one viewer watching for one second). 5,000,000×1 hour×3600=1.8×1010 viewer-seconds.
- Average bitrate from the mix. Each resolution tier has an assumed bitrate and a share of viewing time. The weighted mean is average Mbps=∑isharei×ratei where Mbps is megabits (millions of bits) per second.
- Daily and monthly volume. bytes per day=viewer-seconds×average bits per second÷8 then multiply by 30 days. Dividing by 8 turns bits into bytes.
- Average and peak bandwidth. average bits per second=86,400bytes per day×8 and the peak is the average times the peak-to-average ratio (how much busier the busiest hour is than the mean hour), which comes from an assumed hour-by-hour viewing profile.
- CDN implications. Origin load is (1−cache hit ratio) times the total, where the hit ratio is the share of bytes an edge server hands out without going back to the origin. Edge server count is peak bandwidth divided by the usable output of one server.
Assumptions
| Input | Value | Plausible range |
|---|---|---|
| Daily viewers | 5 million | given |
| Viewing per viewer | 1 hour a day | given |
| Delivered bitrate, SD (480p) | 1.5 Mbps | 0.7 to 2.5 |
| Delivered bitrate, HD (1080p) | 5 Mbps | 3 to 8 |
| Delivered bitrate, UHD (4K) | 15 Mbps | 10 to 25 |
| Viewing-time mix SD / HD / UHD, base | 30% / 55% / 15% | varies by audience and devices |
| Evening profile | 24 relative weights, one per clock hour (listed below), busiest hour about 11% of the day | the shape is the assumption; flat would be 4.2% |
| Edge cache hit ratio | 95% | 85% to 99% |
| One edge server, usable output | 40 Gbps, run at 50% at peak (headroom for failures, bursts inside the hour and uneven load) | 10 to 100 Gbps |
Units are decimal: 1 PB (petabyte) is 1015 bytes or one million GB, and 1 Tbps is 1012 bits per second. The model counts delivered video bytes and ignores audio, retransmissions (packets sent again after being lost) and players that buffer ahead of playback (download several seconds beyond the current position).
The bitrate comes from a ladder of quality levels, called rungs, that the player can pick from; the top rung is the highest quality offered. A codec is the method that compresses the video into those bits, and an encoder is the program that applies it, so a more efficient codec delivers the same picture at a lower rung bitrate.
The evening profile, step by step. The 24 weights, from midnight onward, are 1, 1, 1, 1, 1, 1, 1.5, 2, 2, 2, 2, 2.5, 3, 3, 3, 3.5, 4, 5, 6.5, 8, 9, 9, 7, 3. They add up to 82. The busiest hours (20:00 and 21:00, weight 9) therefore carry 9/82=11.0 percent of the day's viewing, against 1/24=4.2 percent if viewing were flat, and the peak-to-average ratio is 9×24/82=2.63.
Worked example, computed by a program
The program evaluates three bitrate mixes, applies the evening profile, derives the CDN figures for the base mix, and cross-checks the base mix by summing tier by tier and hour by hour.
import math
viewers = 5_000_000 # given: daily viewers
hours_each = 1.0 # given: about an hour of viewing per viewer per day
days = 30 # assumption: days per month
# Assumed delivered bitrates in megabits per second (range given), and shares of VIEWING TIME
rates = {"SD (480p)": 1.5, "HD (1080p)": 5.0, "UHD (4K)": 15.0} # ranges: 0.7-2.5, 3-8, 10-25
mixes = {
"mobile-heavy": (0.60, 0.38, 0.02),
"base": (0.30, 0.55, 0.15),
"premium": (0.15, 0.55, 0.30),
}
# Assumed share of a day's viewing that falls in each clock hour, as relative weights (evening bump)
weights = [1, 1, 1, 1, 1, 1, 1.5, 2, 2, 2, 2, 2.5, 3, 3, 3, 3.5, 4, 5, 6.5, 8, 9, 9, 7, 3]
hour_share = [w / sum(weights) for w in weights]
peak_to_avg = max(hour_share) * 24
hit_ratio = 0.95 # assumption: share of bytes served from CDN edge caches (range 0.85 to 0.99)
edge_gbps = 40 # assumption: usable output of one edge server (range 10 to 100)
edge_util = 0.5 # assumption: run edge servers at 50% of that at peak
viewer_seconds = viewers * hours_each * 3600
def summary(mix):
avg_mbps = sum(s * r for s, r in zip(mix, rates.values()))
daily_bytes = viewer_seconds * avg_mbps * 1e6 / 8
avg_tbps = daily_bytes * 8 / 86_400 / 1e12
return avg_mbps, daily_bytes, avg_tbps
print(f"peak hour carries {max(hour_share):.1%} of the day; peak-to-average = {peak_to_avg:.2f}")
print(f"{'mix':<14}{'avg Mbps':>9}{'PB/day':>8}{'PB/month':>10}{'avg Tbps':>10}{'peak Tbps':>11}")
for name, mix in mixes.items():
a, d, t = summary(mix)
print(f"{name:<14}{a:>9.2f}{d/1e15:>8.2f}{d*days/1e15:>10.1f}{t:>10.2f}{t*peak_to_avg:>11.2f}")
a, d, t = summary(mixes["base"])
peak_tbps = t * peak_to_avg
peak_concurrent = viewers * hours_each * max(hour_share) * 1.0 # viewers watching in the peak hour (1 hour each)
print(f"base: concurrent viewers at peak hour ~ {peak_concurrent:,.0f}; peak {peak_tbps:.2f} Tbps")
print(f"base: monthly egress {d*days/1e15:.1f} PB = {d*days/1e9/1e6:.1f} million GB (decimal, 1 PB = 1 million GB)")
origin_tbps = peak_tbps * (1 - hit_ratio)
edge_servers = math.ceil(peak_tbps * 1000 / (edge_gbps * edge_util))
print(f"origin load at {hit_ratio:.0%} hit ratio: peak {origin_tbps*1000:.0f} Gbps, month {d*days*(1-hit_ratio)/1e15:.1f} PB")
print(f"edge servers at {edge_gbps} Gbps x {edge_util:.0%} utilisation: {edge_servers}")
print(f"each 0.01 USD per GB of delivery price = {d*days/1e9*0.01/1e6:.2f} million USD per month")
# Independent recomputation: tier-by-tier viewer-seconds, and hour-by-hour bandwidth integrated over the day
mix = mixes["base"]
tier_bytes = sum(viewer_seconds * share * r * 1e6 / 8 for share, r in zip(mix, rates.values()))
hourly_bytes = sum((d * s) for s in hour_share) # each hour's bytes = day total x its share
hourly_bps = [d * 8 * s / 3600 for s in hour_share]
ok = (abs(tier_bytes - d) / d < 1e-12 and abs(hourly_bytes - d) / d < 1e-12
and abs(max(hourly_bps) / 1e12 - peak_tbps) < 1e-9)
print("check (per-tier sum, hour-by-hour integral):", "PASS" if ok else "FAIL")
Output:
peak hour carries 11.0% of the day; peak-to-average = 2.63
mix avg Mbps PB/day PB/month avg Tbps peak Tbps
mobile-heavy 3.10 6.97 209.2 0.65 1.70
base 5.45 12.26 367.9 1.14 2.99
premium 7.47 16.82 504.6 1.56 4.10
base: concurrent viewers at peak hour ~ 548,780; peak 2.99 Tbps
base: monthly egress 367.9 PB = 367.9 million GB (decimal, 1 PB = 1 million GB)
origin load at 95% hit ratio: peak 150 Gbps, month 18.4 PB
edge servers at 40 Gbps x 50% utilisation: 150
each 0.01 USD per GB of delivery price = 3.68 million USD per month
check (per-tier sum, hour-by-hour integral): PASS
Hand check of the base row: 0.30×1.5+0.55×5+0.15×15=0.45+2.75+2.25=5.45 Mbps. One viewer-hour is 5.45×106×3600/8=2.4525×109 bytes, about 2.45 GB. Times 5 million viewers is 12.26 PB per day, and times 30 days is 367.9 PB per month.
How the bitrate mix and the evening peak change the answer
- Bitrate mix moves volume. Mobile-heavy (60% SD) gives 3.10 Mbps average and 209.2 PB per month; premium (30% UHD) gives 7.47 Mbps and 504.6 PB. That is 0.57 and 1.37 times the base, a range of more than 2 to 1 from the mix alone, and UHD viewers are the most expensive per hour: 15 Mbps is 10 times SD for the same hour watched.
- The evening profile moves the peak, not the volume. The volume per month is identical whatever the clock-hour shape. The base mix averages 1.14 Tbps over the day, but the assumed profile puts about 11.0 percent of viewing in the busiest hour, 2.63 times an average hour, so the peak is 2.99 Tbps and about 548,780 viewers are watching during that hour (the concurrent viewers at peak, found as 5,000,000×9/82 because each viewer watches one hour). A flat day would peak at 1.14 Tbps; the profile alone raises the peak to 2.6 times that.
- Peak across mixes. 1.70 Tbps (mobile-heavy) up to 4.10 Tbps (premium). The busiest hour's average is used here, and the instantaneous peak inside that hour is somewhat higher.
What the egress figure implies for a CDN
- Origin cannot serve this directly. A peak of 2.99 Tbps is far beyond one site's network, so a CDN is needed.
- Hit ratio sets the origin load. At 95 percent, the origin supplies 150 Gbps at peak and 18.4 PB per month. At 90 percent it would be 0.10×2.99 Tbps≈299 Gbps, double. The long tail of rarely watched titles is where hit ratio is lost.
- Edge capacity is set by the peak. 2.99 Tbps = 2,990 Gbps, divided by 20 Gbps (40 Gbps at 50 percent utilisation) gives 150 edge servers across all locations, and the load is not spread evenly across the world.
- Cost follows volume. Delivery is usually priced per GB, and the price is a negotiated assumption, so state the formula: each 0.01 USD per GB is 367.9 million GB×0.01=3.68 million USD per month. A 10 percent cut in average bitrate (a more efficient codec, or a lower top rung) cuts that by 10 percent.
- Peak and volume are billed differently. A capacity commitment (a contract for a fixed amount of bandwidth you pay for whether or not you fill it) follows the peak, 2.99 Tbps here, while a usage bill follows the volume, 367.9 PB. Two services with the same monthly volume but a flat day and an evening-heavy day would need about 1.14 and 2.99 Tbps of committed capacity, so the flatter day is cheaper at the same volume.
The judgment
Plan on the base case of about 2.5 GB per viewer-hour, 368 PB per month and a peak near 3 Tbps, and serve it from a CDN with a 95 percent hit target. Measure the two drivers separately, because they set different things: the bitrate mix sets the volume and therefore the bill (209 to 505 PB a month across the three mixes, more than 2 to 1), and the evening shape sets the capacity (a peak 2.63 times the average hour).
What would change the plan: a hit ratio near 85 percent, which triples the origin load from 150 Gbps to 449 Gbps (0.15 times 2.99 Tbps) and calls for a much larger origin and network commitment; or a more concentrated evening, since the edge server count rises in proportion to the peak-to-average ratio (a profile with a ratio of 4 instead of 2.63 would need about 228 edge servers instead of 150).
Common mistakes
- Forgetting to divide bits by 8 (a 5 Mbps stream is 0.625 MB per second).
- Multiplying the average bandwidth by 24 hours and 30 days without converting to bytes, or mixing Tbps and TB.
- Using a single bitrate ("1080p") instead of a mix, or weighting the mix by viewers instead of by viewing time.
- Presenting the peak as the average, or the monthly volume as if it set the capacity needed.
- Ignoring the hit ratio, so the origin appears to need terabits per second.
Running the code
Python 3.12, standard library only.
python video_egress_sizing.py
Unlock Full Question Bank
Get access to all 12 Estimation and Capacity Sizing interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.