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.
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.
You are onboarding a 5 TB per day event stream into an analytics platform. Estimate the storage, compute and monthly cost it implies. Tell me which assumptions you have to pin down first, how sensitive the estimate is to each, and how you would present the range and a contingency plan to the stakeholders funding it.
Sample Answer
The idea in plain words
An event stream turns into three costs: where the bytes live (storage), the machines that receive and write them as they arrive (ingest compute), and the machines that answer questions over them (query compute). Each cost is driven by a different assumption, so the first job is to say which assumptions you must pin down before the number means anything, then show how far the total moves when each one changes. The honest output is a base estimate with a range and a list of what would narrow it, not a single figure.
Conventions: decimal units (1 TB = 1,000 GB = 106 MB), a 730-hour month, and every price below is an assumed figure for illustration, not a quote.
Method
- Ingest rate: 5×106 MB/86,400 s=57.9 MB/s on average. Traffic is bursty, so assume the peak is 3x the average (plausible 2 to 5): 173.6 MB/s.
- Stored size: raw events compress when written to a columnar format (data stored by column, which compresses well). Assume 5x (plausible 3 to 10), so 1 TB is kept per day. With 90 days of queryable history (a business decision, plausible 30 to 365) that is 90 TB at steady state. Add a raw landing copy (the untouched, uncompressed events, kept briefly in cheap storage) for 3 days so that a parsing bug can be fixed and the events replayed, meaning re-processed from the original bytes: 3 x 5 TB = 15 TB.
- Storage cost: (90+15) TB×1000×USD 0.02=USD 2,100 per month, with the object-storage price assumed at USD 0.02 per GB-month (plausible 0.01 to 0.03).
- Ingest compute: one core handles about 10 MB/s of parse and write (plausible 5 to 30) and should run at no more than 60% at peak, so peak needs 173.6/(10×0.6)=28.9 cores. At an assumed USD 0.04 per core-hour (the price of one CPU core running for one hour; plausible 0.02 to 0.06) and 730 hours: 28.9×730×0.04=USD 845.
- Query compute: assume analysts scan 10 times one day's stored size per day (10 TB, plausible 2 to 50 times; for example 100 queries a day that each read about 100 GB of compressed data, a few days of one event type, add up to 10 TB), a core scans 50 MB/s (plausible 20 to 200), and the busy hour is 8x the daily average. Average cores: 10×106/50/86,400=2.3; at 8x peak that is 18.5 cores, costing 18.5×730×0.04=USD 541.
# Sizing a 5 TB/day event stream. Decimal units: 1 TB = 1,000 GB, 1 GB = 1,000 MB. 730-hour month (H_MONTH).
DAY_S = 86_400
H_MONTH = 730 # hours in a month (24 x 365 / 12)
BASE = dict(
raw_tb_day=5.0, # given
compression=5.0, # raw to stored columnar (plausible 3 to 10)
retention_days=90, # queryable history (plausible 30 to 365)
landing_days=3, # raw landing copy kept (plausible 1 to 7)
peak_mult=3.0, # peak ingest over average (plausible 2 to 5)
core_mb_s=10.0, # parse + write throughput per core (plausible 5 to 30)
ingest_util=0.6, # max sustained utilisation at peak
scan_mult=10.0, # compressed bytes scanned per day, as a multiple of one day's stored size (plausible 2 to 50)
scan_mb_s=50.0, # scan throughput per core (plausible 20 to 200)
query_peak=8.0, # busy-hour query load over the daily average (plausible 3 to 15)
usd_gb_month=0.02, # object storage, assumed price (plausible 0.01 to 0.03)
usd_core_hour=0.04, # compute, assumed price per core-hour (plausible 0.02 to 0.06)
)
def model(p):
avg_mb_s = p["raw_tb_day"] * 1e6 / DAY_S
peak_mb_s = avg_mb_s * p["peak_mult"]
ingest_cores = peak_mb_s / (p["core_mb_s"] * p["ingest_util"])
stored_tb_day = p["raw_tb_day"] / p["compression"]
stored_tb = stored_tb_day * p["retention_days"]
landing_tb = p["raw_tb_day"] * p["landing_days"]
storage_cost = (stored_tb + landing_tb) * 1000 * p["usd_gb_month"]
scan_mb_day = stored_tb_day * p["scan_mult"] * 1e6
avg_query_cores = scan_mb_day / p["scan_mb_s"] / DAY_S
query_cores = avg_query_cores * p["query_peak"]
ingest_cost = ingest_cores * H_MONTH * p["usd_core_hour"]
query_cost = query_cores * H_MONTH * p["usd_core_hour"]
return dict(avg_mb_s=avg_mb_s, peak_mb_s=peak_mb_s, ingest_cores=ingest_cores, stored_tb=stored_tb,
landing_tb=landing_tb, query_cores=query_cores, storage=storage_cost,
ingest=ingest_cost, query=query_cost, total=storage_cost + ingest_cost + query_cost)
b = model(BASE)
print(f"average ingest : {b['avg_mb_s']:.1f} MB/s ; peak {b['peak_mb_s']:.1f} MB/s")
print(f"stored (90 days) : {b['stored_tb']:.0f} TB ; raw landing {b['landing_tb']:.0f} TB")
print(f"ingest cores : {b['ingest_cores']:.1f} ; query cores {b['query_cores']:.1f}")
print(f"monthly cost USD : storage {b['storage']:,.0f} + ingest {b['ingest']:,.0f} + query {b['query']:,.0f} = {b['total']:,.0f}")
print("\none input at a time (monthly total USD)")
ranges = {"compression": (10, 3), "retention_days": (30, 365), "peak_mult": (2, 5), "scan_mult": (2, 50),
"usd_gb_month": (0.01, 0.03), "usd_core_hour": (0.02, 0.06), "core_mb_s": (30, 5)}
for k, (lo, hi) in ranges.items():
a = model({**BASE, k: lo})["total"]; c = model({**BASE, k: hi})["total"]
print(f"{k:15s} {lo:>6} -> {a:8,.0f} {hi:>6} -> {c:8,.0f} swing {abs(c-a):8,.0f}")
low = model({**BASE, "compression": 10, "retention_days": 30, "peak_mult": 2, "scan_mult": 2})["total"]
high = model({**BASE, "compression": 3, "retention_days": 365, "peak_mult": 5, "scan_mult": 50})["total"]
print(f"\nscenario range (several inputs together): low {low:,.0f} ; base {b['total']:,.0f} ; high {high:,.0f}")
every_low = model({**BASE, **{k: v[0] for k, v in ranges.items()}})["total"]
every_high = model({**BASE, **{k: v[1] for k, v in ranges.items()}})["total"]
print(f"all seven inputs in the table at their ends together: low {every_low:,.0f} ; high {every_high:,.0f}")
# independent recomputation: day-by-day stock of stored data and a per-TB-ingested route
stock_tb = 0.0
daily = BASE["raw_tb_day"] / BASE["compression"]
window = []
for day in range(400):
window.append(daily)
window = window[-BASE["retention_days"]:]
stock_tb = sum(window)
assert abs(stock_tb - b["stored_tb"]) < 1e-9, "stored size disagrees with day-by-day stock"
ingest_alt = (BASE["raw_tb_day"] * 1e6 / 24 / 3600 * BASE["peak_mult"]) / (BASE["core_mb_s"] * BASE["ingest_util"]) * H_MONTH * BASE["usd_core_hour"]
assert abs(ingest_alt - b["ingest"]) < 1e-6, "ingest cost disagrees"
print("checks passed")
Output:
average ingest : 57.9 MB/s ; peak 173.6 MB/s
stored (90 days) : 90 TB ; raw landing 15 TB
ingest cores : 28.9 ; query cores 18.5
monthly cost USD : storage 2,100 + ingest 845 + query 541 = 3,486
one input at a time (monthly total USD)
compression 10 -> 2,315 3 -> 5,046 swing 2,731
retention_days 30 -> 2,286 365 -> 8,986 swing 6,700
peak_mult 2 -> 3,204 5 -> 4,049 swing 845
scan_mult 2 -> 3,053 50 -> 5,649 swing 2,596
usd_gb_month 0.01 -> 2,436 0.03 -> 4,536 swing 2,100
usd_core_hour 0.02 -> 2,793 0.06 -> 4,178 swing 1,386
core_mb_s 30 -> 2,922 5 -> 4,331 swing 1,408
scenario range (several inputs together): low 1,217 ; base 3,486 ; high 18,381
all seven inputs in the table at their ends together: low 421 ; high 29,684
checks passed
Result and sensitivity
The base estimate is about USD 3,500 per month at steady state: storage 2,100, ingest 845, query 541. The first three months cost less because the 90-day history is still filling.
The one-at-a-time table changes one input to its low and high value while all others stay at base; the swing column is the high-case total minus the low-case total (as a positive number). It says what to pin down first, roughly in order of swing:
- Retention (swing USD 6,700): 30 versus 365 days. It is a business decision, so get it from the stakeholders before engineering anything.
- Compression ratio (swing USD 2,731): measure it by writing one real day of events in the target format; do not guess it.
- Query scan multiple (swing USD 2,596): how many times one day's stored size is read per day; it depends on how many dashboards and analysts exist, so ask for the top five workloads and estimate the bytes each reads per day.
- Unit prices (storage swing USD 2,100, compute USD 1,386): replace with the actual contract rates.
- Peak multiple and per-core throughput (swings USD 845 and USD 1,408): measure peak from a sample of the real stream.
Moving several inputs together gives a scenario range: low USD 1,217 (compression 10x, 30 days, peak 2x, scans 2x) and high USD 18,381 (compression 3x, 365 days, peak 5x, scans 50x). Unit prices and per-core throughput stay at base in this range, because the contract rates are looked up and throughput is measured in an hour of benchmarking; moving all seven table inputs to their ends together gives USD 421 to USD 29,684. These are corner cases chosen to bracket the base, not a probability interval.
Not included: the message queue or log in front of the platform (which holds data at its own replication factor), network transfer between zones, monitoring, support and engineering time. Say so when presenting, because a stakeholder will otherwise read the figure as the whole bill.
Presenting the range and the contingency plan
For the people funding it, one page. The sentences they would read:
"At steady state we expect about 3,500 dollars a month: 2,100 for storage, 845 for ingest machines and 541 for query machines. If the unit prices and machine speeds hold, then depending on how long you want data kept, how well it compresses, how bursty the stream is and how heavily analysts query it, the cost could land between about 1,200 and about 18,400 dollars; that range combines the cheapest and the costliest values of those four inputs, so landing at either end needs every one of them to go the same way at once, and prices and machine speeds could widen it further. Retention is the biggest lever and it is your decision. A two-week pilot on a tenth of the stream will replace our guesses on compression, peak load and query pattern with measurements, and we will bring back a narrower range before the full commitment."
Then the supporting points:
- The ask: approve the pilot and a base of about USD 3,500 per month. None of the unmeasured ranges gives a usable ceiling: the four-input high scenario is 18,381, about 5.3 times the base (18,381 / 3,486), and moving prices and machine speeds too reaches 29,684. So the funders set a provisional spending limit for the pilot period, and the ceiling is re-set after the pilot by re-running the model with measured values. The 80% budget alert and the kill switch below act on whichever limit is in force.
- The three drivers: retention, compression and query volume, with the decision or measurement that settles each and its date.
- The pilot: ingest 10% of the stream for two weeks. This measures the compression ratio, the peak multiple and the real query pattern, and replaces three assumptions with data before the full commitment.
- Contingency, in the order I would pull it: shorten hot retention and keep only aggregates beyond 30 days (cuts the largest driver); sample low-value event types at ingest; add a budget alert at 80% of the approved figure; keep a kill switch (a pre-agreed switch that takes effect automatically or with one command) that drops ingestion to sampled mode (keeping only a fixed fraction of events, for example 1 in 10) if spend exceeds the limit in force.
Common mistakes
- Sizing compute for the average ingest rate instead of the peak.
- Forgetting that stored size is raw size divided by compression, or storing raw bytes for the whole retention window.
- Presenting one number with no range, or a range from moving every input at once without saying so.
- Leaving out the surrounding cost (queue, network, monitoring) and letting the estimate be read as the total.
Running the code
Python 3.12, standard library only. Save the listing as stream_sizing.py and run python stream_sizing.py. It ends with checks passed when a day-by-day stock of stored data and a second route to the ingest cost match the model; shortening the retention window in the check by one day makes it fail.
You are sizing a new messaging feature for a product with 10M monthly active users. Assume each active user has about 30 sessions a month and each session makes about 10 requests, and that at the busiest moment roughly 0.5% of active users are concurrently active. Walk through your estimate of average and peak requests per second, state the assumptions you are least sure of, and explain how you would validate the numbers against telemetry once the feature is in beta.
Sample Answer
The idea in plain words
Requests per second (RPS) is how many requests reach your servers each second. The average RPS is just total requests divided by total seconds, but servers are sized for the peak, the busiest moment, because that is when they fail. The stated inputs give the average directly. For the peak they give how many people are online at once (0.5% of 10M monthly active users, MAU; here "concurrently active" is read as "online in a session at the same moment") but not how fast each of them sends requests. The missing link is session length: a session is one visit, and if a visit sends 10 requests over T seconds, each online user sends 10/T requests per second. So session length is the assumption to pin down first, and the inputs themselves bound it.
Method
- Average RPS from monthly totals (30-day month, 86,400 seconds per day):
where M = 10M MAU, s = 30 sessions per user per month, r = 10 requests per session.
-
Peak concurrent users: C=0.005×10,000,000=50,000 (the given 0.5%).
-
Peak RPS (the average over the busiest minute):
with T the session length in seconds. This is an assumption, here 180 seconds (3 minutes, plausible range 60 to 420).
-
Cross-check with Little's law (the average number of users in a system equals the arrival rate times how long each stays: L=λW). Sessions start at λ=Ms/(30×86,400) per second, so the average number online is λT. The busiest moment cannot have fewer people online than the average moment, so C≥λT. In words: if sessions start at λ per second and each lasts T seconds, then on average λT people are online at any instant (a shop that gets 2 customers a minute who each stay 5 minutes holds about 10 customers on average). Requiring C≥λT and dividing by λ gives T≤C/λ, so the stated peak share caps how long a session can be.
-
Burst allowance: the busiest single second is higher than the busiest-minute average. Assume a factor of 2 (plausible 1.5 to 4) and state it.
Worked example with the numbers
Monthly requests are 10,000,000×30×10=3,000,000,000. Divided by 30×86,400=2,592,000 seconds, the average is 1,157.4 RPS. At T=180 s, a user online sends 10/180=0.0556 requests per second, so the peak is 50,000×0.0556=2,778 RPS, which is 2.40 times the average. The program below reproduces these and varies T.
from fractions import Fraction
MAU = 10_000_000 # given: monthly active users
SESSIONS_PER_USER = 30 # given: sessions per active user per month
REQ_PER_SESSION = 10 # given: requests per session
PEAK_SHARE = 0.005 # given: share of MAU concurrently active at the busiest moment
SESSION_SECONDS = 180 # assumption: session length, plausible range 60 to 420
BURST = 2.0 # assumption: busiest second vs busiest-minute average, plausible 1.5 to 4
DAYS = 30 # convention: 30-day month
DAY_S = 86_400
def model(session_s):
monthly_requests = MAU * SESSIONS_PER_USER * REQ_PER_SESSION
avg_rps = monthly_requests / (DAYS * DAY_S)
sessions_per_s = MAU * SESSIONS_PER_USER / (DAYS * DAY_S)
avg_concurrent = sessions_per_s * session_s # Little's law: L = lambda * W
peak_concurrent = MAU * PEAK_SHARE
peak_rps = peak_concurrent * REQ_PER_SESSION / session_s
return avg_rps, avg_concurrent, peak_concurrent, peak_rps
avg_rps, avg_conc, peak_conc, peak_rps = model(SESSION_SECONDS)
print(f"monthly requests : {MAU*SESSIONS_PER_USER*REQ_PER_SESSION:,}")
print(f"average RPS : {avg_rps:,.1f}")
print(f"average concurrent : {avg_conc:,.0f}")
print(f"peak concurrent : {peak_conc:,.0f}")
print(f"peak RPS (minute mean): {peak_rps:,.0f}")
print(f"peak / average : {peak_rps/avg_rps:.2f}x")
print(f"burst-second RPS : {peak_rps*BURST:,.0f}")
print("\nsensitivity to session length")
print("session_s avg_conc peak_conc peak_rps peak/avg consistent")
for s in (60, 180, 300, 420, 600, 1800):
a, ac, pc, pr = model(s)
print(f"{s:9d} {ac:9,.0f} {pc:10,.0f} {pr:9,.0f} {pr/a:8.2f}x {'yes' if pc >= ac else 'NO'}")
max_session = PEAK_SHARE * MAU / (MAU * SESSIONS_PER_USER / (DAYS * DAY_S))
print(f"\nlongest session compatible with the 0.5% peak: {max_session:.0f} s")
# checks
exact_avg = Fraction(MAU * SESSIONS_PER_USER * REQ_PER_SESSION, DAYS * DAY_S)
assert abs(float(exact_avg) - avg_rps) < 1e-6, "average RPS mismatch"
per_day = MAU * SESSIONS_PER_USER * REQ_PER_SESSION / DAYS
assert abs(per_day / DAY_S - avg_rps) < 1e-6, "daily route disagrees"
assert peak_conc >= avg_conc, "peak concurrency below average concurrency"
print("checks passed")
Output:
monthly requests : 3,000,000,000
average RPS : 1,157.4
average concurrent : 20,833
peak concurrent : 50,000
peak RPS (minute mean): 2,778
peak / average : 2.40x
burst-second RPS : 5,556
sensitivity to session length
session_s avg_conc peak_conc peak_rps peak/avg consistent
60 6,944 50,000 8,333 7.20x yes
180 20,833 50,000 2,778 2.40x yes
300 34,722 50,000 1,667 1.44x yes
420 48,611 50,000 1,190 1.03x yes
600 69,444 50,000 833 0.72x NO
1800 208,333 50,000 278 0.24x NO
longest session compatible with the 0.5% peak: 432 s
checks passed
Reading the table: the 0.5% concurrency figure and 30 sessions per month together force sessions to be short. A 10-minute session would put the average number online (69,444) above the stated peak (50,000), which is a contradiction, so either the 0.5% or the session length is wrong. Within the consistent range (about 1 to 7 minutes) the peak runs from 1,190 to 8,333 RPS, a 7x spread caused by one unmeasured number. That is why session length is the assumption to validate first.
Judgment: what to plan for
Plan the load balancer, API tier and database around about 2,800 RPS as the busiest-minute figure and 5,556 RPS as the busiest-second figure (2,778 x 2). Add about 50% headroom for growth and uneven days, which gives roughly 8,300 RPS (5,556 x 1.5 = 8,334) as the capacity to confirm in a load test. If the real session is 1 minute rather than 3, the busiest-minute figure triples to 8,333 RPS (the 60-second row of the table). That is a different quantity from the 8,334 headroom target above, which is the 3-minute estimate with burst and growth added; the two land close together only by coincidence of arithmetic. Run the load test at both, because the 1-minute case has to be ruled out before launch. A load test replays synthetic traffic at a chosen rate against a copy of the system to see where it slows or fails; the load balancer is the front component that spreads requests across servers, and the API tier is the group of servers that handle them.
Assumptions to trust least
| Assumption | Why it is shaky | Effect if wrong |
|---|---|---|
| Session length 180 s | Not given; only bounded by the 0.5% consistency check | Peak moves 1,190 to 8,333 RPS |
| All 10M MAU use messaging | Feature adoption is usually a fraction of MAU | Scales both average and peak linearly down |
| 30 sessions and 10 requests are means | Heavy users send far more, and they dominate the peak | Peak understated if the mix is skewed |
| 0.5% concurrent at the busiest moment | Depends on time zones and on whether it is a share of MAU or daily actives | Scales peak linearly |
| Requests spread evenly in a session | Opening a chat can fire a burst, and polling or push connections add traffic | Burst factor 2 may be too low |
Validating against telemetry in beta
Measure each assumption separately instead of comparing only the final RPS:
Telemetry means the usage data the running feature records about itself (request logs, session start and end events, counters).
- Session length and requests per session: log session start and end and the request count per session; use the median and the 95th percentile (P95, the value that 95% of sessions fall below, so it shows the long ones the mean hides), not just the mean.
- Concurrency: count distinct users with a request in each minute, across a full week including weekends.
- Peak RPS and burst: take per-second request counts from load balancer logs (the access records the front component keeps for every request it forwards) and compute the ratio of the busiest second to the busiest-minute mean.
- Scaling to 10M: beta users are early adopters and usually heavier than the average user. Convert to per-active-user rates, then multiply by the projected active population from the adoption plan, instead of extrapolating raw beta RPS.
An illustrative rule: if a measured rate is within about 30% of the estimate, keep the plan; if it is off by 2x or more, re-derive the number and re-run the load test.
Common mistakes
- Sizing for the average (1,157 RPS) when the busiest-minute load is 2.4 times that.
- Forgetting that 86,400 seconds per day times 30 is the month, or mixing sessions per month with requests per month.
- Treating the peak concurrent share as independent of session length and not noticing the contradiction for long sessions.
Running the code
Python 3.12, standard library only. Save the listing as rps_estimate.py and run python rps_estimate.py. It prints the table above and ends with checks passed if the independent recomputation (exact fractions, and a per-day route) and the peak-above-average check hold; a session length of 1,800 seconds makes the last check fail.
Estimate the monthly storage cost per active user for a photo-sharing app where the average user stores 200MB of photos and object storage costs $0.02 per GB-month. Show your unit conversions and say which overheads (metadata, backups, replication) would move the number most.
Sample Answer
The idea in plain words
Object storage (a service that keeps files as named objects behind a web API, and is billed by the amount stored) is priced per gigabyte per month (GB-month): you pay the price once for each gigabyte you keep for a month. So the cost per user is just their gigabytes times the price. The only trap is the unit: the user's data is in megabytes and the price is in gigabytes, so convert first.
Method and unit conversion
Using decimal units (1 GB = 1,000 MB), the convention taken for this estimate. Providers differ: Amazon S3, for example, bills in binary gigabytes (1 GB = 2^30 bytes, a gibibyte), so read the unit definition on your provider's price list:
200 MB=1000200 GB=0.2 GB 0.2 GB×GB-monthUSD 0.02=USD 0.004 per user per monthThat is 0.4 cents per user per month, or USD 4 per month for 1,000 users. If you work in binary units (1 GiB = 1,024 MiB) the same 200 MiB is 0.1953 GiB and costs USD 0.00391, a 2.3% difference. State which one you use; the gap is small next to the overheads below.
# Storage cost per active user. Decimal units: 1 GB = 1,000 MB.
PRICE_GB_MONTH = 0.02 # given, USD per GB-month
USER_MB = 200 # given: average stored per active user
base = USER_MB / 1000 * PRICE_GB_MONTH
print(f"200 MB = {USER_MB/1000:.3f} GB (decimal); cost = USD {base:.4f} per user-month ({base*100:.2f} cents)")
print(f"same 200 MiB in GiB : {USER_MB/1024:.4f} GiB -> USD {USER_MB/1024*PRICE_GB_MONTH:.5f} (a {1-1000/1024:.1%} gap)")
PHOTO_MB = 2.0 # assumption: average photo, so 100 photos per user
PHOTOS = USER_MB / PHOTO_MB
META_KB = 1.0 # assumption: database row per photo (plausible 0.5 to 5 KB)
meta_mb = PHOTOS * META_KB / 1000
print(f"\nphotos per user {PHOTOS:.0f}; metadata {meta_mb:.2f} MB = {meta_mb/USER_MB:.2%} of the photo bytes")
print(f"even priced like object storage, metadata adds USD {meta_mb/1000*PRICE_GB_MONTH:.6f} per user-month")
# overheads as multipliers on the 200 MB (assumptions, with plausible ranges)
scenarios = [
("photos only, provider-managed durability", 1.0),
("+ thumbnails at 10%", 1.10),
("+ thumbnails + 1 backup copy", 1.10 * 2),
("+ thumbnails + 1 backup + 1 cross-region copy", 1.10 * 3),
("self-managed 3x replication, no thumbnails", 3.0),
]
print("\nscenario multiplier USD per user-month")
for name, k in scenarios:
print(f"{name:48s} {k:8.2f} {base*k:12.5f}")
# independent route: cost per 1,000 users and per user, from bytes
users = 1000
total_gb = users * USER_MB / 1000
assert abs(total_gb * PRICE_GB_MONTH / users - base) < 1e-12, "routes disagree"
assert abs(base - 0.004) < 1e-12, "expected 0.004 dollars per user-month"
print("\nchecks passed")
Output:
200 MB = 0.200 GB (decimal); cost = USD 0.0040 per user-month (0.40 cents)
same 200 MiB in GiB : 0.1953 GiB -> USD 0.00391 (a 2.3% gap)
photos per user 100; metadata 0.10 MB = 0.05% of the photo bytes
even priced like object storage, metadata adds USD 0.000002 per user-month
scenario multiplier USD per user-month
photos only, provider-managed durability 1.00 0.00400
+ thumbnails at 10% 1.10 0.00440
+ thumbnails + 1 backup copy 2.20 0.00880
+ thumbnails + 1 backup + 1 cross-region copy 3.30 0.01320
self-managed 3x replication, no thumbnails 3.00 0.01200
checks passed
Which overheads move the number
The base figure counts only the photo bytes. Each overhead is a multiplier on the bytes you actually pay for:
| Overhead | Typical size (assumption) | Effect on USD 0.004 |
|---|---|---|
| Metadata (a database row per photo) | About 1 KB per photo, so 0.10 MB for 100 photos of 2 MB | Negligible: 0.05% of the photo bytes |
| Thumbnails and other derived sizes | About 10% of the originals | x 1.1, so USD 0.0044 |
| Backups | One extra full copy doubles the bytes | x 2 on top, USD 0.0088 with thumbnails |
| Replication | See the note below | x 3 if you store three copies yourself, USD 0.012 |
A cross-region copy (a copy kept in a data centre in a different geographic region, so one regional outage cannot destroy every copy) on top of the backup (three full copies of the photos and thumbnails) gives USD 0.0132. Derived files are the thumbnails and resized versions the app generates from each original; they are stored too, so they are billed too. The program above prints these rows.
Note on replication: a managed object store's price per GB-month is normally charged on the logical bytes you store, with its internal durability copies included in that price (durability means the stored data survives disk and server failures without being lost, which the provider achieves by keeping several internal copies or parity data), so you would not multiply by 3 for it (check your provider's pricing page). You do multiply when you keep your own extra copies: backups, a second region, or a self-run storage cluster that replicates three times.
Judgment
Quote USD 0.004 per user per month as the floor, and about USD 0.009 to 0.013 as the realistic range once thumbnails and one or two extra full copies are counted (the 0.0088 and 0.0132 rows of the program output). The movers are the number of full copies you keep and derived files; metadata is noise. Also say what the denominator is: this is per active user, but inactive users' photos still sit in storage, so the fleet cost divided by active users is higher than this figure. Retrieval and request fees, which depend on how often photos are opened, are separate and not included.
Common mistakes
- Treating 200 MB as 200 GB, or forgetting the divide by 1,000, which is off by three orders of magnitude.
- Applying a 3x replication factor to a managed object store whose price already covers its internal durability.
- Counting metadata as a major cost when it is a fraction of a percent of photo bytes.
- Mixing a per-month price with a per-year budget.
Running the code
Python 3.12, standard library only. Save the listing as storage_per_user.py and run python storage_per_user.py. It ends with checks passed when a second route from total gigabytes for 1,000 users matches the per-user figure of USD 0.004.
A relational database holds 30 TB today, grows by 50 GB a day and must absorb 40,000 writes per second at peak. If one node comfortably handles 5,000 writes per second and 4 TB of data, estimate how many shards you need today and in two years, and which constraint drives the number.
Sample Answer
The idea in plain words
A shard is one horizontal slice of a database: each shard holds a different subset of the rows and runs on its own primary node (the node that accepts the writes for that shard; replicas are copies of it kept for availability), so adding shards adds both storage room and write capacity. A node has two limits at once: how much data it can hold (4 TB here) and how many writes per second it can absorb (5,000 here). The number of shards is the larger of the two counts, and the constraint that produces the larger count is the one that drives the design. Here the two counts tie today at 8, but data grows and writes (as stated) do not, so storage takes over within weeks and is what sets the two-year number.
Method, in the order you would do it
- Count shards for each constraint separately. shards by data=⌈4data in TB⌉shards by writes=⌈5,000peak writes per second⌉ The brackets mean round up, because you cannot buy part of a node.
- Take the maximum. The shard count is the larger of the two.
- Project the inputs forward. Data in two years is 30+50 GB per day×730 days÷1000=66.5 TB (decimal units, 1 TB is 1,000 GB). The question gives no growth rate for writes, so treat peak writes as flat and test growth as a scenario.
- Add a buffer. "Comfortably handles" is a design figure, but real data and traffic are not spread perfectly evenly across shards. A buffer (1.25 times is assumed here, with a plausible range of 1.1 to 1.5) covers uneven spread and growth between hardware purchases. It is applied to the data count and to the write count separately because each limit can be hit separately: skew (some shards getting more data or traffic than others) can fill one shard's disk while another stays half empty, and a busy key can saturate one shard's write capacity while the others idle.
- Say which constraint binds, and when it changes.
Worked example, computed by a program
The program evaluates the five cases, finds the day each shard count is first needed by stepping through the days in whole gigabytes, and compares that with a closed-form calculation.
import math
# Given
data_now_tb = 30
growth_gb_per_day = 50
writes_peak_now = 40_000
node_writes = 5_000
node_tb = 4
# Assumptions
days = 730 # two years
write_growth_2y = 1.0 # peak writes in two years / today (1.0 = flat; range 1 to 3)
headroom = 1.25 # skew and growth buffer on the binding limit (range 1.1 to 1.5)
def shards(data_tb, writes, buffer=1.0):
by_data = math.ceil(data_tb * buffer / node_tb)
by_writes = math.ceil(writes * buffer / node_writes)
return by_data, by_writes, max(by_data, by_writes)
data_2y_tb = data_now_tb + growth_gb_per_day * days / 1000
print(f"data in 2 years, TB : {data_2y_tb:.1f}")
print(f"{'case':<28}{'by data':>8}{'by writes':>10}{'shards':>8}")
cases = [
("today, no buffer", data_now_tb, writes_peak_now, 1.0),
("2 years, writes flat", data_2y_tb, writes_peak_now * write_growth_2y, 1.0),
("2 years, writes x2.2", data_2y_tb, writes_peak_now * 2.2, 1.0),
(f"today, {headroom}x buffer", data_now_tb, writes_peak_now, headroom),
(f"2 years flat, {headroom}x buffer", data_2y_tb, writes_peak_now, headroom),
]
for name, d, w, b in cases:
bd, bw, n = shards(d, w, b)
print(f"{name:<28}{bd:>8}{bw:>10}{n:>8}")
capacity_tb = 8 * node_tb
print(f"days until 8 shards are full by data: {(capacity_tb - data_now_tb) * 1000 / growth_gb_per_day:.0f}")
print("sensitivity of 2-year shards (no buffer, writes flat) to growth per day:")
for g in (25, 50, 100):
d = data_now_tb + g * days / 1000
print(f" {g:>3} GB/day -> data {d:.1f} TB -> {math.ceil(d / node_tb)} shards")
# Independent recomputation: walk the days in whole GB and find when each shard count is first needed
need = {}
for day in range(0, days + 1):
data_gb = data_now_tb * 1000 + growth_gb_per_day * day
n = max(math.ceil(data_gb / (node_tb * 1000)), math.ceil(writes_peak_now / node_writes))
need.setdefault(n, day)
first_day_9 = (capacity_tb - data_now_tb) * 1000 // growth_gb_per_day + 1 # closed form
ok = (max(need) == shards(data_2y_tb, writes_peak_now)[2] and need[9] == first_day_9 and need[8] == 0)
print("first day each count is needed:", {k: need[k] for k in (8, 9, 10, 17)})
print("check (day-by-day walk vs closed form):", "PASS" if ok else "FAIL")
Output:
data in 2 years, TB : 66.5
case by data by writes shards
today, no buffer 8 8 8
2 years, writes flat 17 8 17
2 years, writes x2.2 17 18 18
today, 1.25x buffer 10 10 10
2 years flat, 1.25x buffer 21 10 21
days until 8 shards are full by data: 40
sensitivity of 2-year shards (no buffer, writes flat) to growth per day:
25 GB/day -> data 48.2 TB -> 13 shards
50 GB/day -> data 66.5 TB -> 17 shards
100 GB/day -> data 103.0 TB -> 26 shards
first day each count is needed: {8: 0, 9: 41, 10: 121, 17: 681}
check (day-by-day walk vs closed form): PASS
Reading the output:
- Today. 30 TB / 4 TB is 7.5, rounded up to 8. 40,000 / 5,000 is exactly 8. The two constraints tie at 8 shards, which means that at 8 shards writes sit at 100 percent of the stated comfortable rate and data at 30/32=93.75 percent of capacity. There is no slack on either.
- Why storage takes over immediately. Eight shards hold 32 TB, so with 50 GB arriving each day they are full after (32−30)×1000/50=40 days, and a ninth shard is needed on day 41 (the day-by-day walk finds the same day). Writes do not move unless they grow.
- In two years. 66.5 TB / 4 TB is 16.6, so 17 shards by data against 8 by writes. Storage drives the number.
- When writes would take over. 17 shards absorb 17×5,000=85,000 writes per second, which is 2.125 times today's peak. If peak writes grew faster than that, writes would drive. With writes growing 2.2 times (roughly in line with data, since 66.5/30≈2.2), the write count is 18 and edges ahead of the data count of 17.
- With the buffer. Applying 1.25 times to both gives 10 shards today and 21 in two years.
The judgment
Plan for roughly 10 primary shards now and 21 in two years, with storage as the driver. In an interview the commitments are:
- Answer both asks. Today: 8 minimum, 10 with a buffer, and the constraint is a tie that storage breaks within weeks. Two years: 17 minimum, 21 with a buffer, and storage drives.
- Design the shard map for growth. Hash the key into many fixed logical slots (for example 64 or 128), and assign slots to nodes with a lookup table, the shard map. Going from 10 to 21 nodes then means moving slots, not rehashing every row. For example, 64 slots on 10 nodes is 4 nodes with 7 slots and 6 nodes with 6 (4×7+6×6=64). On 21 nodes it is 20 nodes with 3 slots and one with 4 (20×3+4=64), so the 11 new nodes take about 33 slots, roughly half the slots, from the old nodes. Every key still hashes to the same slot as before; only the shard map changes, and only the rows in moved slots travel. Hashing the key straight to a node number (hash mod 10, then hash mod 21) would instead leave only about 1 key in 21 on its old node.
- Replication is separate. The counts above are primaries. Keeping, say, two replicas per shard for availability (copies of the shard's data on other machines, so it survives losing the primary) triples the machine count (30 today with the buffer) but adds no write capacity, because every write must still be applied on the primary.
- Cheaper levers than more shards. Because storage drives, archiving or compressing old rows lowers the count directly. If writes ever drive, batching writes or removing secondary indexes (extra lookup structures on columns other than the key, each of which must be updated on every write) lowers the per-write cost.
What would flip it: faster data growth (100 GB per day gives 103.0 TB and 26 shards in two years; 25 GB per day gives 13, per the sensitivity lines), or a write rate that grows faster than 2.125 times.
Common mistakes
- Giving only the writes figure (8) or only the data figure (8) and calling it done, instead of computing both and taking the maximum.
- Rounding down. 7.5 nodes means 8.
- Ignoring skew: one very popular key can saturate one shard even when the average is fine.
- Forgetting replicas when counting machines, or counting them as extra write capacity.
- Mixing TB and TiB, or assuming the stated per-node limits are hard ceilings rather than comfortable operating points.
Running the code
Python 3.12, standard library only.
python shard_sizing.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.