Skip to content

Back-of-the-Envelope Capacity Estimation: Traffic, Storage, Bandwidth ​

"Important skill: ability to estimate performance of a system design – without actually having to build it!" — Jeff Dean, Software Engineering Advice from Building Large-Scale Distributed Systems (Stanford CS295 talk slides)

Summary: A capacity estimate turns product numbers (users, objects, retention) into engineering numbers (requests per second, bytes, bits per second, requests in flight, servers) using a dozen small formulas and a table of latencies, so that architecture choices rest on arithmetic and not on taste. Focus: Units and powers of two, the latency ladder with 2025-era corrections, QPS from DAU with peak and read/write ratio, storage with row overhead, indexes, replicas and retention, bandwidth and CDN, cache memory and the 80/20 rule, Little's law, queue sizing, database sizing (connections, IOPS, WAL), cost, headroom, five worked examples, common mistakes, and how the result picks an architecture style. Learning goal: Given a one-paragraph product description, produce in ten minutes a table of peak QPS, storage over retention, bandwidth, cache size, in-flight requests and node count, say which of them is the first to hurt, pick monolith, modular monolith, sharding or CDN on the numbers, and then validate the estimate against a measured load test.

This chapter belongs to the Foundations group of the Architecture path. It sits between From Requirements to Architecture (which tells you which quality numbers to collect) and SLAs, SLOs, SLIs and Error Budgets (which turns the latency and availability targets into promises). The same method, as an interview routine, is in The 4-Step Approach; the tail-latency half of the story is in Latency Budgets, Geography and Tail Latency; the planning cycle at a company scale is in Capacity Planning and Disaster Recovery. Here we teach the arithmetic itself and the code that does it for you.

Page map ​

If you are looking forGo to
The whole chapter in a few tablesEverything in one minute
Why we estimate at allWhy it exists
Dean, Norvig, Colin Scott, Little 1961, the SRE bookWhere it comes from
KB/MB/GB/TB, powers of two, bits vs bytesUnits
L1 to cross-region latency, 2025 numbersLatency numbers
DAU to QPS, peak factor, read/write ratioQPS from DAU
Row size, indexes, replicas, retentionStorage
Ingress, egress, CDNBandwidth
Working set, 80/20, Redis memoryCache memory
servers = throughput x latencyLittle's law
Producer and consumer rates, lagQueue sizing
Connections, IOPS, WAL growthDatabase sizing
Per-request cost, egress costCost
2x rule, 3-year horizonHeadroom and growth
p99 vs mean, peaksPercentiles and peaks
Twitter-like, URL shortener, images, chat, analyticsWorked examples
What the numbers say about architectureChoosing, In architecture
Estimator CLI, Artisan commandGo, Laravel
Estimate, then measure with hey or k6Lab
Wrong beliefs, cheat sheet, self-check, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The ten formulas. Every row is unpacked in the concepts section.

QuantityFormulaTiny exampleWhat goes wrong if you skip it
Average QPSDAU x requests per user per day / 86,40010 M x 20 / 86,400 = 2,315You size for a number nobody sees
Peak QPSaverage QPS x peak factor (2 to 10)2,315 x 3 = 6,944The system falls over at 20:00, not at 04:00
Read and write QPSpeak QPS split by the read:write ratio100:1 gives 69 writes, 6,875 readsOne database serves both and you cannot tell which one hurts
Storage per dayDAU x objects x (payload + row overhead) x (1 + index factor) x replicas10 M x 1 x 540 x 1.5 x 3 = 24 GBDisk full in month four
Total storagestorage per day x retention days24 GB x 365 = 8.9 TBNo deletion policy, a surprise bill
BandwidthQPS x bytes per message x 86,875 x 5 KB x 8 = 275 Mbit/sA 1 Gbit/s link at 80% because you counted bytes
Cache sizehot fraction x data size20% x 1 TB = 200 GBA cache that is too small evicts what it must keep
In flight (Little)L = arrival rate x time in system6,944 x 0.05 s = 347Thread pool and connection pool sized by hope
ServersL / (per-node concurrency x target utilization)347 / (200 x 0.6) = 3Either 30 idle servers or an outage
Queue drain timebacklog / (consume rate - produce rate)6,000 / (200 - 100) = 60 sA backlog that never drains

Five numbers to remember for 2025.

NumberValueWhy it matters
Seconds per day86,400 (round to about 100,000 for mental math)The bridge between "per day" and "per second"
Memory vs SSD vs networkabout 100 ns, 20 to 100 us, 0.5 msEach step is 10 to 1,000 times slower
Same-datacenter round tripabout 0.5 ms (Dean); 0.1 to 1 ms in practiceThe price of every network hop between services
Cross-region round trip70 to 150 msYou cannot make this faster; you can only avoid it
Peak factor2 to 10 over the daily meanCapacity is bought for the peak

