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.
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.
A social feed fans each new post out to every follower's timeline at write time. Users post 50 million times a day and the average poster has 200 followers, but a few accounts have tens of millions. Estimate the timeline writes per second and the storage they add per day, and show what the heavy-tailed follower counts do to the estimate.
Sample Answer
The idea in plain words
Fan-out on write means that when someone posts, the system immediately copies a small pointer to that post into the stored timeline (the list of posts a user sees) of every follower, so reading a timeline later is one cheap lookup. The cost moves to the write side: every post becomes as many timeline writes as the poster has followers. For example, a user with 3 followers posts once: the system writes 3 timeline entries, one per follower, each holding the follower's id and the post's id. That is 3 timeline writes. A post from an account with 30 million followers is 30 million of them. So the basic estimate is a product, timeline writes=posts×followers per post, and the question is which "followers per post" to use. A heavy-tailed distribution (most accounts small, a few enormous) makes the average a poor description of any single post: the mean is far above the median, a handful of accounts produce a large share of all writes, and one post from one of them is a burst of tens of millions of writes.
A tiny example shows why the mean misleads. Take five accounts, four with 10 followers and one with 1,000,000. The mean is (4×10+1,000,000)/5=200,008 followers, but the median (the middle account when sorted) is 10. The mean is dominated by the one large account and says nothing about a typical post.
Headline. The answer an interview asks for first is just posts times followers: 10 billion timeline writes a day, 115,741 per second. The log-normal model and the sampling simulation are deeper reading that show what the tail does to that headline.
Every input is an assumption with a plausible range, not a statistic about a real service.
Method
- Average case. writes per day=50,000,000×200=1010, then divide by 86,400 seconds for a rate.
- Peak. Multiply the average rate by an assumed peak-to-average ratio (how much busier the busiest period is than the mean): 3, range 2 to 5.
- Storage per day. bytes per day=writes per day×bytes per timeline entry where an entry is a user id, a post id and index overhead (32 bytes assumed, range 16 to 100). Replication multiplies this by the number of copies kept.
- Model the tail explicitly. Split the accounts into ordinary ones with a spread-out follower count and a few very large accounts, check what share of all writes the large ones produce, and size the burst of a single large post.
- Choose a policy for the large accounts and recompute.
Assumptions
| Input | Value | Plausible range |
|---|---|---|
| Posts per day | 50 million | given |
| Mean followers per posting account | 200 | given |
| Posting accounts | 5 million, each posting 10 times a day | the split of 50 million posts is an assumption |
| Very large accounts | 10, with 30 million followers each | 5 to 100 accounts, 10 to 100 million followers |
| Ordinary accounts | log-normal followers (a bell shape on a logarithmic scale, so most accounts are small and a few are much larger), spread parameter 1.5 | 1.0 to 2.0 |
| Peak-to-average ratio | 3 | 2 to 5 |
| Bytes per timeline entry | 32 (user id, post id and the extra bytes, called index overhead, the database adds to find the entry) | 16 to 100 |
| Fan-out cut-off in the hybrid policy (fan out on write for accounts below the cut-off; for accounts above it, store the post once and merge it into followers' timelines when they open them) | 1 million followers | 100 thousand to 5 million |
The question's "200" can be read two ways, and the program prints both. Reading A (the headline): 200 is the mean over all posting accounts, large ones included; this is the first row of the program's table. Ten accounts with 30 million followers contribute 10×30,000,000/5,000,000=60 of that mean, so the ordinary accounts average 140. Reading B: 200 is the average of the ordinary accounts and the large accounts come on top; this is the second row.
Why the ordinary accounts' median is 45.5 while their mean is 140: in a log-normal shape the logarithm of the follower count is bell-shaped, the median is eμ and the mean is eμ+σ2/2. With the spread parameter σ=1.5 the mean is e1.125=3.08 times the median, and 140/3.08=45.5. Half of the ordinary accounts have fewer than 46 followers, yet the mean is 140.
Worked example, computed by a program
The program prints the three cases and the burst of one large post (the part an interview asks for), then, as deeper reading, what a random sample of 10,000 accounts would have told you about the mean: the sampling part only shows that a small sample misses the celebrities. Its draws come from the hypergeometric distribution (the exact chance of drawing a given number of large accounts when sampling without replacement), are seeded, and are checked against the exact probability from scipy 1.14.1.
import math
import numpy as np
from scipy import stats
# Given
posts_per_day = 50_000_000
mean_followers = 200 # per posting account, counting every account
# Assumptions
accounts = 5_000_000 # posting accounts, each posting posts_per_day / accounts times a day
celebs = 10 # accounts with tens of millions of followers (range 5 to 100)
celeb_followers = 30_000_000 # followers per celebrity account (range 10M to 100M)
sigma = 1.5 # spread of the ordinary accounts (log-normal; range 1.0 to 2.0)
peak_multiple = 3 # peak = 3 x average (range 2 to 5)
entry_bytes = 32 # one timeline entry: user id, post id, index overhead (range 16 to 100)
hybrid_threshold = 1_000_000 # accounts above this are NOT fanned out; merged at read time
posts_each = posts_per_day / accounts
regular = accounts - celebs
regular_mean = (mean_followers * accounts - celebs * celeb_followers) / regular
mu = math.log(regular_mean) - sigma**2 / 2
regular_median = math.exp(mu)
def per_day(writes):
return writes, writes / 86_400, writes * peak_multiple / 86_400, writes * entry_bytes / 1e9
print(f"ordinary accounts: mean {regular_mean:.1f} followers, median {regular_median:.1f}")
print(f"celebrities: {celebs} x {celeb_followers:,} = {celebs*celeb_followers/1e6:.0f}M follower links "
f"= {celebs*celeb_followers/(mean_followers*accounts):.0%} of all links")
rows = [
("200 counts everyone", accounts * mean_followers * posts_each),
("200 is ordinary, celebs extra", regular * mean_followers * posts_each + celebs * celeb_followers * posts_each),
(f"hybrid (skip > {hybrid_threshold:,})", regular * regular_mean * posts_each),
]
print(f"{'case':<32}{'writes/day (B)':>15}{'avg /s':>10}{'peak /s':>10}{'GB/day':>9}")
for name, w in rows:
d, a, p, gb = per_day(w)
print(f"{name:<32}{d/1e9:>15.2f}{a:>10,.0f}{p:>10,.0f}{gb:>9,.0f}")
celeb_share = celebs * celeb_followers * posts_each / rows[0][1]
avg_rate = rows[0][1] / 86_400
print(f"celebrity share of all timeline writes: {celeb_share:.0%}")
print(f"one celebrity post = {celeb_followers:,} writes = {celeb_followers/avg_rate:.0f} s of the whole average write rate")
# What a small sample of accounts would suggest
n, trials = 10_000, 2_000
rng = np.random.default_rng(42)
estimates, with_celeb = [], 0
for _ in range(trials):
k = rng.hypergeometric(celebs, regular, n) # celebrities that landed in the sample
ordinary = rng.lognormal(mu, sigma, n - k)
estimates.append((ordinary.sum() + k * celeb_followers) / n)
with_celeb += k > 0
estimates = np.array(estimates)
p_hit = stats.hypergeom.sf(0, accounts, celebs, n)
print(f"sample of {n:,} accounts, {trials} draws: {with_celeb/trials:.1%} contained a celebrity (exact {p_hit:.1%})")
print(f"estimated mean followers: median {np.median(estimates):.0f}, 5th-95th percentile {np.percentile(estimates,5):.0f}-{np.percentile(estimates,95):.0f}, true {mean_followers}")
# Independent checks
lognorm_mean = stats.lognorm(s=sigma, scale=math.exp(mu)).mean()
total_mean = (regular * lognorm_mean + celebs * celeb_followers) / accounts
se = math.sqrt(p_hit * (1 - p_hit) / trials)
ok = (abs(total_mean - mean_followers) < 1e-6
and abs(with_celeb / trials - p_hit) < 4 * se
and abs(rows[0][1] - posts_per_day * mean_followers) < 1)
print("check (scipy lognormal mean, exact hypergeometric, posts x mean):", "PASS" if ok else "FAIL")
Output:
ordinary accounts: mean 140.0 followers, median 45.5
celebrities: 10 x 30,000,000 = 300M follower links = 30% of all links
case writes/day (B) avg /s peak /s GB/day
200 counts everyone 10.00 115,741 347,222 320
200 is ordinary, celebs extra 13.00 150,463 451,388 416
hybrid (skip > 1,000,000) 7.00 81,019 243,056 224
celebrity share of all timeline writes: 30%
one celebrity post = 30,000,000 writes = 259 s of the whole average write rate
sample of 10,000 accounts, 2000 draws: 1.8% contained a celebrity (exact 2.0%)
estimated mean followers: median 140, 5th-95th percentile 134-148, true 200
check (scipy lognormal mean, exact hypergeometric, posts x mean): PASS
Hand check of the first row: 50,000,000×200=10,000,000,000 writes per day, /86,400=115,741 per second, times 3 is 347,222 at peak, and 1010×32 bytes=3.2×1011 bytes, which is 320 GB per day in decimal units.
What the heavy tail does to the estimate
- The headline holds only if 200 really is the mean over every posting account. Then the answer is 10.00 billion timeline writes a day, 115,741 per second on average, 347,222 at peak, and 320 GB of new timeline entries a day (about 960 GB a day with three replicas).
- A few accounts produce a large share. The 10 large accounts hold 30 percent of all follower links and, posting as often as everyone else, produce 30 percent of the writes. Their writes scale in proportion to how often they post, but their share of the total does not: if they posted twice as often as everyone else their writes would be 6.00 billion a day against 7.00 billion from the ordinary accounts, a share of 46 percent, and at half the rate 1.50 billion, a share of 18 percent.
- If 200 describes ordinary accounts and the large ones come on top, the total is 13.00 billion writes a day, 150,463 per second on average, 451,388 at peak, and 416 GB a day. This is the reading to clarify with the interviewer, since the two totals differ by 3 billion writes a day.
- A single large post is a burst, not a rate. One post from a 30 million follower account is 30,000,000 writes, equal to 259 seconds of the entire system's average write rate. The system must queue and spread this work, and followers of such an account see the post later than other posts unless the fan-out is spread across many workers.
- A small sample hides the tail. Drawing 10,000 accounts at random, only 1.8 percent of 2,000 simulated samples contained a large account (the exact probability is 2.0 percent), so the typical estimate of the mean was 140 (5th to 95th percentile, the range holding the middle 90 percent of the 2,000 sampled estimates: 134 to 148) against the true 200. Estimating from a sample of typical accounts would under-count the writes by 30 percent. In the rare sample that does hold one large account, that single account adds 30,000,000/10,000=3,000 to the sample mean, so a sample mean is either far too low or far too high and almost never near 200.
The judgment
Size for roughly 350 thousand timeline writes per second at peak and 320 GB a day of new entries, then change the design for the tail rather than buying capacity for it. Use fan-out on write for ordinary accounts and, above a follower cut-off, do not fan out: store those accounts' posts once and merge them into a follower's timeline when it is read (pull at read: the follower's timeline request fetches the large account's recent posts and merges them in). With a 1 million cut-off in the model, the load falls from 10.00 to 7.00 billion writes a day (81,019 per second on average, 243,056 at peak, 224 GB a day), a 30 percent reduction, and the burst of a 30 million follower post disappears. The cost moves to the read path, where each timeline read must also fetch recent posts from the few large accounts that user follows.
Also note that timelines are normally capped to the most recent entries per user, so stored size levels off; the per-day figure is the write volume before old entries are evicted (deleted to make room). What would flip the choice: if almost nobody follows more than one or two large accounts, pull-at-read is cheap, and if read latency is the dominant product requirement, a lower cut-off with more fan-out is acceptable.
Common mistakes
- Using the mean for a single post's cost, or sizing queue capacity from the average when the burst of one large post is the real constraint.
- Estimating the mean from a small random sample of accounts that contains none of the large ones.
- Forgetting the peak-to-average ratio, or replication in the storage figure.
- Reading 200 as "followers of the typical account" when the question gives it as the mean.
- Treating storage as growing forever when timelines are trimmed.
Running the code
Python 3.12 with numpy 2.1.3 and scipy 1.14.1.
python fanout_sizing.py
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
You are asked to size storage for a data warehouse. Today it holds 120 tables with about 150M rows each at roughly 400 bytes per row, retention is 3 years, and ingest grows 0.5% per day. Estimate current storage and the projected size in 3 years, decide how much safety buffer you would provision, and state what you assumed about compression, indexes and replication.
Sample Answer
The idea in plain words
Warehouse storage is rows x bytes per row, adjusted for what the platform does to those bytes (compression makes them smaller; indexes, free space and extra copies make them bigger). Two things make the future different from today: retention (rows older than 3 years are deleted, so the table does not grow forever) and growth (ingest, the data arriving each day, is growing). Keep two quantities apart: the stock is how much is stored right now, and the ingest rate is how much new data arrives per day. With growth stated as 0.5% per day, the compounding is the whole story: 0.5% a day is 6.17 times in a year and 235 times in three years. A candidate who multiplies it through without noticing should stop and ask whether the figure is per day or per month, because the 3-year answer differs by a factor of about 40.
Method
Conventions: decimal units (1 TB = 1012 bytes), 365-day years, a retention window of 1,095 days.
- Current raw size:
- Today's daily ingest: the question gives the stock, not the rate. Assume the stock is a full 3-year window filled at a flat rate, so daily ingest per table is r0=150×106/1,095=136,986 rows. (Small version of the same step: a table that keeps the last 1,095 days and holds 1,095 rows must be receiving 1 row a day; a table holding 150 million rows receives 150 million divided by 1,095 a day.)
- Growth: ingest on day d from now is r0(1+g)d with g=0.005. The rows retained at day D are the last 1,095 days of ingest. After 3 years every row in the window is new. Each day's ingest is 1.005 times the day before, so the retained rows are a sequence of 1,095 terms that each grow by the same factor, and a geometric sum adds such a sequence in one step (a closed-form formula: one expression instead of adding 1,095 terms one by one). With first term r0(1+g), ratio (1+g) and 1,095 terms:
Worked by hand: 1.0051096=236.594, so the bracket is (236.594−1.005)/0.005=47,117.8 and the rows retained per table are 136,986×47,117.8=6,454.5 million, the figure in the program output below. The 1-year figure is the 730 days of today's flat-rate rows that have not yet expired plus 365 days of compounding new ingest: 136,986×(730+(1.005366−1.005)/0.005)=136,986×(730+1,040.1)=242.5 million rows per table.
- Physical size (assumptions, each with a plausible range): compression 3x (2 to 8; columnar formats store each column's values together, which compresses better than row stores that keep whole rows together), index and free-space overhead x 1.15 (1.0 to 1.5), 2 stored copies (1 to 3, depending on whether the platform bills logical bytes or you replicate yourself):
- Buffer: decided below.
# Warehouse storage with retention and compounding ingest growth. Decimal units: 1 TB = 10**12 bytes.
TABLES = 120 # given
ROWS_NOW = 150_000_000 # given: rows per table today
ROW_BYTES = 400 # given
RETENTION_DAYS = 3 * 365 # given: 3 years, 1,095 days
GROWTH_PER_DAY = 0.005 # given: daily ingest volume grows 0.5% per day, compounding
# assumptions (not given)
COMPRESSION = 3.0 # columnar compression ratio (plausible 2 to 8)
INDEX_OVERHEAD = 1.15 # indexes, metadata, free space (plausible 1.0 to 1.5)
COPIES = 2 # stored copies (plausible 1 to 3, depends on platform)
BUFFER = 0.25 # safety buffer on the projected size
TB = 1e12
def physical(rows_per_table):
raw = TABLES * rows_per_table * ROW_BYTES
return raw, raw / COMPRESSION * INDEX_OVERHEAD * COPIES
# Today's stock is treated as a full window of past flat ingest: daily rows per table today.
r0 = ROWS_NOW / RETENTION_DAYS
print(f"raw size today : {TABLES*ROWS_NOW*ROW_BYTES/TB:.2f} TB (120 x 150M x 400 B)")
print(f"daily ingest per table: {r0:,.0f} rows (stock / 1,095 days)")
print(f"physical size today : {physical(ROWS_NOW)[1]/TB:.2f} TB (raw / {COMPRESSION:g} x {INDEX_OVERHEAD} x {COPIES} copies)")
def stock_after(days, g):
"""Rows per table retained after `days`, simulating day by day with expiry of rows older than the window."""
ingest = [r0] * RETENTION_DAYS # past 1,095 days at the flat rate
for d in range(1, days + 1):
ingest.append(r0 * (1 + g) ** d)
window = ingest[-RETENTION_DAYS:]
return sum(window)
for label, days in (("1 year", 365), ("3 years", 1095)):
rows = stock_after(days, GROWTH_PER_DAY)
raw, phys = physical(rows)
print(f"{label:8s}: {rows/1e6:9,.1f}M rows/table raw {raw/TB:8.1f} TB physical {phys/TB:8.1f} TB"
f" with {BUFFER:.0%} buffer {phys*(1+BUFFER)/TB:8.1f} TB")
print(f"\ngrowth over a year : {(1+GROWTH_PER_DAY)**365:.2f}x ; over 3 years: {(1+GROWTH_PER_DAY)**1095:.1f}x")
import math
print(f"a {BUFFER:.0%} buffer is {math.log(1+BUFFER)/math.log(1+GROWTH_PER_DAY):.0f} days of runway at that growth rate")
ALERT = 0.70 # alert when the provisioned space is this full
print(f"an alert at {ALERT:.0%} full leaves {math.log(1/ALERT)/math.log(1+GROWTH_PER_DAY):.0f} days of runway if stock grew as fast as ingest")
# the recommended plan in the day-by-day model: provision the 12-month physical size plus the buffer, alert at ALERT
def first_day_at_or_above(level_tb):
for d in range(1, RETENTION_DAYS + 1):
if physical(stock_after(d, GROWTH_PER_DAY))[1] / TB >= level_tb:
return d
cap_tb = physical(stock_after(365, GROWTH_PER_DAY))[1] * (1 + BUFFER) / TB
d_alert, d_full = first_day_at_or_above(ALERT * cap_tb), first_day_at_or_above(cap_tb)
print(f"plan ({cap_tb:.1f} TB): alert on day {d_alert}, full on day {d_full}, {d_full - d_alert} days of runway")
print("\nthree-year raw size under other readings of the growth rate (TB)")
for label, g in (("0.5% per day", 0.005), ("0.1% per day", 0.001), ("0.5% per month", (1.005) ** (1/30) - 1), ("no growth", 0.0)):
print(f"{label:16s} {physical(stock_after(1095, g))[0]/TB:9.1f}")
# independent check: closed-form geometric sum for the rows ingested in the next 1,095 days
g = GROWTH_PER_DAY
closed = r0 * ((1 + g) ** (1095 + 1) - (1 + g)) / g # sum_{d=1..1095} r0 (1+g)^d
assert abs(closed - stock_after(1095, g)) / closed < 1e-9, "simulation and closed form disagree"
assert abs(TABLES * ROWS_NOW * ROW_BYTES / TB - 7.2) < 1e-9
print("\nchecks passed")
Output:
raw size today : 7.20 TB (120 x 150M x 400 B)
daily ingest per table: 136,986 rows (stock / 1,095 days)
physical size today : 5.52 TB (raw / 3 x 1.15 x 2 copies)
1 year : 242.5M rows/table raw 11.6 TB physical 8.9 TB with 25% buffer 11.2 TB
3 years : 6,454.5M rows/table raw 309.8 TB physical 237.5 TB with 25% buffer 296.9 TB
growth over a year : 6.17x ; over 3 years: 235.4x
a 25% buffer is 45 days of runway at that growth rate
an alert at 70% full leaves 72 days of runway if stock grew as fast as ingest
plan (11.2 TB): alert on day 316, full on day 435, 119 days of runway
three-year raw size under other readings of the growth rate (TB)
0.5% per day 309.8
0.1% per day 13.1
0.5% per month 7.9
no growth 7.2
checks passed
Reading the result
- Today: 7.20 TB raw, 5.52 TB physical.
- In 3 years, if ingest really compounds at 0.5% per day: 6,454.5M rows per table, 309.8 TB raw, 237.5 TB physical, about 43 times the physical size today. By then every row in the table was ingested after today.
- In 1 year: 11.6 TB raw, 8.9 TB physical (the oldest rows start expiring but new ingest dominates).
- Other readings of the growth number: at 0.1% a day the 3-year raw size is 13.1 TB; at 0.5% a month it is 7.9 TB; with no growth it stays at 7.2 TB. The spread from 7.9 TB to 309.8 TB is entirely the growth-rate reading, so confirm it from ingest history before buying anything.
- If the stock is younger than the retention window (say the tables filled in 1 year rather than 3), daily ingest today is three times higher and the 3-year figures are three times higher, because the 3-year stock is all new ingest.
The buffer
A percentage buffer says little under compounding growth. A 25% buffer on the projected size buys ln1.25/ln1.005=45 days of runway (the time until you are full) at that growth rate, once the window is mostly new data so that stock grows at roughly the ingest rate. The logarithm appears because growth multiplies: you want the number of days n with 1.005n=1.25, and a logarithm turns that power into n=ln1.25/ln1.005. Check by trace: 1.00545=1.2516, so after 45 days the data has grown by 25%. The program prints 45. So I would not provision 3 years up front. The recommendation:
- Provision for the next 12 months: 8.9 TB physical (8.92 TB before rounding) plus a 25% buffer, which is 11.2 TB.
- Alert at 70% utilisation. The runway after the alert has to cover the lead time (the time between asking for more capacity and having it, for example the procurement process of ordering hardware or the approval of a larger cloud quota). Stored data cannot grow faster than ingest, so an alert at a fraction f full leaves at least ln(1/f)/ln1.005 days, which is 72 days for f=0.7. For this plan the day-by-day model is more generous, because stock grows slower than ingest while old rows are still expiring (it reaches 0.5% a day only once the window is all new data): the alert fires on day 316 and the space is full on day 435, 119 days later (the program prints both days). Size the alert threshold against the floor, and if your lead time is longer than that, lower the threshold.
- Re-forecast monthly from the measured daily ingest, fitting the growth rate on the last 90 days instead of trusting the stated 0.5%.
- Use the 3-year figure (296.9 TB with the same buffer) for budget planning and as an upper scenario only. If measured growth turns out to be 0.1% a day or less, the 3-year need is in the low tens of TB and the same 25% fixed buffer is enough.
The 25% is a judgment, not a derived number: it covers forecast error in compression and overhead (which I assumed) more than growth.
Assumptions to state
- Compression, index overhead and copies are assumptions; the range 2x to 8x on compression alone moves the physical size by a factor of 4.
- Retention deletes whole days of data at the window edge; the platform may keep deleted space reserved until a vacuum or compaction (a clean-up job that reclaims the space left by deleted rows) runs, so physical size can lag the projection.
- All 120 tables are assumed to grow at the same rate and to have the same row width.
Common mistakes
- Multiplying 7.2 TB by 1.0051095 and ignoring that retention expires the old rows.
- Reading 0.5% per day as 0.5% per month, or the reverse, without checking.
- Treating compression, indexes and replication as zero because the question did not give them.
- Buying 3 years of capacity at once for a number that is compounding from a guess.
Running the code
Python 3.12, standard library only. Save the listing as warehouse_size.py and run python warehouse_size.py. It ends with checks passed when the day-by-day simulation matches the closed-form sum; shortening the retention window by one day in the simulation makes that check fail.
Unlock Full Question Bank
Get access to all 6 Estimation and Capacity Sizing interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.