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.
A teammate's back-of-the-envelope estimate says a photo service needs 4 petabytes of new storage per day for 10 million daily uploads. Find what is wrong with the estimate, explain the checks that catch this kind of error (units, bits versus bytes, per-second versus per-day, order of magnitude against a known system), and give a corrected figure.
Sample Answer
The idea in plain words
Divide the claim back into a size per item. 4 petabytes (PB; 1 PB is 1015 bytes) per day spread over 10 million uploads is 4×1015/107=4×108 bytes, which is 400 megabytes (MB) per photo. A photo from a phone is typically a few MB (an assumption, range 1 to 10 MB for a stored original). So the estimate is about 100 times too high. The check that found it, dividing a total by a count to see whether the unit looks believable, takes ten seconds and works on almost any estimate.
All sizes below are decimal (1 MB = 106 bytes, 1 TB = 1012 bytes) so the prefixes stay consistent; the 1024-based versions differ by roughly 5 percent at the megabyte level and 10 percent at the terabyte level, which does not change an order of magnitude.
The checks, in the order to run them
- Write every quantity with its unit and basis. "4 PB per day" is bytes per day. "10 million uploads per day" is a count per day. Both are per day, so the division is legitimate.
- Divide back to a per-item size. 400 MB per photo. Compare with objects you know: a phone photo is a few MB, a short video clip is tens to hundreds of MB. A 400 MB "photo" is the size of a video clip, which a photo service is not expected to store as a photo.
- Check the common slips one by one. Compare the claim with an honest estimate (10 million times 4 MB) and see whether the ratio matches a known factor:
- bits versus bytes: a factor of 8 (1 byte is 8 bits);
- per second versus per day: a factor of 86,400 (seconds in a day);
- a prefix mistake such as KB for MB: a factor of 1,000;
- 1000 versus 1024 conventions: a factor of 1.024 per prefix step (about 1.05 at megabytes, 1.10 at terabytes, 1.13 at petabytes);
- miscounting zeros in the count or the size: a factor of 10, 100 and so on.
- Recompute forward by a second route. Go per day, then go per second and multiply back by 86,400. If the two disagree, there is a unit slip in one of them.
- Cross-check a second quantity. The ingest rate implied by the claim should look believable too.
- Compare with a reference of known scale. Express the result in something you can picture: how many large disks fill up per day, and whether the implied network rate is plausible for the service.
Worked example by hand
Assumptions: 10 million uploads per day (given), 4 MB average stored original (range 1 to 10), derived copies such as thumbnails and resized versions add 25 percent of the original (range 10 to 60 percent), 3 full replicas (replication factor 3; 1.5 if erasure coded, a scheme that stores parity pieces instead of whole copies).
- Originals per day: 107×4×106=4×1013 bytes = 40 TB.
- With derived copies: 40×1.25=50 TB.
- Physical disk after 3 replicas: 50×3=150 TB per day.
- Per year, originals only: 40×365=14,600 TB = 14.6 PB.
- Upload rate: 107/86400=115.7 per second on average. At 4 MB each that is 463 MB/s, and times 8 bits per byte it is 3,704 megabits per second, about 3.70 gigabits per second (Gbit/s). If the peak is 3 times the average (an assumption), the figure to design for is 3.70×3=11.1 Gbit/s.
- The claim, as a rate: 4×1015/86400=4.63×1010 bytes per second = 46.3 GB/s = 370 Gbit/s on average, which is 100 times the 3.70 Gbit/s.
- In disks: with 20 TB disks (assumption), the claim fills 4000/20=200 disks per day before replication; the corrected physical figure fills 150/20=7.5.
Ratios: the claim is 100 times the 40 TB of originals, and 4000/150=26.7 times the 150 TB of physical storage. Pushing every assumption to the top of its range (10 MB, derived copies at 0.6, 3 replicas) gives 107×10×1.6×3/106=480 TB per day, still 4000/480=8.3 times below the claim. No choice inside the stated ranges reaches 4 PB.
import math
# ---- Assumptions (decimal units: 1 MB = 10**6 bytes, 1 TB = 10**12, 1 PB = 10**15) ----
UPLOADS_PER_DAY = 10_000_000 # given
PHOTO_MB = 4.0 # average stored original, range 1 to 10
DERIVED = 0.25 # thumbnails and resized copies as a fraction of the original, range 0.1 to 0.6
REPLICAS = 3 # full copies kept, 1.5 if erasure coded, range 1.5 to 3
CLAIMED_PB_PER_DAY = 4.0 # the teammate's figure
SECONDS_PER_DAY = 86_400
PLAUSIBLE_PHOTO_MB = (0.05, 100) # illustrative band for one uploaded image
claimed_bytes = CLAIMED_PB_PER_DAY * 1e15
implied_mb = claimed_bytes / UPLOADS_PER_DAY / 1e6
print(f"implied size per upload: {implied_mb:.0f} MB")
lo, hi = PLAUSIBLE_PHOTO_MB
print(f"inside the {lo}-{hi} MB photo band: {lo <= implied_mb <= hi}")
# Which single slip would explain the claim, given a 4 MB photo and 10 million uploads?
honest_bytes = UPLOADS_PER_DAY * PHOTO_MB * 1e6
ratio = claimed_bytes / honest_bytes
slips = {"bits vs bytes (x8)": 8, "KB vs MB (x1000)": 1000, "per second vs per day (x86400)": 86400,
"1024 vs 1000 (x1.024 to x1.13)": 1.024, "two extra zeros (x100)": 100}
print(f"claim / honest estimate = {ratio:.0f}")
for name, f in slips.items():
print(f" {name:32s} reproduces claim: {math.isclose(f, ratio, rel_tol=0.01)}")
# Corrected estimate, step by step
original_tb = UPLOADS_PER_DAY * PHOTO_MB * 1e6 / 1e12
with_derived_tb = original_tb * (1 + DERIVED)
physical_tb = with_derived_tb * REPLICAS
print(f"originals per day: {original_tb:.0f} TB")
print(f"with derived copies: {with_derived_tb:.1f} TB")
print(f"physical with {REPLICAS} replicas: {physical_tb:.1f} TB")
print(f"originals per year: {original_tb * 365 / 1000:.2f} PB")
# Bandwidth view (bytes vs bits)
avg_upload_rate = UPLOADS_PER_DAY / SECONDS_PER_DAY
avg_mb_s = avg_upload_rate * PHOTO_MB
print(f"uploads per second (average): {avg_upload_rate:.1f}")
print(f"ingest: {avg_mb_s:.0f} MB/s = {avg_mb_s * 8 / 1000:.2f} Gbit/s")
print(f"claimed figure would be {claimed_bytes / SECONDS_PER_DAY / 1e9:.1f} GB/s = {claimed_bytes / SECONDS_PER_DAY * 8 / 1e9:.0f} Gbit/s")
# Independent recomputation: per-second route (with seconds per day spelled out as 24*60*60) must match the per-day route
per_second_route_tb = avg_upload_rate * PHOTO_MB * 1e6 * (24 * 60 * 60) / 1e12
assert math.isclose(per_second_route_tb, original_tb, rel_tol=1e-9), (per_second_route_tb, original_tb)
assert not (lo <= implied_mb <= hi), "claim should fail the size check"
print("check: per-second route equals per-day route")
# Sensitivity on physical TB per day
def phys(mb=PHOTO_MB, d=DERIVED, r=REPLICAS, n=UPLOADS_PER_DAY):
return n * mb * 1e6 * (1 + d) * r / 1e12
print(f"photo size 1 / 10 MB -> {phys(mb=1):.1f} / {phys(mb=10):.1f} TB")
print(f"derived 0.1 / 0.6 -> {phys(d=0.1):.1f} / {phys(d=0.6):.1f} TB")
print(f"replication 1.5 / 3 -> {phys(r=1.5):.1f} / {phys(r=3):.1f} TB")
print(f"uploads 5M / 20M -> {phys(n=5_000_000):.1f} / {phys(n=20_000_000):.1f} TB")
drive_tb = 20
print(f"drives of {drive_tb} TB filled per day: claim {claimed_bytes / 1e12 / drive_tb:.0f} (before replicas), corrected {physical_tb / drive_tb:.1f}")
Output:
implied size per upload: 400 MB
inside the 0.05-100 MB photo band: False
claim / honest estimate = 100
bits vs bytes (x8) reproduces claim: False
KB vs MB (x1000) reproduces claim: False
per second vs per day (x86400) reproduces claim: False
1024 vs 1000 (x1.024 to x1.13) reproduces claim: False
two extra zeros (x100) reproduces claim: True
originals per day: 40 TB
with derived copies: 50.0 TB
physical with 3 replicas: 150.0 TB
originals per year: 14.60 PB
uploads per second (average): 115.7
ingest: 463 MB/s = 3.70 Gbit/s
claimed figure would be 46.3 GB/s = 370 Gbit/s
check: per-second route equals per-day route
photo size 1 / 10 MB -> 37.5 / 375.0 TB
derived 0.1 / 0.6 -> 132.0 / 192.0 TB
replication 1.5 / 3 -> 75.0 / 150.0 TB
uploads 5M / 20M -> 75.0 / 300.0 TB
drives of 20 TB filled per day: claim 200 (before replicas), corrected 7.5
Computed with Python 3.12 (standard library only). The size band in the program is an illustrative test for one uploaded image; a real review would also cover video, RAW files and very large panoramas.
What is wrong, and the corrected figure
The estimate implies 400 MB per photo. Of the slips tried, only a factor of 100 reproduces it: either the per-photo size was entered as roughly 400 MB instead of roughly 4 MB, or the count was read as about a billion uploads instead of 10 million. The list of slips is not exhaustive and the number alone cannot say which happened, so ask the author for the derivation line by line. The bits-versus-bytes factor of 8, the per-second factor of 86,400 and the prefix factor of 1,000 each fail to match.
The corrected figure, under the assumptions above: about 40 TB per day of new original photos, about 50 TB with derived copies, and about 150 TB per day of physical disk with 3 replicas. Varying one assumption at a time, the physical figure ranges from 37.5 TB (1 MB photos) to 375 TB (10 MB photos), and with every assumption at the top of its range it reaches 480 TB, still far below 4 PB. Name the basis whenever you quote one: logical bytes (what users uploaded) versus physical bytes (what the disks hold).
Judgment
State the corrected figure with its range and its basis, and say what would change it: if the service also accepts video, the average object size and the whole answer change, and video should be estimated as its own line. Reconcile with real data when it exists: the storage system's growth over the last few weeks is a measurement that overrides any estimate here.
Common mistakes
- Comparing two numbers on different bases, such as a claim meant as physical disk against 40 TB of logical originals.
- Reporting the corrected figure without saying what it includes (originals only, derived copies, replicas).
- Fixing the arithmetic but not testing the result against a size you know.
- Mixing MB/s and Mbit/s: network links are quoted in bits, storage in bytes.
- Treating 86,400 as 100,000 and calling it close enough; that is fine for an order of magnitude only if it is stated.
Running the code
python photo.py
Save the program as photo.py. It needs only the Python 3.12 standard library (math) and no input files.
A new microtransaction feature is expected to process $50M of gross volume a year at an average of $2 per transaction. Assuming 20% of daily volume lands in a single peak hour, estimate average and peak transactions per second, and explain what that implies for how you would provision the payment path and what headroom you would want.
Sample Answer
The idea in plain words
Dollars per year become transactions per second (TPS, transactions processed each second) in two steps: divide dollars by the average ticket to get a count, then spread the count over time. Spreading it evenly gives the average rate; concentrating a stated share of a day into one hour gives the peak. The surprise is how small the numbers are: under 1 TPS on average and under 4 at the peak. The useful part of the answer is what that implies: throughput is not the constraint, availability and the payment provider's behaviour are.
Method
Assumptions: volume is spread evenly over 365 days (real volume has weekday and seasonal shape), and the 20% peak-hour share is as given.
- Transactions per year: 50,000,000/2=25,000,000.
- Per day: 25,000,000/365=68,493.
- Average TPS: 25,000,000/(365×86,400)=25,000,000/31,536,000=0.793.
- Peak-hour transactions: 0.20×68,493=13,699.
- Peak TPS: 13,699/3,600=3.805, which is 4.8 times the average (24 hours x 20% share).
- Busiest single second: the peak hour is itself uneven. Assume the busiest second is 3 times the hour's mean (plausible 2 to 5): 11.4 TPS.
- Calls in flight (Little's law: items in the system equal arrival rate times time spent in it): at 3.805 TPS and an assumed 1 second per call to the payment provider, about 3.8 calls are in flight at once.
from fractions import Fraction
ANNUAL_USD = 50_000_000 # given: gross volume per year
AVG_TICKET = 2 # given: USD per transaction
PEAK_HOUR_SHARE = 0.20 # given: share of a day's volume in the peak hour
DAYS = 365 # convention: spread evenly over 365 days (assumption)
SEC_BURST = 3.0 # assumption: busiest second vs the peak-hour mean (plausible 2 to 5)
LATENCY_S = 1.0 # assumption: payment provider round trip (plausible 0.3 to 3)
HEADROOM = 10 # design multiple on the peak-hour rate
tx_year = ANNUAL_USD / AVG_TICKET
tx_day = tx_year / DAYS
avg_tps = tx_year / (DAYS * 86_400)
peak_hour_tx = tx_day * PEAK_HOUR_SHARE
peak_tps = peak_hour_tx / 3_600
print(f"transactions per year : {tx_year:,.0f}")
print(f"transactions per day : {tx_day:,.0f}")
print(f"average TPS : {avg_tps:.3f}")
print(f"peak-hour transactions: {peak_hour_tx:,.0f}")
print(f"peak-hour TPS : {peak_tps:.3f} ({peak_tps/avg_tps:.1f}x average)")
print(f"busiest-second TPS : {peak_tps*SEC_BURST:.1f}")
print(f"in flight at peak : {peak_tps*LATENCY_S:.1f} (Little's law, {LATENCY_S:g} s per call)")
print(f"design target (x{HEADROOM}) : {peak_tps*HEADROOM:.1f} TPS")
OUTAGE_S, DRAIN_S = 1_800, 600 # assumption: provider down 30 minutes at peak, backlog drained in 10 minutes
backlog = peak_tps * OUTAGE_S
drain_tps = backlog / DRAIN_S + peak_tps
print(f"backlog after {OUTAGE_S//60} min outage: {backlog:,.0f} transactions ; rate to drain in {DRAIN_S//60} min while live traffic continues: {drain_tps:.1f} TPS")
print("\nsensitivity: peak-hour TPS")
for label, share, ticket in (("20% of day, USD 2", 0.20, 2), ("10% of day", 0.10, 2), ("40% of day", 0.40, 2),
("USD 0.50 average ticket", 0.20, 0.5), ("USD 10 average ticket", 0.20, 10)):
t = ANNUAL_USD / ticket / DAYS * share / 3600
print(f"{label:26s} {t:7.2f}")
# independent route with exact fractions: peak TPS = (annual / ticket / 365 * share) / 3600
exact = Fraction(ANNUAL_USD, AVG_TICKET) / DAYS * Fraction(1, 5) / 3600
assert abs(float(exact) - peak_tps) < 1e-9, "exact fraction disagrees"
# the peak-hour rate is 24 x the share times the average, so 4.8x for a 20% share
assert abs(peak_tps - 3.805) < 0.001
assert peak_tps / avg_tps == 24 * PEAK_HOUR_SHARE or abs(peak_tps / avg_tps - 24 * PEAK_HOUR_SHARE) < 1e-9
print("\nchecks passed")
Output:
transactions per year : 25,000,000
transactions per day : 68,493
average TPS : 0.793
peak-hour transactions: 13,699
peak-hour TPS : 3.805 (4.8x average)
busiest-second TPS : 11.4
in flight at peak : 3.8 (Little's law, 1 s per call)
design target (x10) : 38.1 TPS
backlog after 30 min outage: 6,849 transactions ; rate to drain in 10 min while live traffic continues: 15.2 TPS
sensitivity: peak-hour TPS
20% of day, USD 2 3.81
10% of day 1.90
40% of day 7.61
USD 0.50 average ticket 15.22
USD 10 average ticket 0.76
checks passed
What this implies for provisioning
- Throughput is trivial. 3.8 TPS in the peak hour and 11.4 TPS in the busiest second is within what a single small service instance and an ordinary relational database can write: as a rough order of magnitude that varies with hardware and schema, one relational database on ordinary hardware handles hundreds to thousands of small writes per second, which is at least about 25 times this 3.8 TPS peak and far more at the upper end. Do not add sharding (splitting the data across several databases), a queue whose purpose is to spread load across many workers, or autoscaling (adding and removing instances automatically as load changes) for this reason. A different queue is still worth having: a durable holding area for payments that wait while the provider is down, which is the backlog discussed below.
- Provision for availability instead. Run at least two instances in different failure zones (separate data-centre sections that do not share power or network, so one failing does not take down the other) so one can fail without an outage, with the database in a replicated setup (a second copy kept in step with the first that can take over if it fails). The payment path should be built around correctness: idempotency keys (a unique key per payment attempt so a retry cannot charge twice), a durable record before calling the provider, and reconciliation (comparing your own payment records with the provider's reports to find any that disagree).
- The provider is the bottleneck to check. Confirm its rate limits and latency at 11.4 TPS and at the headroom target below; time out and retry with backoff (waiting longer before each further attempt, for example 1 s, 2 s, 4 s, so retries do not pile onto a struggling provider).
- Headroom: design and load-test for 10 times the peak-hour rate, 38.1 TPS. The reason is not that 10x traffic is expected; it is that the share of the day in the peak hour is an assumption (the sensitivity table shows 40% of the day in one hour gives 7.6 TPS, and a USD 0.50 average ticket gives 15.2 TPS), launches and promotions bunch traffic, and failures create backlogs. For example, if the provider is down for 30 minutes at the peak, 6,849 transactions queue (3.805×1,800); draining them in 10 minutes while live traffic continues needs 6,849/600+3.805=15.2 TPS, four times the peak. A 10x design target covers that with room.
What would change the answer
The average ticket matters most: the count of transactions is inversely proportional to it, so USD 0.50 average quadruples every rate above, and USD 10 divides them by five. The peak-hour share scales the peak linearly. The count equals total dollars divided by the true mean ticket, whatever the spread of tickets, so the one thing to confirm is that the USD 2 is a mean and not a typical or median ticket. In a heavy-tailed mix (many tiny transactions and a few very large ones) the mean is usually above the median, so a median quoted as the average would make the real count lower than computed here.
Common mistakes
- Dividing 50 million dollars by seconds without converting to transactions first (a factor of 2 here, and a larger error for smaller tickets).
- Using the average as the design number, or applying the 20% share to the year instead of a day.
- Over-building for scale when the load is under 12 TPS in the busiest second, and under-building for availability and correctness.
- Forgetting to ask about the provider's limits and about retries after an outage.
Running the code
Python 3.12, standard library only. Save the listing as tps_estimate.py and run python tps_estimate.py. It ends with checks passed when an exact-fraction recomputation of the peak TPS agrees with the floating-point result and the peak-to-average ratio equals 24 times the share.
A chat service keeps a persistent connection open for every online user. With 20 million daily active users and a peak of 4 million concurrent connections, estimate the memory and the number of connection servers needed, and explain which per-connection costs dominate the estimate.
Sample Answer
The idea in plain words
A persistent connection (a network connection the client opens once and keeps open so the server can push messages at any time) costs the server a little memory and a little work for as long as it stays open, even if nothing is sent. Two things follow. First, the quantity to size from is concurrent connections (how many are open at the same moment), not daily active users (DAU, distinct users in a day): 20 million DAU with a 4 million peak means only about one user in five is connected at the busiest moment. Second, the number of servers is the largest of several counts, each from a different limit: memory, CPU, and an operating cap on how many connections you are willing to lose when one server fails. With the numbers below the memory and CPU counts come out small, and the operating cap is what sets the fleet size.
The cap exists because of blast radius: the number of users who lose their connection when one server dies. With the numbers below one server carries about 83,333 of the 4 million connections, so a single failure disconnects 2.1 percent of users, and all of them try to reconnect at once.
All inputs below are assumptions with plausible ranges, not measurements of any product. Memory uses binary units: 1 KiB is 1,024 bytes and 1 GiB is 10243 bytes.
Method
- List the per-connection memory costs and add them: bytes per connection=kernel+buffers+TLS+session+runtime where the kernel part is the operating system's socket buffers and state, TLS is the encryption session state (TLS is the protocol that encrypts the connection), session is your own per-user state, and runtime is the language runtime's object for the connection. A server that handles many connections in one thread, which watches all of them and acts on whichever has data, is called an event loop; the alternative, one thread per connection, gives every connection its own thread stack and costs far more memory.
- Cluster memory. GiB=10242concurrent connections×KiB per connection
- Count servers by each limit. By memory: cluster GiB divided by usable memory per server. By CPU: message-equivalents per second divided by what one server handles, where a message-equivalent is the CPU work of one ordinary chat message (a keepalive costs 0.2 of one). By operating cap: concurrent connections divided by the connections you allow per server. The cap is a policy number, not a hardware limit: pick the share of users you accept losing when one server dies, and the cap follows. Losing one server of a fleet of N servers disconnects about 1/N of users, so a cap that gives 96 servers loses 1.0 percent per failure (1/96), 48 servers loses 2.1 percent (1/48) and 20 servers loses 5.0 percent (1/20). The cap used here, 100,000, gives the 48-server fleet computed below.
- Take the maximum, then add spare servers so that losing one, or draining one for a rolling deploy (taking its clients off it, then restarting servers a few at a time), does not overload the rest.
- Say which costs dominate, using the shares in the breakdown.
Assumptions
| Input | Value | Plausible range |
|---|---|---|
| Concurrent connections at peak | 4 million | given |
| Kernel socket state and buffers, idle | 8 KiB | 3 to 20 (grows when a connection is busy) |
| Application read and write buffers | 8 KiB | 2 to 64 |
| TLS session state | 20 KiB | 0 if a proxy ends TLS, otherwise 10 to 50 |
| Session and routing state | 4 KiB | 1 to 16 |
| Runtime object per connection | 4 KiB | 2 to 64 for an event loop; a thread per connection would typically cost far more |
| Keepalive (a small periodic message that keeps the connection alive through network devices) | every 30 s | 15 to 120 s |
| Messages sent plus received per connection | 2 per minute | 0.5 to 10 |
| CPU cost of one keepalive | 0.2 of a message | |
| One server's capacity | 50,000 message-equivalents per second | 20,000 to 200,000 |
| Server RAM, usable share | 64 GiB, 75 percent usable | the machine assumed for the memory count; memory turns out not to bind, so a smaller one would do |
| Operating cap per server | 100,000 connections | 50,000 to 250,000 |
| Spare capacity | 20 percent | 10 to 50 |
Worked example, computed by a program
import math
dau = 20_000_000 # given (the sizing input is the concurrent count, not this)
concurrent = 4_000_000 # given: peak concurrent connections
# Assumed memory per connection in KiB (1 KiB = 1,024 bytes), with plausible ranges
per_conn_kib = {
"kernel socket state and buffers": 8, # 3 to 20 when idle; grows if a connection is busy
"application read/write buffers": 8, # 2 to 64
"TLS session state": 20, # 0 if TLS ends at a proxy; 10 to 50 otherwise
"session and routing state": 4, # 1 to 16 (user id, presence, subscriptions)
"runtime object per connection": 4, # 2 to 64 (event-loop object vs a thread stack)
}
# Assumed activity per connection
heartbeat_s = 30 # one keepalive every 30 s (range 15 to 120)
msgs_per_min = 2 # messages sent plus received per connection per minute (range 0.5 to 10)
heartbeat_cost = 0.2 # one heartbeat costs 0.2 of a message in CPU
server_msgs_s = 50_000 # message-equivalents per second one server handles (range 20k to 200k)
# Assumed server and operating limits
server_ram_gib = 64
usable_fraction = 0.75 # rest: operating system, process overhead, headroom
conn_cap = 100_000 # operating cap per server (range 50k to 250k): blast radius of one failure
spare = 0.20 # spare servers for failures and rolling deploys
total_kib = sum(per_conn_kib.values())
print(f"per connection: {total_kib} KiB")
for name, k in per_conn_kib.items():
print(f" {name:<34}{k:>3} KiB {k/total_kib:>5.0%}")
cluster_gib = concurrent * total_kib / 1024 / 1024
print(f"cluster memory for {concurrent:,} connections: {cluster_gib:.1f} GiB")
print(f"wrongly sized from DAU instead: {dau * total_kib / 1024 / 1024:.1f} GiB")
by_memory = math.ceil(cluster_gib / (server_ram_gib * usable_fraction))
work = concurrent * (msgs_per_min / 60 + heartbeat_cost / heartbeat_s)
by_cpu = math.ceil(work / server_msgs_s)
by_cap = math.ceil(concurrent / conn_cap)
base = max(by_memory, by_cpu, by_cap)
servers = math.ceil(base * (1 + spare))
per_server_conns = concurrent / servers
per_server_gib = per_server_conns * total_kib / 1024 / 1024
hb_per_s = concurrent / heartbeat_s
print(f"work: {work:,.0f} message-equivalents/s; heartbeats are {hb_per_s:,.0f}/s = {hb_per_s*heartbeat_cost:,.0f} of them")
print(f"servers by memory {by_memory}, by CPU {by_cpu}, by connection cap {by_cap} -> {base}; with {spare:.0%} spare: {servers}")
print(f"per server: {per_server_conns:,.0f} connections, {per_server_gib:.1f} GiB of connection state")
print("sensitivity (cluster GiB for per-connection KiB):", {k: round(concurrent * k / 1024 / 1024, 1) for k in (20, total_kib, 100)})
print("sensitivity (servers for connection cap):", {c: math.ceil(math.ceil(concurrent / c) * (1 + spare)) for c in (50_000, 100_000, 250_000)})
print("TLS ended at a proxy instead:", f"{concurrent * (total_kib - per_conn_kib['TLS session state']) / 1024 / 1024:.1f} GiB")
# Independent recomputation in bytes, through the per-server accounting
bytes_total = concurrent * total_kib * 1024
per_server_bytes = math.ceil(concurrent / servers) * total_kib * 1024
ok = (abs(bytes_total / 1024**3 - cluster_gib) < 1e-9
and per_server_bytes * servers >= bytes_total
and per_server_bytes / 1024**3 < server_ram_gib * usable_fraction
and math.ceil(concurrent / servers) <= conn_cap)
print("check (bytes route, per-server accounting):", "PASS" if ok else "FAIL")
Output:
per connection: 44 KiB
kernel socket state and buffers 8 KiB 18%
application read/write buffers 8 KiB 18%
TLS session state 20 KiB 45%
session and routing state 4 KiB 9%
runtime object per connection 4 KiB 9%
cluster memory for 4,000,000 connections: 167.8 GiB
wrongly sized from DAU instead: 839.2 GiB
work: 160,000 message-equivalents/s; heartbeats are 133,333/s = 26,667 of them
servers by memory 4, by CPU 4, by connection cap 40 -> 40; with 20% spare: 48
per server: 83,333 connections, 3.5 GiB of connection state
sensitivity (cluster GiB for per-connection KiB): {20: 76.3, 44: 167.8, 100: 381.5}
sensitivity (servers for connection cap): {50000: 96, 100000: 48, 250000: 20}
TLS ended at a proxy instead: 91.6 GiB
check (bytes route, per-server accounting): PASS
Hand check of the headline: 4,000,000×44 KiB=176,000,000 KiB, divided by 10242 gives 167.8 GiB. The CPU count: 4,000,000×2/60=133,333 messages per second, plus 4,000,000/30=133,333 keepalives per second at 0.2 each (26,667), is 160,000 message-equivalents per second, and 160,000/50,000=3.2, rounded up to 4.
What dominates the estimate
- Memory per connection is dominated by TLS state (45 percent of the 44 KiB) and by the buffers (kernel plus application, 16 KiB, 36 percent together). If a proxy in front ends TLS, the connection servers hold 91.6 GiB instead of 167.8. Large pre-allocated buffers are the other lever: at 100 KiB per connection the cluster needs 381.5 GiB.
- CPU is dominated by messages, not keepalives. Messages and keepalives each arrive at 133,333 events per second, but a keepalive is cheap (0.2 of a message), so messages account for 133,333 of the 160,000 message-equivalents (83 percent) and keepalives for 26,667 (17 percent). Halving the keepalive interval to 15 seconds would double the keepalive part to 53,333 and lift the total to 186,667, which still needs 4 servers.
- The server count is dominated by the cap. Memory needs 4 servers, CPU needs 4, and the cap needs 40. The cap is a policy choice: 100,000 connections means one failure disconnects 2.1 percent of users (1/48) and a drain is manageable. At a 50,000 cap the fleet is 96 servers; at 250,000 it is 20.
- Sizing from DAU would be wrong. 20,000,000×44 KiB is 839.2 GiB, five times the real need.
Other limits to check before trusting the count
- File descriptors. A file descriptor is the number the operating system hands a program for each open file or connection. Each connection uses one, and the default limit per process is often low (a soft limit of 1,024 is common on Linux, though it varies by system and configuration), so it must be raised well above the cap.
- Ports. A server accepting connections on one port is not limited to about 64 thousand connections, because each connection is identified by four values together: the client's address and port and the server's address and port, so many clients can share the server's one port. The port limit applies to a client or a proxy opening many connections to one destination.
- Reconnect storms. When a server dies, its 83,333 clients reconnect at nearly the same time, and each reconnect pays a TLS handshake (the exchange at the start of a connection that sets up the encryption keys) and an authentication call. This burst is called a reconnect storm. If the 83,333 clients spread their reconnects over one minute, that is about 1,389 handshakes per second, so backend capacity for handshakes and authentication is a separate number to size. A load balancer or proxy (a server in front that accepts client connections and forwards them) can end TLS for you, which moves this work and the 20 KiB of TLS state off the connection servers.
The judgment
Provision about 48 connection servers (40 at the cap plus 20 percent spare), each carrying about 83,333 connections and about 3.5 GiB of connection state, so a machine with 8 to 16 GiB of memory is enough rather than 64 GiB: 3.5 GiB of connection state plus an assumed 2 GiB for the operating system and the server program is 5.5 GiB, and 8 GiB leaves 2.5 GiB spare for bursts and for taking over a failed neighbour's connections. The machine count is a decision about failure blast radius (how many users one dead server disconnects) more than about resources. What would flip it: a much larger per-connection cost that makes memory the binding count (with 64 GiB machines at 75 percent usable, memory needs more than 40 servers only above about 500 KiB per connection, which is thread-per-connection or very large pre-allocated buffers, not 100 KiB); heavier traffic per connection (the CPU count passes 40 only above about 30 messages a minute per connection at 50,000 message-equivalents per second per server, or about 12 a minute if a server handles only 20,000, so at the 10 messages a minute top of the assumed range the CPU count is 14 and the cap still decides: 4,000,000×10/60=666,667 plus 26,667 is 693,333, divided by 50,000 is 13.9); or a faster recovery path that lets you raise the cap, which shrinks the fleet directly (250,000 gives 20 servers).
Common mistakes
- Sizing from DAU instead of peak concurrency.
- Counting only the application's state and forgetting kernel buffers and TLS.
- Taking the memory-bound or CPU-bound count (4 servers) as the answer without a failure-domain limit.
- Mixing KiB and KB, or GiB and GB, between the per-connection and per-server figures.
- Assuming the roughly 64 thousand port limit caps a server's connections.
Running the code
Python 3.12, standard library only.
python connection_sizing.py
An application emits 2 billion events a day, averaging 1 KB each, into a log-based message broker such as Kafka. Estimate the peak ingest throughput, the number of partitions needed if one consumer handles about 5 MB/s, and the disk needed for 7 days of retention with a replication factor of 3.
Sample Answer
The idea in plain words
A log-based message broker such as Kafka stores each stream of events as an append-only log (new events are added at the end and never edited in place) split into partitions (independent slices of the stream, each written in order). A consumer group is a set of consumers that share one stream: each partition is read by exactly one member of the group at a time, and a second, independent group gets its own full read of the stream. A broker is one server in the cluster. Three quantities size it: ingest throughput (bytes arriving per second, which decides network and write load), the partition count (which caps how many consumers can read in parallel), and disk (events kept for the retention period, multiplied by the replication factor, which is the number of brokers holding a copy of each partition: one is the leader copy, which takes the writes, and the others are follower copies that replicate it, so a factor of 3 means one leader and two followers). The insight is that the three answers come from three different constraints: throughput sets partitions, retention times replication sets disk, and nothing about the event count alone tells you which one is tight.
Method, in the order you would do it
- Average rate. events per second=86,400events per day and MB per second=events per second×bytes per event÷106
- Peak rate. Multiply the average by an assumed peak-to-average ratio (how much busier the busiest period is than the mean). Here 3, with a plausible range of 2 to 5.
- Partitions. Because one consumer handles about 5 MB/s, the minimum is ⌈5peak MB per second⌉ where the brackets mean round up. For example, with 14 partitions up to 14 consumers in a group read in parallel, one partition each, at about 5 MB/s apiece, 70 MB/s together, just above a 69.4 MB/s peak. Then add headroom: after an outage consumers have a backlog to drain while new events keep arriving, and a group that reads at exactly the incoming rate never catches up, so it needs to read faster (1.5 times the peak means half again as much capacity as the incoming rate).
- Disk. raw TB=TB per day×retention days×replication factor then divide by the fraction of each disk you are willing to fill.
- Spread evenly. Round the partition count up to a multiple of the broker count, so no broker carries more partitions, and therefore more load, than another.
- Sanity-check the results against per-partition rates and broker counts.
Assumptions
| Input | Value | Plausible range |
|---|---|---|
| Events per day | 2 billion | given |
| Event size | 1 KB, taken as 1,000 bytes | given (1,024 bytes would add 2.4 percent) |
| Peak-to-average ratio | 3 | 2 to 5 |
| Consumer speed | 5 MB/s | given |
| Backlog headroom | 1.5 times the peak | 1.2 to 2 |
| Retention | 7 days | given |
| Replication factor | 3 | given |
| Disk fill limit | 70 percent | 60 to 80 percent (a full disk blocks writes and slows recovery) |
| Usable disk per broker | 8 TB | assumption; varies with hardware |
Units are decimal: 1 MB is 1,000,000 bytes and 1 TB is 1012 bytes. Event size is taken as the size on disk, so compression, if any, is treated as a separate lever.
Worked example, computed by a program
import math
# Assumptions (ranges in comments)
events_per_day = 2_000_000_000 # given
event_bytes = 1_000 # given: 1 KB, taken as 1,000 bytes (1,024 would add 2.4%)
peak_multiple = 3 # assumption: peak = 3 x daily average (range 2 to 5)
consumer_mb_s = 5 # given: one consumer handles about 5 MB/s
catchup_headroom = 1.5 # assumption: consumers must run 1.5x peak to drain a backlog (range 1.2 to 2)
retention_days = 7 # given
replication = 3 # given
disk_fill_limit = 0.70 # assumption: keep disks at most 70% full (range 0.6 to 0.8)
broker_disk_tb = 8 # assumption: usable disk per broker, TB
sec = 86_400
avg_events_s = events_per_day / sec
avg_mb_s = avg_events_s * event_bytes / 1e6
peak_mb_s = avg_mb_s * peak_multiple
min_partitions = math.ceil(peak_mb_s / consumer_mb_s)
planned = math.ceil(peak_mb_s * catchup_headroom / consumer_mb_s)
daily_tb = events_per_day * event_bytes / 1e12
retained_tb = daily_tb * retention_days
raw_tb = retained_tb * replication
provisioned_tb = raw_tb / disk_fill_limit
brokers_by_disk = math.ceil(provisioned_tb / broker_disk_tb)
planned_even = math.ceil(planned / brokers_by_disk) * brokers_by_disk # same partition count per broker
cluster_in_mb_s = peak_mb_s * replication # leader write + 2 follower copies, summed over the cluster
print(f"events/s average : {avg_events_s:,.0f}")
print(f"ingest MB/s avg, peak : {avg_mb_s:.1f}, {peak_mb_s:.1f}")
print(f"partitions, minimum : {min_partitions} (peak / {consumer_mb_s} MB/s)")
print(f"partitions, with headroom: {planned}, rounded to {planned_even} for {brokers_by_disk} brokers")
print(f"data per day, TB : {daily_tb:.1f}")
print(f"retained {retention_days} days, 1 copy : {retained_tb:.1f} TB")
print(f"x{replication} replication : {raw_tb:.1f} TB")
print(f"at {disk_fill_limit:.0%} full limit : {provisioned_tb:.1f} TB -> {brokers_by_disk} brokers of {broker_disk_tb} TB")
print(f"cluster write MB/s at peak: {cluster_in_mb_s:.1f} (all copies)")
print("sensitivity of raw retained TB:")
for days, rf, label in ((3, 3, "3 days"), (7, 3, "7 days"), (7, 2, "7 days, RF 2"), (14, 3, "14 days")):
print(f" {label:<12} -> {events_per_day*event_bytes*days*rf/1e12:.1f} TB")
print("sensitivity of minimum partitions to peak multiple:")
for m in (2, 3, 5):
print(f" x{m} -> {math.ceil(avg_mb_s*m/consumer_mb_s)}")
# Independent recomputation: sum the retained bytes day by day, and rebuild the peak from events per second
bytes_window = sum(events_per_day * event_bytes for _ in range(retention_days)) * replication
peak_b = (events_per_day / sec) * event_bytes * peak_multiple / (1000 * 1000)
ok = (abs(bytes_window / 1e12 - raw_tb) < 1e-9
and abs(peak_b - peak_mb_s) < 1e-9
and math.ceil(peak_b / consumer_mb_s) == min_partitions)
print("check (day-by-day sum):", "PASS" if ok else "FAIL")
Output:
events/s average : 23,148
ingest MB/s avg, peak : 23.1, 69.4
partitions, minimum : 14 (peak / 5 MB/s)
partitions, with headroom: 21, rounded to 24 for 8 brokers
data per day, TB : 2.0
retained 7 days, 1 copy : 14.0 TB
x3 replication : 42.0 TB
at 70% full limit : 60.0 TB -> 8 brokers of 8 TB
cluster write MB/s at peak: 208.3 (all copies)
sensitivity of raw retained TB:
3 days -> 18.0 TB
7 days -> 42.0 TB
7 days, RF 2 -> 28.0 TB
14 days -> 84.0 TB
sensitivity of minimum partitions to peak multiple:
x2 -> 10
x3 -> 14
x5 -> 24
check (day-by-day sum): PASS
Reading the output:
- Peak ingest. 2,000,000,000 / 86,400 is 23,148 events per second, or 23.1 MB/s on average. At 3 times that, peak ingest is 69.4 MB/s (about 556 Mbit/s, multiplying bytes by 8).
- Partitions. 69.4/5=13.9, so the minimum is 14. With 1.5 times headroom the need is 21, which rounds up to 24 so that each of the 8 brokers holds the same number of partitions (3). With 21, the split cannot be equal (21=2×8+5: five brokers would hold 3 and three would hold 2), and a broker with 3 partitions carries 50 percent more than one with 2.
- Disk. 2.0 TB per day, 14.0 TB for 7 days, 42.0 TB with three copies. Filling disks only to 70 percent means provisioning 60.0 TB, which is 8 brokers of 8 TB.
- Cluster-wide write load. Every byte is written three times, once to the leader and once to each of two followers, so the cluster as a whole absorbs 3×69.4=208.3 MB/s of writes at peak. Of that, 2×69.4=138.9 MB/s travels between brokers as follower copies. Consumer reads (egress, data leaving the brokers) come on top of this.
Sanity checks
- Per-partition load. At 24 partitions, the peak is 69.4/24≈2.9 MB/s per partition, below the 5 MB/s a consumer handles, so a consumer has room to catch up. This assumes keys spread events evenly across partitions; a few very busy keys make some partitions much hotter than the average.
- Disk and partitions agree on the broker count. 8 brokers by disk and 24 partitions give 3 partitions each. If disk had asked for 7 brokers, 24 would not divide evenly, which is the reason to round.
- Retention is the lever on disk. The sensitivity lines show 3 days at 18.0 TB, 14 days at 84.0 TB, and replication factor 2 at 28.0 TB. Those are linear in each input, so a quick doubling check is available in the room.
The judgment
Recommend 24 partitions on 8 brokers, about 60 TB provisioned. The minimum of 14 is the floor if everything runs perfectly; the extra headroom is cheap compared with changing the partition count later, because adding partitions changes which partition a given key maps to, which breaks per-key ordering for keyed streams. A key is a label such as a user id that the producer attaches to each event; events with the same key go to the same partition, and a partition keeps events in the order they were written, so one user's events stay in order. Kafka's default producer partitioner computes the murmur2 hash of the key's bytes, clears the sign bit so the value is non-negative, and takes it modulo the number of partitions (a producer can be configured with a custom partitioner instead). Other systems use their own hash, and some, such as Amazon Kinesis, map the hash onto ranges assigned to shards rather than taking a modulo, but a keyed partitioning scheme that depends on the partition count has the same consequence when that count changes. Take a made-up hash value to see the effect: if a key hashes to 50, it goes to partition 50mod14=8 with 14 partitions but to partition 50mod24=2 with 24, so that user's old events sit in one partition and new events in another, and no consumer sees them in a guaranteed order.
What would change the answer:
- Peak multiple of 5 instead of 3 lifts the minimum to 24 partitions (see the sensitivity lines), so the headroom would be gone. Measure the real peak.
- Compression. Events with repetitive text often compress well, and a ratio of 2 to 1 would halve 42.0 TB to 21.0 TB. Measure on a real sample before relying on it.
- Consumer speed. If consumers do 2 MB/s because of heavy per-event work, the minimum becomes ⌈69.4/2⌉=35 partitions. The 5 MB/s figure is the input most worth checking.
- Multiple consumer groups. Each independent group reads the whole stream, so egress and broker read load grow with the number of groups, although partitions and disk do not.
Common mistakes
- Sizing partitions from the average rate and ignoring peak and catch-up.
- Forgetting that disk is multiplied by the replication factor, or filling disks to 100 percent.
- Mixing bits and bytes, or MB and MiB (the binary megabyte of 1,048,576 bytes), in the throughput figures.
- Treating the partition count as freely adjustable later.
- Stating one number without naming which constraint (consumer parallelism, disk, network) produced it.
Running the code
Python 3.12, standard library only.
python broker_sizing.py
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
Unlock Full Question Bank
Get access to all 9 Estimation and Capacity Sizing interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.