The estimate in one picture (details: DAU to servers, Little's law):

DAU (daily active users)e.g. 10,000,000average QPSDAU x requests per user / 86,400peak QPSaverage x peak factor (2 to 10)in flight Lpeak QPS x latency (Little)serversL / (per-node concurrency x utilization)Estimate from product numbers, not guesses1 day = 86,400 s (round to 100,000 for speed)Size for the peak, not the meanLatency = W: measure p50 and p99Then multiply by 2 for headroom

Why it exists ​

An architecture is a set of bets about quality attributes. Without numbers the bets are arguments about taste: "microservices scale", "a single PostgreSQL is enough", "we need Kafka". A back-of-the-envelope estimate converts each bet into a quantity you can compare with what one machine, one disk or one link can do. It answers four questions before any code exists:

QuestionThe estimate that answers itTypical decision it drives
Will one machine be enough?Peak QPS, in-flight requests, storageMonolith on one node vs several
What breaks first?Compare each resource to its limitInvest in the bottleneck, not the loudest worry
Which style fits?QPS per team, data size, bandwidthMonolith, modular monolith, sharding, CDN
What will it cost?Storage x price, egress x price, nodes x priceBuild, buy, or change the product

The analogy we reuse on this page: a restaurant kitchen. Before opening, the owner does not know the exact number of guests either. But "200 dinners on a Friday, each table sits for 90 minutes, a cook plates a dish in 4 minutes" is enough to decide the number of tables, stoves and cooks. Peak (Friday 20:00), time-in-system (the 90 minutes at the table) and utilization (never run the kitchen at 100%) are exactly the three ideas of this chapter.

Weaker estimate (rough)Stronger estimate (precise)
Takes 10 minutes, usable in a meetingTakes days, needs a prototype and real data
Right within a factor of 2 to 10Right within 10 to 30 percent
Chooses between styles and orders of magnitudeChooses instance sizes and reserved capacity
Wrong inputs give wrong outputs, visiblyLooks more certain than the inputs deserve

Three common misunderstandings, up front ​

  1. "Estimates must be accurate." No. The goal is the order of magnitude: 100 QPS vs 10,000 QPS vs 1,000,000 QPS lead to different architectures; 6,900 vs 7,400 does not. Errors of 2x are normal and are covered by headroom.
  2. "Averages are enough." No. Users do not arrive evenly. Capacity is bought for the peak and judged by the p99, not by the mean (see Percentiles and peaks).
  3. "Estimation is something you do once, in the design phase." No. The numbers drift every quarter. Google's SRE book calls capacity planning "a neverending cycle" in which assumptions change; the estimate is a living model you re-run, then check against measurements.

Where it comes from ​

Little, 1961. John Little proved that, for a stable system, the long-term average number of items in it equals the arrival rate multiplied by the average time each spends in it. The result is independent of the arrival distribution and the service order; the original is A Proof for the Queuing Formula: L = λW, Operations Research 9(3), 1961 (cited from Wikipedia, a secondary source, which we fetched; we did not fetch the original paper).

Norvig, 2002, and Dean. The comments in the source of Colin Scott's page credit Peter Norvig's essay Teach Yourself Programming in Ten Years (norvig.com/21-days.html) as the origin of the numbers, dated 2002 (we did not fetch the essay). Jeff Dean's Stanford talk (the PDF is undated) turned the idea into a datacenter-era slide titled "Numbers Everyone Should Know": L1 cache reference 0.5 ns, main memory reference 100 ns, round trip within the same datacenter 500,000 ns, disk seek 10,000,000 ns, packet CA to Netherlands and back 150,000,000 ns. The same deck shows the method on a real question, how long a results page with 30 image thumbnails takes:

"Design 1: Read serially, thumbnail 256K images on the fly: 30 seeks * 10 ms/seek + 30 * 256K / 30 MB/s = 560 ms. Design 2: Issue reads in parallel: 10 ms/seek + 256K read / 30 MB/s = 18 ms (Ignores variance, so really more like 30-60 ms, probably)" — Jeff Dean, Stanford CS295 slides

Colin Scott. The page Latency Numbers Every Programmer Should Know (interactive, by year) keeps Norvig's 2002 numbers as the anchor and extrapolates each category by a trend (CPU clock, memory bus latency, SSD, disk, network bandwidth). Its own source comment says: "All of Norvig's original numbers were from 2002". Read the page as a model, not as a measurement: it is useful to see which numbers fell by 1,000x (SSD, network bandwidth) and which hardly moved (round trips, speed of light).

Google SRE, 2016. Site Reliability Engineering (O'Reilly) devotes the case study "Auxon" to capacity planning and the chapter "Handling Overload" to why queries per second is a poor capacity unit (quoted below). The Kafka documentation (hardware and OS page) contains a literal back-of-the-envelope rule: memory = write throughput x 30 seconds.

text
     Year   Source                           What it gave us
1    1961   Little's law                     L = lambda x W, valid for any stable system
2    2002   Norvig's timing table            Orders of magnitude for a typical PC
3    n/a    Dean, "Numbers Everyone..."      Datacenter-era latency table + worked estimates (undated slides)
4    n/a    Colin Scott's interactive page   The table extrapolated per year, per category
5    2016   Google SRE book                  Capacity planning as a continuous cycle; QPS is not a capacity unit
6    2020s  NVMe, 25-100 Gbit/s NICs         Disk and network no longer the slowest rungs; round trips still are

The concepts, one by one ​

Units: powers of two, KB/MB/GB/TB, bits vs bytes Must-know ​

In plain words: Storage is counted in bytes, networks in bits per second. A kilobyte is about a thousand bytes, and each step up multiplies by about a thousand. A computer counts in powers of two, so 1,024 is also called a kilo, which causes a 2 to 10 percent mismatch that is harmless for estimates and harmful for invoices.

Common misunderstanding: "A 1 Gbit/s link moves 1 GB per second." It moves at most 125 MB per second, and in practice about 100 to 110 MB per second after protocol overhead. Network vendors say bits, filesystems say bytes; a factor of 8 hides between them.

Definition: Decimal prefixes (SI): kB 10^3, MB 10^6, GB 10^9, TB 10^12, PB 10^15. Binary prefixes (IEC): KiB 2^10, MiB 2^20, GiB 2^30, TiB 2^40. One byte is 8 bits. Cloud providers bill in GB or GiB depending on the service; read the pricing page footnote.

PowerExact valueNameRough decimalMemory aid
2^101,0241 KiB10^3 (thousand)a short email
2^201,048,5761 MiB10^6 (million)a JPEG thumbnail
2^301,073,741,8241 GiB10^9 (billion)a phone video, 1 minute
2^401.0995 x 10^121 TiB10^12 (trillion)one large HDD
2^501.1259 x 10^151 PiB10^15a data lake
2^324,294,967,2964 Gi4.3 x 10^9the limit of a 32-bit unsigned id
2^639.22 x 10^18max of bigint9.2 x 10^18enough for any counter
QuantityHandy conversion
Seconds per day86,400; use 10^5 for mental math (error 14%)
Seconds per month2.6 x 10^6 (30 days)
Seconds per year3.15 x 10^7
1 Gbit/s125 MB/s peak, about 100 MB/s usable, 8.6 TB per day
1 million requests per day11.6 requests per second on average
1 byte per request at 1,000 QPS86.4 MB per day
1 KB x 1 million1 GB
1 MB x 1 million1 TB
text
     Step                                         Result
1    10 M users x 2 KB profile                    20 GB (2 x 10^3 x 10^7 = 2 x 10^10)
2    The link says "1 Gbit/s"                     divide by 8: 125 MB/s
3    20 GB over that link                         20,000 / 125 = 160 s, not 20 s
4    Invoice says 1 TiB, you counted 1 TB         10% off: 1.0995 vs 1.0

Where the products say it: PostgreSQL reports sizes with pg_size_pretty in binary units (kB meaning 1,024); Redis INFO memory prints used_memory_human in binary units; AWS and Google Cloud bill storage per GB-month (check each page's note for GB vs GiB); network gear and AWS instance bandwidth are quoted in Gbit/s.

Latency numbers Must-know ​

In plain words: Doing work in the CPU cache takes nanoseconds, memory about a hundred nanoseconds, a fast SSD tens of microseconds, another machine in the same datacenter half a millisecond, another continent a hundred milliseconds. Each rung of the ladder is much slower than the one before, and the design question is almost always "how many rungs does one request climb, and how many times".

Common misunderstanding: "Modern hardware is fast everywhere, so the old table is obsolete." Bandwidth and storage got 100 to 1,000 times faster; round trips between machines and between regions did not, because they are bounded by distance and the speed of light in fibre. Dean's table is old, but the ratios between the rungs still hold.

Definition: The table below combines Dean's slide (the exact original values) with typical 2025-era values. The 2025 column is not from one source; it is the commonly measured range on current cloud hardware, rounded, and you must measure your own. Treat the ratios, not the digits, as the knowledge.

OperationDean's slide (original)2025-era typicalRatio to main memory
L1 cache reference0.5 ns0.5 to 1 ns0.005x
Branch mispredict5 ns3 to 5 ns0.05x
L2 cache reference7 ns3 to 5 ns (per core)0.05x
Mutex lock/unlock100 ns15 to 50 ns uncontended0.2x
Main memory reference100 ns60 to 100 ns1x
Compress 1 KB (Zippy)10,000 ns2,000 to 5,000 ns (LZ4 and Snappy class)50x
Send 2 KB over a 1 Gbps network20,000 ns16,000 ns serialisation at 1 Gbit/s, 1,600 ns at 10 Gbit/s100 to 200x
NVMe SSD random read (4 KB)not on the slide20 to 100 us300x
Read 1 MB sequentially from memory250,000 ns30,000 to 100,000 ns500x
Round trip within the same datacenter500,000 ns100 to 500 us (same availability zone), up to about 1 ms across zones5,000x
Disk seek (spinning disk)10,000,000 ns5 to 10 ms (still the same)100,000x
Read 1 MB sequentially from SSDnot on the slideabout 0.3 to 1 ms5,000x
Read 1 MB sequentially from disk30,000,000 ns5 to 10 ms (sequential HDD at 150 to 250 MB/s)50,000x
Cross-region round trip (same continent)not on the slide30 to 80 ms500,000x
Packet CA to Netherlands and back150,000,000 ns130 to 170 ms1,500,000x
L1 cache reference~0.5 nsL2 cache reference~7 nsMain memory reference~100 nsCompress 1 KB (Zippy)~10 usNVMe SSD random read~20-100 usRead 1 MB from memory~50-250 usSame-datacenter round trip~0.5 msDisk seek (spinning)~10 msCross-region round trip~70-150 ms

The picture is on a logarithmic scale: every few steps along the bars the time grows by a factor of ten.

text
     Rule                                                   Consequence for design
1    Network round trip = 5,000 memory references           Never call a service in a loop; batch
2    Cross-region = 200 to 300 same-datacenter round trips  Keep the chatty parts in one region
3    SSD random read = 100 x slower than memory             A cache hit rate of 90% cuts latency about 10x
4    HDD seek = 20 to 100 SSD reads                         Sequential access (logs, LSM) wins on HDD
5    Compression costs microseconds, saves milliseconds     Compress before the wire when bandwidth is the limit

What this does to a request. A request that crosses three services and two databases in one datacenter pays at least five round trips: 5 x 0.5 ms = 2.5 ms of pure network before any CPU. The same request with one cross-region hop pays 5 x 0.5 + 80 = 82.5 ms. Latency budgeting (Latency Budgets) is this addition, done on purpose.

ScenarioArithmeticResultLesson
Page makes 100 sequential cache lookups, same datacenter100 x 0.5 ms50 msUse one MGET or a pipeline
Page makes 100 sequential queries, one per row (N+1)100 x (0.5 ms network + 1 ms query)150 msJoin or WHERE id IN (...); see ORM pitfalls
Thumbnails page, 30 images, serial HDD reads30 x 10 ms + 30 x 256 KB / 30 MB/s560 ms (Dean)Parallelise: 18 ms
Write 1 KB with fsync on NVMeone flush, 50 to 500 usat most a few thousand commits per second per deviceGroup commit; see durability
User in Tehran reads from a region in Frankfurtabout 80 to 120 ms RTT, TLS adds 1 to 2 more160 to 360 ms before first byteCDN or a nearer region

QPS from DAU: peak factor, read/write ratio Must-know ​

In plain words: Take the number of users who come on an ordinary day, multiply by what each does, divide by the seconds in a day, and you have the average requests per second. Then multiply by a peak factor, because people are not evenly spread over the day.

Common misunderstanding: "MAU (monthly active users) is the number to start with." No: capacity is driven by what happens at the busiest minute of the day, so start from DAU, then peak concurrent users, and convert. MAU can be three to ten times DAU, and the ratio varies per product.

Definition: Average QPS = DAU x requests per user per day / 86,400. Peak QPS = average x peak factor. Read QPS and write QPS split the peak by the read:write ratio. QPS means requests per second at the layer you are measuring: the edge, the application, or the database see different numbers because caches and fan-out sit between them.

Product kindPeak factorRead:writeWhy
B2B SaaS, office hours, one time zone3 to 5 (the day is 8 hours, not 24)10:1 to 50:18 busy hours compress 24 hours of traffic
Consumer social, global2 to 3100:1 or moreTime zones flatten the curve
E-commerce with a sale10 to 50 on the sale minute50:1, then checkout writes spikeCampaigns and flash sales
Streaming or sport events5 to 20 around a matchread heavyOne event, one audience
Chat3 to 51:1Every message is written once and read by the recipient
Telemetry, analytics ingestion2 to 4write heavy, 1:100 or lessMachines do not sleep
Payments in a single country3 to 6 (evening, month start)5:1Salary days and bills
text
     Step                                  Calculation                         Result
1    DAU                                   given                               10,000,000
2    Requests per user per day             given (20 page views, 1 API each)   20
3    Requests per day                      10,000,000 x 20                     200,000,000
4    Average QPS                           200,000,000 / 86,400                2,315
5    Peak factor                           assume 3                            6,944 peak QPS
6    Read:write = 100:1                    writes = 6,944 / 101                69 writes/s, 6,875 reads/s
7    Headroom 2x                           design target                       about 14,000 QPS
ShortcutCalculationUse when
1 M requests/day is about 12 QPS10^6 / 10^5Mental math in an interview
100 M requests/day is about 1,200 QPS10^8 / 86,400Startup to mid-size
1 B requests/day is about 11,600 QPS10^9 / 86,400A large public API
Peak concurrent users (PCU)DAU x fraction online at peak (often 5 to 20 percent)Sizing websockets, sessions
Requests per second from concurrencyPCU / think time (seconds between actions)When you know "users click every 10 s"

What QPS means at each layer. A browser page may make 1 request to the app, which makes 5 calls to the database and 20 to a cache. The app sees 1,000 QPS, the cache 20,000, the database 5,000 (if the cache hits for 75%, fewer). Always write down the layer.

Real scenarios: a login endpoint at 09:00 when a company's staff arrives; a salary-day spike on a banking app; a push notification that brings 500,000 users to the same screen within a minute (the "thundering herd", which a flat peak factor of 3 underestimates, so use 10 and add a queue); a mobile app that refreshes every 30 s for a live score, which turns 1 M open apps into 33,000 QPS even without any "action".

Storage: objects, row overhead, indexes, replicas, retention Must-know ​

In plain words: Multiply the number of new objects per day by the size of one object, then add what the database adds around it (headers, indexes), multiply by the number of copies, and by the number of days you keep the data.

Common misunderstanding: "One row is as big as the sum of its columns." In PostgreSQL a row also pays a tuple header (23 bytes, padded), a 4-byte item pointer in the page, alignment padding between columns, and every index entry it has; a "100 byte" row is routinely 150 to 200 bytes in the table and another 50 to 150 in indexes. Text, JSON and arrays can be compressed (TOAST), which sometimes helps and sometimes does not.

Definition: Total bytes = objects per day x (payload + row overhead) x (1 + index factor) x replication factor x retention days. Add 20 to 30 percent for free space (fill factor, bloat, vacuum lag) and 100 percent if you also keep backups on the same medium.

ComponentPostgreSQLRule of thumb
Page size8 kB (default, fixed at build time)Rows live in 8 kB pages; a page header takes 24 bytes
Tuple header23 bytes, padded to 24 (MAXALIGN)Add 24 bytes per row
Item pointer (line pointer)4 bytes per rowAdd 4 bytes per row
integer / bigint4 / 8 bytesChoose by range, not by habit
timestamptz, double precision8 bytesAligned to 8, padding after a 4-byte column
uuid16 bytes2x a bigint, and random v4 keys bloat the index
text, varchar1 or 4 byte header plus contentContent size plus 1 to 4
jsonbcontent plus about 20 to 50 percent structureTest with pg_column_size
B-tree index entryabout 8 to 16 bytes header and key, plus 4 pointer, at 70 to 90 percent fillEstimate 20 to 40 bytes per entry for small keys
Free space and bloatfill factor 100 by default for tables, 90 for B-tree indexesPlan 20 to 30 percent more
sql
-- Measure instead of guessing: bytes per row, table and index size, and a projection.
SELECT pg_size_pretty(pg_total_relation_size('orders'))     AS total,
       pg_size_pretty(pg_relation_size('orders'))           AS heap,
       pg_size_pretty(pg_indexes_size('orders'))            AS indexes,
       pg_total_relation_size('orders') / NULLIF(count(*), 0) AS bytes_per_row_with_indexes
FROM orders;

-- Actual size of one value, including its header.
SELECT pg_column_size(ROW(1::bigint, now(), 'hello world'::text)) AS row_bytes;

-- New rows per day, from a timestamp column (use for the "objects per day" input).
SELECT date_trunc('day', created_at) AS day, count(*) AS rows
FROM orders GROUP BY 1 ORDER BY 1 DESC LIMIT 14;
text
     Step                                   Calculation                          Result
1    Payload (3 columns)                    8 + 8 + 40 text                      about 60 B
2    Row overhead                           24 header + 4 pointer                28 B
3    Alignment padding                      to 8-byte boundaries                 about 4 B
4    Row in the table                       60 + 28 + 4                          about 92 B
5    Two indexes (PK bigint, FK + time)     about 32 + 40 per row                about 72 B
6    Per row, one copy                      92 + 72                              about 164 B, factor 2.7x the payload
7    Replication factor 3, retention 1 y    164 x 3 x 365 per daily row          about 180 KB per daily row/year
8    Free space and bloat                   x 1.25                               about 225 KB
EngineWhere the overhead comes from
PostgreSQLTuple header 23 bytes, item pointer 4, alignment, MVCC dead tuples until VACUUM; see MVCC and VACUUM
MySQL InnoDBClustered index: the row lives in the primary key B-tree; secondary indexes store the primary key; a long PK inflates every index
SQLiteVariable-length record, small header; one file
MongoDBBSON with field names inside every document; short field names save space; WiredTiger compresses with snappy by default
Cassandra/ScyllaDBPer-cell timestamp and TTL overhead; compaction needs up to 50 percent free space for size-tiered
RedisPer key overhead of tens of bytes plus encoding; hashes and listpack encodings are cheaper for small values
KafkaPer-record header and per-batch overhead; log retained by time or size; replicated by replication.factor
Object storage (S3 and similar)Billed on logical bytes; the provider keeps the replicas; per-request and per-object monitoring fees on some classes

The replication factor needs one more thought. Three PostgreSQL replicas hold three copies, each with its own indexes and WAL. A Kafka topic with replication.factor=3 stores each partition three times. Object stores bill you once for the logical object, although they keep several copies. Always ask "who pays for the copies".

StorageTime (days)0901802702x daily writes, 90-day retention90-day retention: plateau = daily bytes x 90no retention policy: grows foreverRemember: x replicas,x (1 + index overhead)

Real scenarios: an audit log that is "just 200 bytes per event" and quietly becomes 3 TB per year with indexes and replicas; an orders table whose PK is a random UUID, which makes the primary key index twice the size of a bigint index and slows inserts (see ID generation); a time-series table where retention of 90 days makes storage plateau, whereas "keep forever" makes it grow linearly; log lines, which are the biggest data set of most companies and are often forgotten in estimates.

Bandwidth: ingress, egress, CDN Must-know ​

In plain words: Bandwidth is how many bits per second must flow in (ingress, uploads) and out (egress, downloads). It is requests per second multiplied by the size of each message, times eight to turn bytes into bits.

Common misunderstanding: "Bandwidth is only a cost for video sites." Any API that returns 50 KB of JSON at 5,000 QPS needs 2 Gbit/s at peak, which is more than a 1 Gbit/s NIC. Egress is also the line most often forgotten in a cloud estimate and is billed per GB leaving the provider.

Definition: Bandwidth (bit/s) = QPS x bytes per message x 8. Ingress = write QPS x request payload x 8; egress = read QPS x response size x 8. Add 10 to 30 percent for TLS records, HTTP headers and retransmits. A CDN (content delivery network) answers repeat requests from edge caches near users: your origin sees only the cache misses, so origin egress = egress x (1 - cache hit ratio).

TrafficSize per messageRateBandwidth at peak
JSON API response, small2 KB5,000/s80 Mbit/s
JSON API response, large list50 KB5,000/s2 Gbit/s
Web page, HTML + JS + CSS compressed500 KB (first visit)1,000 page loads/s4 Gbit/s
Image thumbnail20 KB20,000/s3.2 Gbit/s
Photo, original3 MB100 uploads/s2.4 Gbit/s ingress
Video, 1080p stream5 Mbit/s per viewer100,000 viewers500 Gbit/s
Chat message200 B plus 100 B of headers50,000/s120 Mbit/s
Kafka ingestion1 KB x replication 3300,000/s2.4 Gbit/s into the cluster, plus replication traffic between brokers
text
     Step                                   Calculation                          Result
1    Peak read QPS                          6,875 (from the QPS example)         6,875
2    Response size                          5 KB                                 5,000 B
3    Egress                                 6,875 x 5,000 x 8                    275 Mbit/s
4    Plus overhead 20%                      x 1.2                                330 Mbit/s
5    One 1 Gbit/s NIC at 70% target         700 Mbit/s usable                    fits, 47% used
6    Same API at 50 KB                      3.3 Gbit/s                           needs 10 Gbit/s NICs or a CDN
7    CDN hit ratio 90% on cacheable bytes   origin sees 330 x 0.1                33 Mbit/s
PlacementWhat it removesWhen it pays
Compression (gzip, brotli)60 to 80 percent of text bytesJSON, HTML, CSS, JS; costs CPU
CDN (Cloudflare, CloudFront, Fastly, Akamai)Origin egress and latency for cacheable contentStatic files, images, video, public API responses
Image resizing at the edgeOriginal-size downloadsMany device sizes
HTTP/2 and HTTP/3Head-of-line blocking, handshakesMany small requests
Pagination and field selectionOver-fetchingLarge lists; see pagination
Binary formats (protobuf)30 to 70 percent against JSONService-to-service traffic; see gRPC

Memory for caches: working set, 80/20 Important ​

In plain words: A cache does not need to hold everything, only what people ask for again. In most products a small share of the items gets most of the requests, so a cache of 10 to 20 percent of the data can serve 80 percent or more of the reads.

Common misunderstanding: "The 80/20 rule is a law." It is a heuristic. For a social feed it may be 95/5; for a long-tail catalogue (millions of rarely-visited products) it may be 60/40, and a small cache helps little. Measure the hit ratio on a replayed log before buying RAM.

Definition: Working set = the bytes touched by requests in a time window. Cache size = working set x (1 + overhead). Hit ratio h cuts backend load to (1 - h) of the read QPS: at 90 percent, ten times less; at 99 percent, a hundred times less, which is why the last percentage points are expensive and valuable.

Hit ratioBackend reads for 10,000 read QPSAverage latency if hit 1 ms, miss 20 ms
0%10,00020 ms
50%5,00010.5 ms
80%2,0004.8 ms
90%1,0002.9 ms
99%1001.2 ms
EngineMemory rule for estimates
RedisValue bytes plus 50 to 100 bytes of per-key overhead for strings; small hashes and sets use compact listpack encodings when under hash-max-listpack-entries (512) and hash-max-listpack-value (64); bitmaps are tiny: 100 million users in about 12 MB
MemcachedSlab allocator; plan 10 to 20 percent waste; item header about 50 bytes
PostgreSQLshared_buffers (commonly 25 percent of RAM) plus the OS page cache; the "cache" is the hot set that fits in RAM
KafkaPage cache: memory = write throughput x 30 s (Kafka documentation)
CDNDisk plus RAM at the edge; sized by the provider, billed by egress
In-process cache (Go map, Laravel array driver)Per instance; duplicates across instances; no invalidation across nodes
text
     Step                                   Calculation                          Result
1    Items                                  100 M product pages                  100,000,000
2    Average cached size                    4 KB value + 80 B key overhead       4,080 B
3    Everything                             100 M x 4,080 B                      408 GB
4    Hot fraction 20%                       408 GB x 0.2                         82 GB
5    Replication of the cache (1 replica)   x 2                                  164 GB
6    Fits in                                three 64 GB nodes, or one 192 GB     done

Real scenarios: session store (users online x 2 KB, tiny); a rate-limit counter per user (16 bytes x 10 M users = 160 MB); a leaderboard sorted set (100 bytes per member x 50 M = 5 GB); a "recently viewed" list per user capped at 20 entries; a cache stampede on a hot key when the item expires, which is a peak-factor problem, not a size problem.

Little's law and concurrency Must-know ​

In plain words: The average number of requests being worked on at the same time equals how fast they arrive multiplied by how long each stays. So the number of servers you need is the throughput times the latency, divided by what one server can hold at once.

Common misunderstanding: "If I double the number of servers, latency drops in half." No: latency of one request is whatever the work takes. More servers let more requests be in flight at the same time; they raise throughput, not speed. Latency drops only if the queue before the work was the cause.

Definition: L = λ x W, where L is the average number of requests in the system, λ (lambda) is the average arrival rate (equal to throughput in a stable system), and W is the average time a request spends in the system (queueing plus service). It holds for any stable system and any distribution (Little 1961), and applies to a whole service, a thread pool, a connection pool, a queue, or a checkout line.

the system: L requests in flightarrivals: lambda = 1000/sdepartures: lambdaeach request stays W = 0.05 sL = lambda x W = 1000 x 0.05 = 50
text
     Step                                   Calculation                          Result
1    Peak throughput lambda                 6,944 req/s                          6,944
2    Mean latency W                         50 ms                                0.05 s
3    In flight L                            6,944 x 0.05                         347 requests
4    One Go server holds                    goroutines are cheap; limit is DB pool 100
5    One PHP-FPM node holds                 pm.max_children = 32 workers          32 in flight
6    PHP-FPM nodes at 60% utilization       347 / (32 x 0.6)                      19 nodes
7    Go nodes at 60% utilization            347 / (100 x 0.6)                     6 nodes
8    Latency doubles to 100 ms under load   L = 6,944 x 0.1                      694; the same nodes now saturate

The last row is why a small slowdown in a dependency becomes an outage: with fixed workers, W rising from 50 to 100 ms doubles L, the pool is full, new requests queue, W rises again. That is the start of a cascading failure (Cascading Failures).

PoolWhat L measuresLittle applied
PHP-FPM pm.max_childrenRequests being executedworkers needed = peak QPS x mean duration per node
Go net/httpActive handlers (goroutines)Limited by CPU, memory, DB pool, not by a thread count; use http.Server timeouts
Database connection poolQueries in flightpool size = QPS x mean query time per app node; see connection pooling
Thread pool of a Java serviceRequests in flightthreads = QPS x W
Kafka consumer groupMessages being processedconsumers = produce rate x processing time per message
Checkout lineCustomers in the shopThe original use of the law

Utilization matters because queues explode near 100 percent. In a simple single-server queue (M/M/1), the mean time in system is service time / (1 - ρ), where ρ is utilization: at 50 percent it is 2x the service time, at 80 percent 5x, at 90 percent 10x, at 95 percent 20x. That is why we plan for 50 to 70 percent at peak, not 95. (M/M/1 is a model from queueing theory; real services differ, but the shape of the curve is right.)

Utilization ρMean time in system (M/M/1)Verdict
30%1.4x service timeWasteful
50%2xComfortable
70%3.3xTypical target at peak
80%5xTail latency visibly worse
90%10xOne slow dependency from an outage
95%20xNot a plan

Queue sizing: producer and consumer rates, lag Important ​

In plain words: A queue is a buffer between a fast producer and a slower consumer. It is fine when the buffer fills and empties; it is a problem when the consumer is never faster than the producer, because then the backlog only grows.

Common misunderstanding: "A queue gives infinite capacity." It gives time, not capacity. A queue absorbs a peak only if the consumers can drain it afterwards, and storage for the backlog is finite (disk, memory, retention).

Definition: Backlog (lag) = messages produced minus messages consumed. If consumers are faster than producers (μ > λ), the backlog drains at (μ - λ) per second. If μ ≤ λ it never drains. Required consumers = produce rate x processing time per message (Little's law again), plus headroom.

text
     Step                                   Calculation                          Result
1    Producers write                        2,000 msg/s for a 10-minute burst   1.2 M messages
2    Consumers (4 x 100 msg/s)              400 msg/s                            backlog grows 1,600 msg/s
3    After 10 minutes                       1,600 x 600                          960,000 messages behind
4    Burst ends, normal rate 300 msg/s      drain rate 400 - 300 = 100 msg/s    9,600 s = 2 h 40 min
5    Add 4 consumers (800 msg/s)            drain rate 500 msg/s                 1,920 s = 32 min
6    Message 1 KB, retention                960,000 x 1 KB x 3 replicas          about 2.9 GB: fits in Kafka
BrokerWhat to sizeRule
KafkaPartitions, disk for retention, page cachePartitions at least the consumers you want in parallel; disk = rate x size x replication x retention; memory = write throughput x 30 s
RabbitMQQueue length, memory alarm, prefetchLong queues live in memory or lazy on disk; set prefetch_count so consumers are not starved or flooded
Redis StreamsMemoryThe whole stream is in RAM; trim with MAXLEN
Laravel queuesWorkers (queue:work processes), job timeoutworkers = jobs per second x seconds per job; Horizon balances by queue
SQSVisibility timeout, in-flight limitStandard queues have a limit on in-flight messages; check the quota page

Real scenarios: a nightly email campaign that enqueues 2 million jobs at midnight; a payment webhook retry storm; a consumer that gets slow because the database it writes to is slow (the backlog is the symptom, the database is the cause). Related chapters: backpressure and flow control, competing consumers, Kafka, Laravel queue internals.

Database sizing: connections, IOPS, WAL growth Important ​

In plain words: A database has three limits that you reach in this order more often than you expect: the number of connections, the number of disk operations per second, and the speed at which it can write its log.

Common misunderstanding: "Raise max_connections and the problem goes away." Each PostgreSQL connection is a process with its own memory, and more concurrent queries than cores only add context switching. The right fix is a pool (PgBouncer) sized by Little's law.

Definition: Connections needed = QPS to the database x mean query time (Little). IOPS (input/output operations per second) needed = cache-miss reads per second + write operations (WAL flushes, checkpoint writes, index changes). WAL growth per second = update rate x (WAL bytes per change), plus full-page images after each checkpoint.

ResourceHow to estimatePostgreSQL knob or fact
ConnectionsQPS x mean query seconds, per app node, then times nodesmax_connections default is typically 100; PgBouncer in transaction mode multiplexes
Memoryshared_buffers + connections x work_mem x operations per queryOne query can use work_mem several times (per sort or hash node)
Read IOPSread QPS x (1 - hit ratio) x pages per queryNVMe: 100,000+ IOPS; gp3 EBS defaults to 3,000 IOPS; a spinning disk: about 100 to 200
Write IOPScommits per second (WAL flush) + dirty pages per checkpointsynchronous_commit, group commit
WAL volumechanged bytes per second x (1 + full-page-write overhead)max_wal_size (soft limit for WAL between checkpoints), WAL segment 16 MB by default; full_page_writes on
Replica lagWAL rate vs replay rate and networkSee replication
DiskTable + index + WAL + temp + backupsSection Storage
sql
-- How fast is the WAL growing? Take two samples and subtract.
SELECT pg_current_wal_lsn() AS lsn, now() AS at;
-- later:
SELECT pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), '0/5000000'::pg_lsn)) AS wal_since;

-- Current QPS and mean time per statement, from pg_stat_statements.
SELECT queryid, calls, round(mean_exec_time::numeric, 2) AS mean_ms,
       round((total_exec_time / sum(total_exec_time) OVER ())::numeric * 100, 1) AS pct_of_time
FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10;

-- Connections in use right now.
SELECT state, count(*) FROM pg_stat_activity GROUP BY state;
text
     Step                                   Calculation                          Result
1    DB queries at peak                     3,000 QPS after caching              3,000
2    Mean query time                        4 ms                                 0.004 s
3    Queries in flight                      3,000 x 0.004                        12 connections active
4    App nodes                              20, each pool of 10                  200 connections, 188 idle
5    Fix                                    PgBouncer, pool 20                   20 server connections serve all
6    Write rate                             300 commits/s, 2 KB WAL each         0.6 MB/s = 52 GB per day of WAL
7    Archive for PITR, 7 days               52 GB x 7                            about 360 GB of WAL archive

Real scenarios: a deployment that scales the app from 10 to 50 pods and opens 50 x 20 = 1,000 connections to a database set up for 100; an UPDATE of a million rows that produces gigabytes of WAL and a replica that lags for ten minutes; a database on a 3,000 IOPS volume that is fine until a report scans a table and the application queries start to wait for I/O (see Billion-row tables and Connection pooling).

Cost estimation basics Important ​

In plain words: Every resource has a price per unit: compute per hour, storage per GB-month, requests per million, data leaving the cloud per GB. Multiply the quantities you just estimated by these prices to get a monthly bill.

Common misunderstanding: "Compute is the biggest bill." For many data-heavy products the biggest lines are egress (data transfer out), cross-zone and cross-region traffic, and storage that nobody deleted. Compute is easy to see and easy to scale down; the others are slow to notice.

Definition: Monthly cost = Σ (quantity x unit price). Cost per request = monthly cost / monthly requests. Prices change, vary by region and commitment (on-demand, reserved, spot), and must be re-read from the provider's page on the day you decide. The AWS pricing pages (S3, EC2) list the billing dimensions: S3 storage is billed per GB-month by storage class, plus request charges; EC2 data transfer out to the internet has a free monthly allowance and tiered per-GB prices (first 10 TB, next 40 TB, and so on) and data transfer in is free. The pages we fetched (Nov 2026) render the numeric prices dynamically, so the numbers below are assumptions for the exercise, not quotations; fetch the live price on the day.

Billing lineUnitIllustrative rate (assumption)Where to read the real one
Object storage, standardUSD per GB-month0.023AWS S3 pricing page; Google Cloud Storage pricing page
General-purpose VM, 8 vCPU / 32 GBUSD per hour0.35AWS EC2 on-demand pricing; Google Compute Engine pricing
Managed block storage (SSD)USD per GB-month0.08 to 0.12EBS or Persistent Disk pages
Internet egress, first tierUSD per GB0.09AWS EC2 data-transfer section; same dimension on every cloud
CDN egress, high volumeUSD per GB0.02 to 0.08The CDN's own page
Cross-AZ trafficUSD per GB each wayabout 0.01Provider data-transfer pages
Requests to object storageUSD per 1,000 or milliontiny but multiplied by billionsS3 pricing, request section
text
     Step                                   Calculation                          Monthly cost
1    Image service: 2.19 PB stored          2,190,000 GB x 0.023                 about 50,400 USD at year 3
2    Egress 0.9 Gbit/s average              113 MB/s x 2.59 M s = 294 TB         294,000 GB x 0.09 = 26,500 USD
3    Same through a CDN at 0.02             294,000 GB x 0.02                    5,900 USD (when the contract allows it)
4    12 app nodes                           12 x 0.35 x 730 h                    about 3,100 USD
5    Cost per 1,000 requests                total / (579 x 2.59 M / 1,000)       compute is a rounding error

Takeaway: at this shape the bill is storage and egress, not servers. That is a product and architecture question: do you need all originals forever, tiered storage, lifecycle rules, a CDN contract. Per-request cost is a useful sanity check for pricing: if a request earns 0.0001 USD and costs 0.0003 USD, no tuning of the code will help.

Headroom and growth: the 2x rule, the 3-year horizon Important ​

In plain words: Build for the peak you expect, then leave room: double it for surprises, and check that the design survives three years of growth before it needs to be rewritten, even if you do not buy that capacity today.

Common misunderstanding: "Headroom is waste." Headroom is the price of surviving a failure: with N nodes at 80 percent utilization, losing one node pushes the rest over 100 percent. Google's SRE material plans for failure of a unit (N+1 or N+2) on top of growth.

Definition: Capacity target = peak demand x headroom factor (typically 2x for services, 1.3 to 1.5x when scaling is fast and automatic) x growth over the planning horizon, and nodes = ceil(that / usable per node) + redundancy (N+1). Distinguish what you provision today (for the next quarter) from what the architecture must support (the three-year bound).

Planning itemRule of thumb
Peak margin2x the estimated peak, until you have measured peaks
Failure marginN+1 nodes; N+2 when one node loss during maintenance is plausible
Zone failureIf 3 zones, each at most 60 to 66 percent so two can carry the load
GrowthUse the product plan, not a hope: 20 percent per quarter doubles in 4 quarters (1.2^4 = 2.07)
HorizonProvision for 6 to 12 months; verify the architecture holds at 3 years
Storage growthLinear with retention, or exponential with user growth: compute both
Lead timeHardware or reserved capacity weeks to months; cloud minutes, but quotas take days
text
     Quarter   Peak QPS (growth 20%/qtr)   Nodes at 200 x 0.6 = 120 in flight each (L = QPS x 0.05)
1    Q0        6,944                        3
2    Q1        8,333                        4
3    Q2        10,000                       5
4    Q4        14,400                       6
5    Q8        29,860                       13
6    Q12       61,900                       26
     Reading: 3 years later, the same product needs about 9x the capacity; ask which part of the architecture stops scaling first.

Percentiles and peaks: p99 vs mean Must-know ​

In plain words: Averages hide the worst moments. If 1 request in 100 takes ten seconds, the mean looks fine, yet a page that makes 30 backend calls will hit a slow one on about one page view in four.

Common misunderstanding: "Use QPS as the capacity unit." Google's SRE book states the opposite:

"We learned this lesson the hard way: modeling capacity as 'queries per second' or using static features of the requests that are believed to be a proxy for the resources they consume (e.g., 'how many keys are the requests reading') often makes for a poor metric." — Google SRE book, chapter 21 Handling Overload, section "The Pitfalls of 'Queries per Second'"

They recommend measuring capacity directly in resources, typically CPU consumption. Use QPS to estimate and to test; then convert to CPU, memory and I/O per request through measurement.

Definition: Percentile p99 is the latency that 99 percent of requests are faster than. For a request that fans out to n backends, the chance that at least one is slower than its own p99 is 1 - 0.99^n: 10 backends 9.6 percent, 30 backends 26 percent, 100 backends 63 percent. This is the "tail at scale" effect (Dean and Barroso, The Tail at Scale, CACM 2013; named here from memory, not fetched). Plan with p95 or p99 service times, not with the mean, and plan the peak, not the average.

text
     Step                                   Calculation                          Result
1    Backends per page view                 30
2    Each backend: 1% of calls slow         p = 0.01
3    Chance all 30 are fast                 0.99^30                              0.74
4    Chance a page hits a slow one          1 - 0.74                             26%
5    The mean latency of a backend          looks fine                           the page p50 is not the backend p50

See Latency Budgets, Geography and Tail Latency for hedged requests and timeouts, and SLAs, SLOs, SLIs and Error Budgets for turning a percentile into a promise.

Mechanics: the estimation routine ​

The ten-minute routine Must-know ​

  1. Write the assumptions as a list with units: DAU, actions per user, object sizes, retention, read:write, peak factor, replication, latency target. State which are given, which are guessed.
  2. Compute QPS (average, peak, read, write) at each layer you care about.
  3. Compute storage per day and total over retention, with overhead, indexes and copies.
  4. Compute bandwidth (ingress and egress), then the effect of a CDN.
  5. Compute in-flight requests (Little) and nodes; compute connections for the database.
  6. Compute cache size from the hot fraction and the queue lag from the rates.
  7. Apply headroom; find the first bottleneck: the resource closest to a limit.
  8. Compare with one machine's limits and write the decision (choosing).
  9. State the uncertainty: which input would change the answer by 10x.
  10. Plan a measurement that would prove the estimate wrong (lab).
ResourcePractical limit of one commodity server (2025, order of magnitude)Source type
Simple HTTP handler, Go net/http, small JSON20,000 to 100,000 requests/s per node on a few coresMeasure; Go documents the API, not throughput
Laravel on PHP-FPM, simple route100 to 500 requests/s per core, 500 to 3,000 per nodeMeasure; depends on bootstrap and I/O
Laravel Octane (Swoole, RoadRunner, FrankenPHP)2 to 5 times FPM for simple routesMeasure
PostgreSQL, primary-key reads, cached20,000 to 100,000 QPS per nodeMeasure with pgbench
PostgreSQL, writes with fsync5,000 to 30,000 commits/s with group commit on NVMeMeasure
Redis, simple commands100,000+ ops/s per instance, single-threaded command executionRedis docs, benchmark
Kafka broker100 to 500 MB/s per broker with fast disks and enough networkKafka docs and your own test
1 Gbit/s NIC125 MB/sArithmetic
NVMe SSD100,000+ IOPS, 1 to 7 GB/sVendor spec, then measure
RAM per node64 to 512 GB common, up to TBsInstance catalogue

These ranges are deliberately wide, are not official benchmarks (the Go and Nginx project pages publish no throughput numbers), and exist to show scale: if your estimate says 300 QPS you are in "one node" territory for any of these, and if it says 300,000 you are in "a fleet" territory. Replace them with your own measurements as soon as you have a handler to measure.

Where estimates go wrong: error table ​

MistakeSymptomTypical errorFix
Ignoring the peakOutage at 20:00 though the daily mean looked fine3 to 10xUse peak factor; check the traffic graph
Mean instead of p99Page slow for 1 user in 42 to 10x latencyPlan with p99, fan-out maths
Forgetting replicasDisk full, cost 3x higher3xMultiply by the replication factor
Forgetting indexesStorage underestimated1.5 to 3xMeasure pg_indexes_size
Bytes vs bitsLink saturated unexpectedly8xMultiply by 8 for bandwidth
Decimal vs binary prefixesInvoice mismatchup to 10% at TB scalePick one and say it
Counting users, not requestsQPS far too low10 to 100xAsk for requests per user
Not counting fan-outDatabase QPS 10x the edge QPS5 to 50xMultiply per layer
Ignoring retentionLinear growth foreverunboundedLifecycle rules, partition drop
Ignoring write amplificationSSD wears, WAL explodes2 to 10xCount WAL, indexes, compaction
Using MAU instead of DAUOverbuild3 to 10xConvert DAU
Forgetting the cold startCache empty after a deploystampedeWarm up, request coalescing
Closed-loop load testTest hides the saturationmisleadingUse an open model (lab)

Go: an estimator CLI ​

The estimator is a pure function Estimate(Input) Result plus a small main with flags. Pure and flag-driven means you can run it in a meeting, in CI (assert that the estimate stays under a budget), or from a test. Units are decimal on purpose.

The estimate function ​

go
package main

import "math"

// Input holds every assumption of one back-of-the-envelope estimate.
// Decimal units are used on purpose: 1 GB = 1e9 bytes (estimates are rough anyway).
type Input struct {
	DAU                float64 // daily active users
	RequestsPerUser    float64 // requests per active user per day
	PeakFactor         float64 // peak QPS / average QPS (2-10 is typical)
	ReadsPerWrite      float64 // read:write ratio, 100 means 100 reads per write
	WritesPerUser      float64 // stored objects per active user per day
	PayloadBytes       float64 // application payload of one stored object
	RowOverheadBytes   float64 // tuple header + item pointer + alignment (PostgreSQL: about 28-40)
	IndexFactor        float64 // extra bytes for indexes as a fraction of table bytes (0.5 = +50%)
	ReplicationFactor  float64 // copies of the data (primary + replicas)
	RetentionDays      float64 // how long the data is kept
	ResponseBytes      float64 // average response size for a read
	LatencySeconds     float64 // mean time one request spends in the system (W in Little's law)
	ConcurrencyPerNode float64 // requests one node can hold in flight
	TargetUtilization  float64 // 0.6 means run nodes at 60% at peak
	HotFraction        float64 // fraction of stored data that is hot (0.2 = the 80/20 rule)
	Headroom           float64 // growth multiplier (2 = the 2x rule)
}

// Result is the output of Estimate.
type Result struct {
	AvgQPS, PeakQPS, PeakReadQPS, PeakWriteQPS float64
	DailyStoredBytes, TotalStoredBytes         float64
	IngressBitsPerSec, EgressBitsPerSec        float64
	InFlight                                   float64 // L = peak QPS x latency
	Nodes                                      int
	CacheBytes                                 float64
}

const secondsPerDay = 86400

// Estimate applies the standard formulas. It never returns an error: bad input
// (zeros) simply yields zeros, which is visible in the output.
func Estimate(in Input) Result {
	var r Result
	r.AvgQPS = in.DAU * in.RequestsPerUser / secondsPerDay
	r.PeakQPS = r.AvgQPS * in.PeakFactor
	writeShare := 1 / (in.ReadsPerWrite + 1)
	r.PeakWriteQPS = r.PeakQPS * writeShare
	r.PeakReadQPS = r.PeakQPS - r.PeakWriteQPS

	rowBytes := in.PayloadBytes + in.RowOverheadBytes
	perCopy := in.DAU * in.WritesPerUser * rowBytes * (1 + in.IndexFactor)
	r.DailyStoredBytes = perCopy * in.ReplicationFactor
	r.TotalStoredBytes = r.DailyStoredBytes * in.RetentionDays

	r.IngressBitsPerSec = r.PeakWriteQPS * in.PayloadBytes * 8
	r.EgressBitsPerSec = r.PeakReadQPS * in.ResponseBytes * 8

	r.InFlight = r.PeakQPS * in.LatencySeconds
	if usable := in.ConcurrencyPerNode * in.TargetUtilization; usable > 0 {
		r.Nodes = int(math.Ceil(r.InFlight / usable))
	}
	// The hot set is a fraction of one copy, not of all replicas.
	if in.ReplicationFactor > 0 {
		r.CacheBytes = r.TotalStoredBytes / in.ReplicationFactor * in.HotFraction
	}
	return r
}

// Headroomed returns the value multiplied by the growth factor.
func Headroomed(v, headroom float64) float64 { return v * headroom }

// QueueDrain says how long a backlog takes to clear, in seconds. When the
// consumers are not faster than the producers the backlog never drains (+Inf).
func QueueDrain(backlog, producePerSec, consumePerSec float64) float64 {
	if consumePerSec <= producePerSec {
		return math.Inf(1)
	}
	return backlog / (consumePerSec - producePerSec)
}

The command ​

go
// Command estimator prints a back-of-the-envelope capacity estimate.
//
//	go run ./estimator -dau 10e6 -req 20 -peak 3 -rw 100 -writes 0.5 -payload 300
package main

import (
	"flag"
	"fmt"
	"math"
	"os"
)

func human(v float64) string {
	units := []string{"B", "KB", "MB", "GB", "TB", "PB"}
	i := 0
	for v >= 1000 && i < len(units)-1 {
		v /= 1000
		i++
	}
	return fmt.Sprintf("%.2f %s", v, units[i])
}

func bits(v float64) string {
	units := []string{"bit/s", "Kbit/s", "Mbit/s", "Gbit/s", "Tbit/s"}
	i := 0
	for v >= 1000 && i < len(units)-1 {
		v /= 1000
		i++
	}
	return fmt.Sprintf("%.2f %s", v, units[i])
}

func main() {
	var in Input
	flag.Float64Var(&in.DAU, "dau", 1e6, "daily active users")
	flag.Float64Var(&in.RequestsPerUser, "req", 20, "requests per user per day")
	flag.Float64Var(&in.PeakFactor, "peak", 3, "peak / average QPS")
	flag.Float64Var(&in.ReadsPerWrite, "rw", 10, "reads per write")
	flag.Float64Var(&in.WritesPerUser, "writes", 1, "stored objects per user per day")
	flag.Float64Var(&in.PayloadBytes, "payload", 500, "payload bytes per stored object")
	flag.Float64Var(&in.RowOverheadBytes, "overhead", 40, "row overhead bytes (PostgreSQL ~ 28-40)")
	flag.Float64Var(&in.IndexFactor, "index", 0.5, "index bytes as a fraction of table bytes")
	flag.Float64Var(&in.ReplicationFactor, "replicas", 3, "copies of the data")
	flag.Float64Var(&in.RetentionDays, "retention", 365, "retention in days")
	flag.Float64Var(&in.ResponseBytes, "resp", 5000, "average read response bytes")
	flag.Float64Var(&in.LatencySeconds, "latency", 0.05, "mean request latency in seconds")
	flag.Float64Var(&in.ConcurrencyPerNode, "conc", 200, "in-flight requests per node")
	flag.Float64Var(&in.TargetUtilization, "util", 0.6, "target utilization at peak")
	flag.Float64Var(&in.HotFraction, "hot", 0.2, "hot fraction of the data")
	flag.Float64Var(&in.Headroom, "headroom", 2, "growth multiplier")
	flag.Parse()

	if in.DAU <= 0 || in.TargetUtilization <= 0 || in.ConcurrencyPerNode <= 0 {
		fmt.Fprintln(os.Stderr, "dau, util and conc must be positive")
		os.Exit(2)
	}
	r := Estimate(in)
	fmt.Printf("average QPS        %.0f\n", r.AvgQPS)
	fmt.Printf("peak QPS           %.0f (reads %.0f, writes %.0f)\n", r.PeakQPS, r.PeakReadQPS, r.PeakWriteQPS)
	fmt.Printf("stored per day     %s (all replicas, with indexes)\n", human(r.DailyStoredBytes))
	fmt.Printf("stored total       %s over %.0f days\n", human(r.TotalStoredBytes), in.RetentionDays)
	fmt.Printf("ingress at peak    %s\n", bits(r.IngressBitsPerSec))
	fmt.Printf("egress at peak     %s\n", bits(r.EgressBitsPerSec))
	fmt.Printf("in flight (L)      %.0f requests\n", r.InFlight)
	fmt.Printf("nodes              %d at %.0f%% utilization\n", r.Nodes, in.TargetUtilization*100)
	fmt.Printf("cache (hot set)    %s\n", human(r.CacheBytes))
	fmt.Printf("with %.0fx headroom  peak %.0f QPS, storage %s, nodes %d\n",
		in.Headroom, Headroomed(r.PeakQPS, in.Headroom), human(Headroomed(r.TotalStoredBytes, in.Headroom)),
		int(math.Ceil(Headroomed(float64(r.Nodes), in.Headroom))))
}

Tests that pin the arithmetic ​

go
package main

import (
	"math"
	"testing"
)

func TestEstimateURLShortener(t *testing.T) {
	in := Input{
		DAU: 10e6, RequestsPerUser: 1, PeakFactor: 3, ReadsPerWrite: 100,
		WritesPerUser: 0.01, PayloadBytes: 500, RowOverheadBytes: 40, IndexFactor: 0.5,
		ReplicationFactor: 3, RetentionDays: 365, ResponseBytes: 500,
		LatencySeconds: 0.02, ConcurrencyPerNode: 200, TargetUtilization: 0.6, HotFraction: 0.2,
	}
	r := Estimate(in)
	if math.Abs(r.AvgQPS-115.74) > 0.1 {
		t.Fatalf("avg QPS = %.2f", r.AvgQPS)
	}
	if r.Nodes != 1 {
		t.Fatalf("nodes = %d", r.Nodes)
	}
}

func TestQueueDrain(t *testing.T) {
	if got := QueueDrain(6000, 100, 200); got != 60 {
		t.Fatalf("drain = %v", got)
	}
	if !math.IsInf(QueueDrain(1, 100, 100), 1) {
		t.Fatal("equal rates must never drain")
	}
}

Run it:

bash
cd docs/snippets/architecture/capacity-estimation/go
go run ./estimator -dau 10e6 -req 1 -peak 3 -rw 100 -writes 0.01 -payload 500 -retention 1825 -resp 500 -latency 0.02
# average QPS        116
# peak QPS           347 (reads 344, writes 3)
# stored total       443.48 GB over 1825 days

The Go angle ​

  • net/http starts one goroutine per connection (HTTP/1.1) or per stream (HTTP/2); the cost per in-flight request is a few KB of stack, so L from Little's law is limited by CPU, memory and downstream pools, not by a thread count. The knobs that bound in-flight work are yours: http.Server{ReadHeaderTimeout, ReadTimeout, WriteTimeout, IdleTimeout}, MaxHeaderBytes, a semaphore channel for expensive handlers, and database/sql SetMaxOpenConns/SetMaxIdleConns/SetConnMaxLifetime.
  • database/sql pool size is Little's law applied: SetMaxOpenConns(qps_per_node * mean_query_seconds * 2), never more than the database can serve across all nodes.
  • Use time.Since around handlers and export a histogram (Prometheus client_golang) so p50 and p99 can be read; the estimate is only as good as its W.
  • runtime/pprof and go test -bench answer "CPU per request", which is the unit the SRE book prefers over QPS.

Laravel: an Artisan command ​

Laravel 13 declares a command's signature and description with the Signature and Description attributes (Illuminate\Console\Attributes\Signature, Illuminate\Console\Attributes\Description; Laravel 13 Artisan documentation). Options with defaults use {--name=default}. The arithmetic lives in a plain class so it is testable without the framework.

The arithmetic class ​

php
<?php

declare(strict_types=1);

namespace App\Support;

/**
 * Pure arithmetic for a back-of-the-envelope estimate. No framework, no I/O,
 * so it can be unit-tested and reused by the Artisan command and by a test.
 * Decimal units on purpose: 1 GB = 1e9 bytes.
 */
final class CapacityEstimator
{
    private const SECONDS_PER_DAY = 86400;

    /** @param array<string, float> $in keys: dau, req, peak, rw, writes, payload, overhead, index, replicas, retention, resp, latency, conc, util, hot */
    public function estimate(array $in): array
    {
        $avgQps = $in['dau'] * $in['req'] / self::SECONDS_PER_DAY;
        $peakQps = $avgQps * $in['peak'];
        $writeQps = $peakQps / ($in['rw'] + 1);
        $readQps = $peakQps - $writeQps;

        $rowBytes = $in['payload'] + $in['overhead'];
        $perCopyPerDay = $in['dau'] * $in['writes'] * $rowBytes * (1 + $in['index']);
        $dailyBytes = $perCopyPerDay * $in['replicas'];
        $totalBytes = $dailyBytes * $in['retention'];

        $inFlight = $peakQps * $in['latency']; // Little's law: L = lambda x W
        $usable = $in['conc'] * $in['util'];
        $nodes = $usable > 0 ? (int) ceil($inFlight / $usable) : 0;

        return [
            'avg_qps' => $avgQps,
            'peak_qps' => $peakQps,
            'peak_read_qps' => $readQps,
            'peak_write_qps' => $writeQps,
            'daily_bytes' => $dailyBytes,
            'total_bytes' => $totalBytes,
            'ingress_bps' => $writeQps * $in['payload'] * 8,
            'egress_bps' => $readQps * $in['resp'] * 8,
            'in_flight' => $inFlight,
            'nodes' => $nodes,
            'cache_bytes' => $in['replicas'] > 0 ? $totalBytes / $in['replicas'] * $in['hot'] : 0.0,
        ];
    }

    public function human(float $value): string
    {
        $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
        $i = 0;
        while ($value >= 1000 && $i < count($units) - 1) {
            $value /= 1000;
            $i++;
        }

        return sprintf('%.2f %s', $value, $units[$i]);
    }
}

The command ​

php
<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Support\CapacityEstimator;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;

// Usage: php artisan capacity:estimate --dau=10000000 --req=1 --rw=100 --writes=0.01
#[Signature('capacity:estimate
    {--dau=1000000 : Daily active users}
    {--req=20 : Requests per user per day}
    {--peak=3 : Peak QPS divided by average QPS}
    {--rw=10 : Reads per write}
    {--writes=1 : Stored objects per user per day}
    {--payload=500 : Payload bytes per stored object}
    {--overhead=40 : Row overhead bytes}
    {--index=0.5 : Index bytes as a fraction of table bytes}
    {--replicas=3 : Copies of the data}
    {--retention=365 : Retention in days}
    {--resp=5000 : Average read response bytes}
    {--latency=0.05 : Mean request latency in seconds}
    {--conc=200 : In-flight requests one node can hold}
    {--util=0.6 : Target utilization at peak}
    {--hot=0.2 : Hot fraction of the data}
    {--headroom=2 : Growth multiplier}')]
#[Description('Back-of-the-envelope QPS, storage, bandwidth and node estimate')]
class EstimateCapacity extends Command
{
    public function handle(CapacityEstimator $estimator): int
    {
        $in = [];
        foreach (['dau', 'req', 'peak', 'rw', 'writes', 'payload', 'overhead', 'index',
            'replicas', 'retention', 'resp', 'latency', 'conc', 'util', 'hot', 'headroom'] as $key) {
            $in[$key] = (float) $this->option($key);
        }

        if ($in['dau'] <= 0 || $in['util'] <= 0 || $in['conc'] <= 0) {
            $this->error('dau, util and conc must be positive');

            return self::FAILURE;
        }

        $r = $estimator->estimate($in);
        $h = $in['headroom'];

        $this->table(['Quantity', 'Value'], [
            ['average QPS', number_format($r['avg_qps'])],
            ['peak QPS', number_format($r['peak_qps']) . sprintf(' (reads %s, writes %s)',
                number_format($r['peak_read_qps']), number_format($r['peak_write_qps']))],
            ['stored per day (all copies)', $estimator->human($r['daily_bytes'])],
            ['stored total', $estimator->human($r['total_bytes'])],
            ['ingress at peak', number_format($r['ingress_bps'] / 1e6, 2) . ' Mbit/s'],
            ['egress at peak', number_format($r['egress_bps'] / 1e6, 2) . ' Mbit/s'],
            ['in flight (L = lambda x W)', number_format($r['in_flight'])],
            ['nodes', (string) $r['nodes']],
            ['cache (hot set)', $estimator->human($r['cache_bytes'])],
            ["with {$h}x headroom: peak QPS", number_format($r['peak_qps'] * $h)],
            ["with {$h}x headroom: storage", $estimator->human($r['total_bytes'] * $h)],
        ]);

        return self::SUCCESS;
    }
}
bash
php artisan capacity:estimate --dau=10000000 --req=1 --rw=100 --writes=0.01 --payload=500 --retention=1825

The Laravel angle ​

  • PHP-FPM holds one request per worker, so L maps directly to pm.max_children: workers needed = peak QPS x mean request seconds, per node; memory per worker (often 30 to 80 MB for Laravel) times children must fit in RAM. This is the most common sizing mistake in Laravel deployments.
  • Octane (Swoole, RoadRunner or FrankenPHP) keeps the framework booted and serves requests from long-lived workers; you set the worker count with --workers, and the same Little's-law arithmetic applies; the gain is a smaller W for the framework bootstrap.
  • Database connections: each FPM worker may hold one connection; 20 nodes x 32 workers = 640 connections against max_connections = 100 is the classic deployment incident. Put PgBouncer in front.
  • Queues: workers needed = jobs per second x seconds per job; Horizon (for Redis queues) auto-balances by queue and exposes wait time per queue, a direct measurement of backlog.
  • Cache: Cache::remember with Redis; estimate bytes per key from the serialised value, not from the model.

Solving the classic problems: five worked examples ​

The numbers come from the Go estimator; each table is reproducible with the command shown. The assumptions are the inputs; change them and the conclusion may change, which is the point.

Twitter-like timeline Must-know ​

go run ./estimator -dau 100e6 -req 40 -peak 3 -rw 20 -writes 2 -payload 300 -retention 1825 -resp 10000 -latency 0.1 -conc 500 -hot 0.002

QuantityAssumption or formulaResult
DAUgiven100 M
Requests per user per day40 (timeline refreshes and profile views)4 B per day
Average QPS4 B / 86,40046,300
Peak QPSx 3139,000
Read:write20:1 (reads = timeline loads)6,600 writes, 132,000 reads at peak
Object2 posts per user per day, 300 B payload, 40 B overhead, indexes +50%, 3 copies306 GB per day
Retention 5 years306 GB x 1,825558 TB (1.1 PB with 2x headroom)
Egress at peak132,000 x 10 KB x 810.6 Gbit/s
In flight139,000 x 0.1 s13,900
Nodes13,900 / (500 x 0.6)47 (94 with headroom)
Cachehot 0.2% of one copy (the last few days of posts)372 GB

Reading the table: storage is manageable, the read path (10 Gbit/s egress, 132,000 reads) dominates. The write rate is small enough for one primary, but delivering each post to followers' timelines is a fan-out: a user with 1 M followers makes one post a write of 1 M timeline entries. Two designs follow: fan-out on write (precompute timelines in a cache: more write work, fast reads) or fan-out on read (compute at read time: cheap writes, heavy reads); in practice hybrid for celebrities. This is the feeds and fan-out chapter. The estimate told you where the problem is before any design.

URL shortener ​

go run ./estimator -dau 10e6 -req 1 -peak 3 -rw 100 -writes 0.01 -payload 500 -retention 1825 -resp 500 -latency 0.02 -conc 200

QuantityAssumption or formulaResult
Redirects per user per day110 M per day
New URLs0.01 per user per day100,000 per day
Average / peak QPS116 / 347344 reads, 3 writes at peak
Object500 B (long URL, metadata) + 40 overhead, indexes +50%, 3 copies243 MB per day
Retention 5 yearsx 1,825443 GB total, 887 GB with headroom
Egress344 x 500 B x 81.4 Mbit/s
In flight347 x 0.027
Nodes7 / (200 x 0.6)1 (2 for failover)
Key spacebase62, 7 characters62^7 = 3.5 trillion, enough for 100,000 per day for 95,000 years
Cache20% of one copy30 GB; the real hot set is far smaller

Reading: the whole service fits on one primary PostgreSQL and two small app nodes. Everything else (sharding, Kafka, microservices) is optional and must be justified by something other than load. The interesting problem is ID generation (ID generation at scale), not capacity.

Image upload service ​

go run ./estimator -dau 5e6 -req 10 -peak 4 -rw 49 -writes 0.2 -payload 2e6 -overhead 40 -index 0 -replicas 1 -retention 1095 -resp 200000 -latency 0.3 -conc 100 -hot 0.01

QuantityAssumption or formulaResult
Uploads0.2 per user per day = 1 M per day, 2 MB each2 TB per day
Replicas1 logical copy (an object store keeps its own copies and bills the logical size)2 TB per day
Retention 3 yearsx 1,0952.19 PB (4.4 PB with 2x headroom)
Peak QPS579 average, x 42,315 (2,269 reads, 46 uploads)
Ingress46 uploads/s x 2 MB x 8741 Mbit/s
Egress2,269 x 200 KB x 83.6 Gbit/s
In flight2,315 x 0.3694
Nodes694 / (100 x 0.6)12
Hot set1% of the data22 TB (a CDN, not RAM)

Reading: the metadata database is tiny (1 M rows per day, about 100 GB per year) and the load sits in object storage and the network. Decisions that follow: store the bytes in object storage (S3 compatible), keep only metadata in PostgreSQL, upload directly from the client with pre-signed URLs so the app never carries 741 Mbit/s, generate thumbnails asynchronously through a queue, and put a CDN in front of 3.6 Gbit/s of reads. See object storage and CDN.

Chat application ​

go run ./estimator -dau 20e6 -req 80 -peak 5 -rw 1 -writes 40 -payload 150 -index 0.3 -retention 730 -resp 150 -latency 0.03 -conc 1000

QuantityAssumption or formulaResult
Messages40 sent per user per day = 800 M per day800 M
Requests80 per user per day (send + receive/ack)1.6 B per day
Average / peak QPS18,500 / x 592,600 (46,300 reads, 46,300 writes)
Object150 B payload + 40 overhead, indexes +30%, 3 copies593 GB per day
Retention 2 yearsx 730433 TB (870 TB with headroom)
Bandwidth46,300 x 150 B x 856 Mbit/s each way (before headers and TLS)
Concurrent connectionsPCU about 10% of DAU, one websocket each2 M open connections
Memory for connections2 M x about 10 KB20 GB across the gateway fleet
Nodes for the gateway2 M / (50,000 per node)40 nodes

Reading: the load is not bandwidth but connections and write rate: 46,000 writes per second is beyond one comfortable PostgreSQL primary, so messages go to a store that shards by conversation (Cassandra, ScyllaDB, DynamoDB or a sharded SQL), usually with a queue in front. The 2 M connections need an event-driven gateway (Go goroutines or an Elixir/Erlang style runtime fit; classic PHP-FPM does not hold a connection per user; Laravel Reverb or a Go service holds them). See real-time protocols and Wide-column and key-value at scale.

Analytics ingestion ​

go run ./estimator -dau 50e6 -req 200 -peak 4 -rw 0.01 -writes 200 -payload 400 -overhead 0 -index 0 -retention 90 -resp 100 -latency 0.01 -conc 500 -hot 0.05

QuantityAssumption or formulaResult
Events200 per user per day = 10 B per day10 B
Average / peak QPS115,700 / x 4463,000 (almost all writes)
Payload400 B per event, no row overhead (columnar or log format), 3 copies12 TB per day
Retention 90 daysx 901.08 PB (2.2 PB with headroom)
Ingress458,000 x 400 B x 81.5 Gbit/s into the edge
Kafka memorywrite throughput 183 MB/s x 30 s (Kafka docs rule)about 5.5 GB of page cache per copy
In flight463,000 x 0.014,630
Nodes for collectors4,630 / (500 x 0.6)16

Reading: no relational database takes 463,000 writes per second row by row. The design is a log (Kafka), batch inserts into a columnar store (ClickHouse, BigQuery, Parquet on object storage), and aggregation by time windows. Estimation already told us that "INSERT per event into PostgreSQL" is the wrong style; see Big data architectures and OLTP vs OLAP.

ExampleFirst bottleneckStyle it points to
TimelineRead fan-out, egress 10 Gbit/sCache + precomputed timelines + CDN for media
URL shortenerNone (one node)Boring monolith; spend the time on IDs and abuse
Image uploadObject storage and egressObject store + CDN + async workers; tiny metadata DB
ChatConnections and writesEvent-driven gateway + sharded wide-column store + queue
Analytics ingestionWrite rateLog + batch + columnar store

Choosing: what the numbers say about architecture ​

Estimated peak loadTypical single-node capabilityDecisionExtra technique
Up to about 1,000 QPS, data under 1 TBOne app node, one PostgreSQL primaryMonolith, a standby for failoverBackups, one replica; no cache yet
1,000 to 10,000 QPS, reads dominateSeveral app nodes, one primary, read replicasModular monolith; add Redis cache and read replicasConnection pooler; CDN for static files
10,000 to 100,000 QPSMultiple app nodes, sharded or partitioned data stores likelyModular monolith or a few services split by load shape (e.g. media, feed)Partitioning, queue for writes, CDN
Writes above about 10,000 per second sustained on relationalOne primary is at the edgeShard by key, or move that data to a log/wide-column storeBatching, async
Data over 5 to 10 TB in one PostgreSQLBackups and vacuum become slowPartition and archive; sharding thought throughSee partitioning and sharding
Egress over 1 Gbit/s of cacheable contentA NIC and a billCDNCache headers, image sizes
Global users, latency target under 100 msCross-region 70 to 150 msRegional deployments, multi-region readsSee replication topologies
100,000+ QPS or PB-scale dataNot one node anywhereDistributed data tier, dedicated platform teamEverything above

Rules of thumb that come out of the tables (they are heuristics; confirm with a measurement):

RuleReason
A monolith on one well-sized PostgreSQL is fine up to a few thousand QPS and a few TBThe numbers fit one machine; the cost of distribution is higher than the benefit
Shard when one primary cannot take the write rate or the data does not fit, not beforeSharding is irreversible and complicates every query
Add a cache when read QPS x (1 - hit ratio) is below what the database handles and latency mattersA cache is one more thing to invalidate
Add a CDN when static or public bytes make up most of the egressPays for itself on the first bill
Split a service for team autonomy or divergent load shape, not for "scale"See monolith vs microservices vs modular
A queue helps peaks (time) but not sustained overloadLittle's law, queue sizing

In architecture: from a single process to a distributed system ​

The same arithmetic changes meaning as the system grows. The estimate decides when to cross each stage, not whether the stage is "modern".

Monolith: one process, one database ​

Everyday example: a school's grade portal, 5,000 students and staff, 2,000 DAU, 30 requests per user per day: 60,000 requests per day, 0.7 QPS average, 3 QPS at peak (exam results day: 50 QPS). Storage: 100 bytes x 20 grades x 5,000 students x 12 years = 120 MB. One Laravel app on one small VM and one PostgreSQL; the estimate says "stop worrying", which is a result.

Production example: a SaaS back office at 1,500 QPS peak and 400 GB. One PostgreSQL primary (16 cores, 64 GB RAM), PgBouncer, two app nodes behind a load balancer, one hot standby. The estimate shows connection count (not QPS) as the first limit, so PgBouncer comes before any "scaling" project. Related: layered monolith.

Modular monolith and multiple databases ​

Everyday example: a shop whose estimate gives 3,000 QPS (80% reads on product pages) and 500 GB. Modules (catalogue, orders, billing) stay in one deployable, so the estimate is one number; a Redis cache absorbs the catalogue reads and two read replicas serve reports.

Production example: the same shop on a sale day: peak factor 20 for 30 minutes. The estimate shows the checkout write path at 400 QPS is fine; the product page reads at 20,000 QPS are the problem. The decision is cache and CDN for the catalogue, not a split into services. Each module owns its schema and its estimate section, so a module's growth can be seen separately; see Modular Monolith.

Microservices: the estimate per service ​

Everyday example: extract the image processing from the monolith because the estimate showed 12 nodes of CPU-heavy work against a 3-node web tier. The reason is the different load shape, which also differs in scaling unit; the contract is a queue message {image_id, sizes}.

Production example: an order flow where every extra service hop adds a round trip (0.5 ms, plus serialisation) and a failure probability. With 6 synchronous hops at p99 of 20 ms each, the page p99 is far above 120 ms (tail amplification); the estimate changes the design to fewer hops or async events. Each service gets its own estimate sheet: QPS in, QPS out (fan-out), storage, in-flight, and a dependency budget; see Microservices Architecture, Service communication and Data ownership. The cost of a network call is a number from the latency ladder, not an opinion.

Distributed data: replicas, caches and regions ​

Everyday example: a recipe site adds a read replica. Estimate: reads 5,000 QPS, one primary handles 2,000; two replicas at 2,500 each. Replica lag becomes a new quantity (WAL rate vs replay rate), and read-your-writes needs routing; see Replication.

Production example: a global product with users in Europe and Asia. The cross-region round trip (80 to 150 ms) makes a synchronous cross-region commit cost that much per write, so the design keeps writes in one home region per user and reads local; CAP and PACELC trade-offs apply (CAP and PACELC). Storage multiplies by the number of regions, and egress between regions is billed. Sharding thresholds: when one primary cannot fit the data (a few TB comfortable, 10 TB painful) or write rate, shard by a key with even spread (consistent hashing).

Scaling path: 1x, 10x, 100x ​

LoadEstimate showsTypical stepEstimate to re-run
1x (about 500 QPS, 50 GB)One node is enoughMonolith, backups, monitoringBaseline: write the numbers on the wiki
10x (about 5,000 QPS, 500 GB)Connections and read QPS bitePooler, cache, read replica, CDN for staticDB connections, hit ratio, replica lag
100x (about 50,000 QPS, 5 TB)One primary's writes or size is at the limitPartitioning, queue for writes, possibly sharding or a different store for the hot dataWrite QPS, WAL, in-flight per tier
1,000x (about 500,000 QPS, 50 TB)No single machine anywhereDistributed data tier, regional deployment, dedicated platformEverything, plus cost per request

The honest conclusion: most products live in the first two rows for years. An estimate that shows 300 QPS is not a reason for Kubernetes; an estimate that shows 300,000 QPS is not a reason for hope.

Lab: estimate, then measure ​

Goal: predict the throughput and latency of a Go handler and a Laravel endpoint, then measure with hey or k6 and explain the difference. Tooling status on the authoring machine: Go is installed (the estimator and the handler compile, go vet is clean and the unit tests pass); hey, k6, vegeta and php are not installed, so the load-test steps below are written from each tool's documentation (the hey README and the k6 open-versus-closed-model page) and were not run here. Run them on your machine.

Setup.

bash
cd docs/snippets/architecture/capacity-estimation/go
go run ./handler            # listens on :8080; WORK_MS=20 by default
# install a load generator (any one):
#   go install github.com/rakyll/hey@latest
#   brew install k6
go
// Command handler is the lab target: one endpoint whose service time is known,
// so a measured p50 can be compared with the estimate.
package main

import (
	"encoding/json"
	"log"
	"net/http"
	"os"
	"sync/atomic"
	"time"
)

var inFlight atomic.Int64

func main() {
	work := 20 * time.Millisecond // the "W" you will predict and then measure
	if v := os.Getenv("WORK_MS"); v != "" {
		if d, err := time.ParseDuration(v + "ms"); err == nil {
			work = d
		}
	}
	mux := http.NewServeMux()
	mux.HandleFunc("GET /item", func(w http.ResponseWriter, r *http.Request) {
		inFlight.Add(1)
		defer inFlight.Add(-1)
		time.Sleep(work) // stands in for a database call
		w.Header().Set("Content-Type", "application/json")
		_ = json.NewEncoder(w).Encode(map[string]any{"id": 42, "name": "demo", "in_flight": inFlight.Load()})
	})
	srv := &http.Server{
		Addr:              ":8080",
		Handler:           mux,
		ReadHeaderTimeout: 5 * time.Second,
	}
	log.Printf("listening on %s, work=%s", srv.Addr, work)
	log.Fatal(srv.ListenAndServe())
}

The Laravel side is a route with the same artificial work (put it in routes/web.php, run under Octane or php-fpm; do not use php artisan serve, which is single-process):

php
<?php

declare(strict_types=1);

// routes/web.php (or routes/api.php): the lab target. usleep stands in for a
// database call with a known service time, so measured p50 can be compared
// with the predicted W. Run under Octane or php-fpm, never `artisan serve`.

use Illuminate\Support\Facades\Route;

Route::get('/item', function () {
    usleep((int) env('WORK_MS', 20) * 1000);

    return response()->json(['id' => 42, 'name' => 'demo']);
});

Experiments.

  1. Predict. The handler sleeps 20 ms, so W = 0.02 s. With 50 concurrent clients, Little's law gives throughput = L / W = 50 / 0.02 = 2,500 requests/s, if nothing else limits. Write that number down before running anything. Also predict p50 (about 20 ms) and p99 (about 25 to 40 ms).
  2. Measure, closed model, hey. hey -z 30s -c 50 http://localhost:8080/item. Expected: about 2,000 to 2,400 requests/s, p50 about 21 ms. (The hey README documents -n for number of requests, -c for concurrent workers, -q for a per-worker rate limit and -z for duration.) The shortfall from 2,500 is timer granularity and scheduling.
  3. Change the concurrency. Run with -c 10, -c 100, -c 500. Expected: throughput scales with -c until a bottleneck appears (CPU on the load generator, file descriptors, the 100-connection database pool in a real app), then latency rises and throughput flattens. Mark the knee.
  4. Open model, k6. Use the script below with rate: 500, then raise it to 2,000 and 5,000. In an open model, arrivals do not wait for responses; a closed-model tool hides saturation because "the load generator slows down as the server slows down". The k6 documentation describes this effect as coordinated omission.
  5. Laravel. Repeat 2 to 4 against the Laravel route. Predict first: with PHP-FPM, pm.max_children = 16 and W = 25 ms (20 ms sleep + 5 ms framework), the ceiling is 16 / 0.025 = 640 requests/s per node. Compare.
  6. Compare and write down the gap. For each tool and target record predicted vs measured throughput and p50, p99. A gap above 30 percent means an assumption was wrong: find which (W, concurrency, the load generator itself, CPU limit).
js
// k6 run -e BASE=http://localhost:8080 loadtest.js
// Open model: the arrival rate is fixed, so a slow server cannot slow the test down.
import http from 'k6/http';
import { check } from 'k6';

export const options = {
  scenarios: {
    steady: {
      executor: 'constant-arrival-rate',
      rate: 500, // iterations per timeUnit = the QPS you predicted
      timeUnit: '1s',
      duration: '60s',
      preAllocatedVUs: 50,
      maxVUs: 500,
    },
  },
  thresholds: { http_req_duration: ['p(99)<200'] },
};

export default function () {
  const res = http.get(`${__ENV.BASE}/item`);
  check(res, { ok: (r) => r.status === 200 });
}
text
     Run                          Predicted         Expected result (shape, not a promise)
1    hey -c 50, Go, W=20 ms       2,500 req/s       about 2,000-2,400 req/s, p50 about 21 ms
2    hey -c 500, Go               5,000 would need  throughput flattens at the CPU or fd limit, p99 rises
3    k6 open model, 500/s         500 req/s         500 req/s, p99 close to 25 ms, dropped_iterations = 0
4    k6 open model, 5,000/s       5,000 req/s       dropped_iterations rise or VUs run out: the overload shows
5    Laravel FPM, 16 workers      640 req/s         a plateau near 600; beyond it requests queue

Cleanup: stop the handler (Ctrl-C). Nothing is written to disk.

Common misconceptions ​

BeliefReality
"Estimation needs exact numbers"You need the order of magnitude and honest assumptions; a factor of 2 is normal and covered by headroom
"The average QPS is the load"The peak is the load; the average is the denominator of the peak factor
"A 1 Gbit/s link moves 1 GB/s"It moves 125 MB/s at most, about 100 MB/s in practice
"One row equals the sum of its columns"Add the tuple header, item pointer, alignment, indexes, free space and replicas
"More servers make each request faster"They raise throughput; latency changes only if queueing was the cause
"Cache size = data size"The hot working set is usually 10 to 20 percent, measure the hit ratio
"QPS is a good capacity unit"Requests differ; the SRE book recommends CPU and other resources as the unit
"Little's law needs exponential arrivals"It holds for any stable system; only the M/M/1 delay curve assumes that model
"A queue protects against overload"It moves the problem in time; if consumers are not faster than producers the backlog only grows
"Cloud means compute is the bill"Storage, egress and cross-zone traffic are often larger
"99 percent fast means 99 percent of pages are fast"A page with 30 backend calls is slow about 26 percent of the time
"Run the load test to find the number"A load test validates a prediction; without a prediction you cannot tell if the result is good

Cheat sheet ​

TopicWhat to remember
Seconds per day86,400; 10^5 for mental math; 1 M per day is about 12 QPS
Bits vs bytesBandwidth in bits: multiply bytes by 8; 1 Gbit/s is 125 MB/s
PeakPeak = average x 2 to 10; size for the peak
Read:write100:1 social, 10:1 SaaS, 1:1 chat, 1:100 telemetry
Row sizePayload + 24 header + 4 pointer + padding, then indexes (+50% to +200%)
ReplicasMultiply storage by copies; object stores bill logical bytes
RetentionTotal = daily x days; no policy means linear growth forever
Latency ladderMemory 100 ns, SSD 20 to 100 us, DC RTT 0.5 ms, disk seek 10 ms, cross-region 70 to 150 ms
LittleL = lambda x W; servers = L / (per-node concurrency x utilization)
UtilizationPlan 50 to 70 percent at peak; delay explodes above 80
Cache10 to 20 percent hot set; 90 percent hit ratio cuts backend load 10x
QueueDrain time = backlog / (consume - produce); never drains if not faster
DBConnections = QPS x query seconds; default max_connections is typically 100; pool with PgBouncer
Headroom2x peak, N+1 nodes, check the 3-year bound
CostStorage, egress and cross-zone first; compute last; re-read prices on the day
ValidateEstimate, then measure with an open-model test, then fix the model

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A product has 5 M DAU and each user makes 30 requests per day. What are the average and the peak QPS with a peak factor of 4? Must-know ​

Answer

Answer: Requests per day = 150 M; average QPS = 150,000,000 / 86,400 = 1,736; peak = 1,736 x 4 = 6,944. State the layer (edge, app or database) and the peak factor, because both change the answer.

2 — Why is a 1 Gbit/s NIC not enough for 5,000 QPS at 50 KB per response? Must-know ​

Answer

Answer: 5,000 x 50,000 B x 8 = 2 Gbit/s, which is twice the link; at a 70 percent target it needs about 3 Gbit/s, so use 10 Gbit/s NICs, compression, or a CDN.

3 — A row has 60 bytes of payload and two indexes. Roughly how large is it in PostgreSQL? Good to know ​

Answer

Answer: About 60 + 24 header + 4 item pointer + padding, around 92 bytes in the table, plus index entries of roughly 30 to 40 bytes each, so about 160 bytes with both indexes, 2.5 to 3 times the payload, before replicas and free space.

4 — State Little's law and use it to size a thread pool for 800 requests per second with a mean time of 25 ms. Must-know ​

Answer

Answer: L = lambda x W = 800 x 0.025 = 20 requests in flight on average; with a target utilization of 60 percent the pool needs about 20 / 0.6 = 34 slots, plus headroom; pool size must also respect downstream limits.

5 — Producers write 100 messages per second, consumers handle 150. A backlog of 6,000 exists. When is it empty? Must-know ​

Answer

Answer: Drain rate 50 per second; 6,000 / 50 = 120 seconds. If consumers handled only 100, the backlog would never drain.

6 — Why plan for 70 percent utilization instead of 95? Important ​

Answer

Answer: In queueing the delay rises sharply near saturation (M/M/1: 3.3x service time at 70 percent, 20x at 95), a node failure shifts load onto the remaining nodes, and bursts need spare capacity.

7 — Which of the five worked examples needs a CDN and why? Good to know ​

Answer

Answer: The image service (3.6 Gbit/s egress of cacheable thumbnails) and the timeline (10.6 Gbit/s, though mostly JSON, so cache and compression first, CDN for media). The URL shortener's 1.4 Mbit/s does not.

8 — What is wrong with sizing capacity by QPS alone? Must-know ​

Answer

Answer: Requests vary in cost and the ratio changes over time (Google SRE, "The Pitfalls of Queries per Second"); measure CPU, memory and I/O per request and size by those; use QPS for the first estimate and for the test.

9 — A page makes 30 backend calls, each with p99 = 100 ms. How often is the page slow? Important ​

Answer

Answer: 1 - 0.99^30 = 26 percent of page views contain at least one call at or above 100 ms; tail latency amplifies with fan-out.

10 — Why does the load test use an open model? Important ​

Answer

Answer: A closed model starts a new request only after the previous one finishes, so a slow server automatically lowers the offered load (coordinated omission); an open model keeps a fixed arrival rate and shows saturation.

11 — At what numbers would you stop at a monolith with one PostgreSQL, and what would make you shard? Important ​

Answer

Answer: A few thousand QPS and a few TB fit one well-sized node; shard when the write rate or the data size no longer fits one primary (for example sustained writes above roughly 10,000 per second, or data in the tens of TB), after caching, replicas and partitioning have been used.

Glossary ​

TermMeaning
DAU / MAUDaily / monthly active users; DAU is the start of a QPS estimate
QPS / RPSQueries or requests per second at a named layer
Peak factorPeak QPS divided by average QPS, typically 2 to 10
Read:write ratioHow many reads happen per write
Fan-outOne request that triggers many downstream operations (a post delivered to followers)
PayloadThe application bytes of an object, without storage overhead
Row overheadHeader, pointer and padding a database adds per row (PostgreSQL: 23 B header padded to 24, 4 B item pointer)
Index factorIndex bytes as a fraction of table bytes
Replication factorNumber of copies of the data
RetentionHow long data is kept before deletion or archiving
Ingress / egressTraffic into / out of your system; egress is billed by cloud providers
CDNContent delivery network: edge caches near users that answer repeated requests
Hit ratioShare of reads served from the cache
Working set / hot setThe data actually touched in a time window; what a cache must hold
80/20 ruleHeuristic that 20 percent of items receive 80 percent of requests
Little's lawL = lambda x W: average items in a stable system equal arrival rate times average time in system
In flightRequests started but not yet finished
UtilizationShare of a resource's capacity in use; delay explodes near 100 percent
ThroughputCompleted requests per second
Latency / WTime a request spends in the system, queueing plus service
p50 / p95 / p99Percentiles of latency
Tail latencyThe slow end of the latency distribution; amplified by fan-out
Backlog / lagMessages produced but not yet consumed
Drain timeBacklog divided by (consume rate minus produce rate)
Connection poolA limited set of reusable database connections (PgBouncer, database/sql)
IOPSInput/output operations per second a disk can do
WALWrite-ahead log: PostgreSQL's durable change log; its growth rate is a sizing input
PagePostgreSQL's 8 kB storage unit
TOASTPostgreSQL's mechanism for out-of-line and compressed large values
HeadroomSpare capacity above the expected peak (2x rule)
N+1One node more than needed, so a failure does not overload the rest
Open / closed load modelFixed arrival rate / new request only after the previous one finishes
Coordinated omissionA load test that slows down with the server and so hides latency
Egress costPer-GB charge for data leaving the cloud provider
Order of magnitudeA factor of ten; the accuracy an estimate aims for

References ​

All sources below were fetched and read in this session (November 2026); saved text is kept in the authoring scratch folder.

Built by Morteza Negahi