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 for | Go to |
|---|---|
| The whole chapter in a few tables | Everything in one minute |
| Why we estimate at all | Why it exists |
| Dean, Norvig, Colin Scott, Little 1961, the SRE book | Where it comes from |
| KB/MB/GB/TB, powers of two, bits vs bytes | Units |
| L1 to cross-region latency, 2025 numbers | Latency numbers |
| DAU to QPS, peak factor, read/write ratio | QPS from DAU |
| Row size, indexes, replicas, retention | Storage |
| Ingress, egress, CDN | Bandwidth |
| Working set, 80/20, Redis memory | Cache memory |
| servers = throughput x latency | Little's law |
| Producer and consumer rates, lag | Queue sizing |
| Connections, IOPS, WAL growth | Database sizing |
| Per-request cost, egress cost | Cost |
| 2x rule, 3-year horizon | Headroom and growth |
| p99 vs mean, peaks | Percentiles and peaks |
| Twitter-like, URL shortener, images, chat, analytics | Worked examples |
| What the numbers say about architecture | Choosing, In architecture |
| Estimator CLI, Artisan command | Go, Laravel |
| Estimate, then measure with hey or k6 | Lab |
| Wrong beliefs, cheat sheet, self-check, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The ten formulas. Every row is unpacked in the concepts section.
| Quantity | Formula | Tiny example | What goes wrong if you skip it |
|---|---|---|---|
| Average QPS | DAU x requests per user per day / 86,400 | 10 M x 20 / 86,400 = 2,315 | You size for a number nobody sees |
| Peak QPS | average QPS x peak factor (2 to 10) | 2,315 x 3 = 6,944 | The system falls over at 20:00, not at 04:00 |
| Read and write QPS | peak QPS split by the read:write ratio | 100:1 gives 69 writes, 6,875 reads | One database serves both and you cannot tell which one hurts |
| Storage per day | DAU x objects x (payload + row overhead) x (1 + index factor) x replicas | 10 M x 1 x 540 x 1.5 x 3 = 24 GB | Disk full in month four |
| Total storage | storage per day x retention days | 24 GB x 365 = 8.9 TB | No deletion policy, a surprise bill |
| Bandwidth | QPS x bytes per message x 8 | 6,875 x 5 KB x 8 = 275 Mbit/s | A 1 Gbit/s link at 80% because you counted bytes |
| Cache size | hot fraction x data size | 20% x 1 TB = 200 GB | A cache that is too small evicts what it must keep |
| In flight (Little) | L = arrival rate x time in system | 6,944 x 0.05 s = 347 | Thread pool and connection pool sized by hope |
| Servers | L / (per-node concurrency x target utilization) | 347 / (200 x 0.6) = 3 | Either 30 idle servers or an outage |
| Queue drain time | backlog / (consume rate - produce rate) | 6,000 / (200 - 100) = 60 s | A backlog that never drains |
Five numbers to remember for 2025.
| Number | Value | Why it matters |
|---|---|---|
| Seconds per day | 86,400 (round to about 100,000 for mental math) | The bridge between "per day" and "per second" |
| Memory vs SSD vs network | about 100 ns, 20 to 100 us, 0.5 ms | Each step is 10 to 1,000 times slower |
| Same-datacenter round trip | about 0.5 ms (Dean); 0.1 to 1 ms in practice | The price of every network hop between services |
| Cross-region round trip | 70 to 150 ms | You cannot make this faster; you can only avoid it |
| Peak factor | 2 to 10 over the daily mean | Capacity is bought for the peak |
The estimate in one picture (details: DAU to servers, Little's law):
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:
| Question | The estimate that answers it | Typical decision it drives |
|---|---|---|
| Will one machine be enough? | Peak QPS, in-flight requests, storage | Monolith on one node vs several |
| What breaks first? | Compare each resource to its limit | Invest in the bottleneck, not the loudest worry |
| Which style fits? | QPS per team, data size, bandwidth | Monolith, modular monolith, sharding, CDN |
| What will it cost? | Storage x price, egress x price, nodes x price | Build, 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 meeting | Takes days, needs a prototype and real data |
| Right within a factor of 2 to 10 | Right within 10 to 30 percent |
| Chooses between styles and orders of magnitude | Chooses instance sizes and reserved capacity |
| Wrong inputs give wrong outputs, visibly | Looks more certain than the inputs deserve |
Three common misunderstandings, up front
- "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.
- "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).
- "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.
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 areThe 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.
| Power | Exact value | Name | Rough decimal | Memory aid |
|---|---|---|---|---|
| 2^10 | 1,024 | 1 KiB | 10^3 (thousand) | a short email |
| 2^20 | 1,048,576 | 1 MiB | 10^6 (million) | a JPEG thumbnail |
| 2^30 | 1,073,741,824 | 1 GiB | 10^9 (billion) | a phone video, 1 minute |
| 2^40 | 1.0995 x 10^12 | 1 TiB | 10^12 (trillion) | one large HDD |
| 2^50 | 1.1259 x 10^15 | 1 PiB | 10^15 | a data lake |
| 2^32 | 4,294,967,296 | 4 Gi | 4.3 x 10^9 | the limit of a 32-bit unsigned id |
| 2^63 | 9.22 x 10^18 | max of bigint | 9.2 x 10^18 | enough for any counter |
| Quantity | Handy conversion |
|---|---|
| Seconds per day | 86,400; use 10^5 for mental math (error 14%) |
| Seconds per month | 2.6 x 10^6 (30 days) |
| Seconds per year | 3.15 x 10^7 |
| 1 Gbit/s | 125 MB/s peak, about 100 MB/s usable, 8.6 TB per day |
| 1 million requests per day | 11.6 requests per second on average |
| 1 byte per request at 1,000 QPS | 86.4 MB per day |
| 1 KB x 1 million | 1 GB |
| 1 MB x 1 million | 1 TB |
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.0Where 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.
| Operation | Dean's slide (original) | 2025-era typical | Ratio to main memory |
|---|---|---|---|
| L1 cache reference | 0.5 ns | 0.5 to 1 ns | 0.005x |
| Branch mispredict | 5 ns | 3 to 5 ns | 0.05x |
| L2 cache reference | 7 ns | 3 to 5 ns (per core) | 0.05x |
| Mutex lock/unlock | 100 ns | 15 to 50 ns uncontended | 0.2x |
| Main memory reference | 100 ns | 60 to 100 ns | 1x |
| Compress 1 KB (Zippy) | 10,000 ns | 2,000 to 5,000 ns (LZ4 and Snappy class) | 50x |
| Send 2 KB over a 1 Gbps network | 20,000 ns | 16,000 ns serialisation at 1 Gbit/s, 1,600 ns at 10 Gbit/s | 100 to 200x |
| NVMe SSD random read (4 KB) | not on the slide | 20 to 100 us | 300x |
| Read 1 MB sequentially from memory | 250,000 ns | 30,000 to 100,000 ns | 500x |
| Round trip within the same datacenter | 500,000 ns | 100 to 500 us (same availability zone), up to about 1 ms across zones | 5,000x |
| Disk seek (spinning disk) | 10,000,000 ns | 5 to 10 ms (still the same) | 100,000x |
| Read 1 MB sequentially from SSD | not on the slide | about 0.3 to 1 ms | 5,000x |
| Read 1 MB sequentially from disk | 30,000,000 ns | 5 to 10 ms (sequential HDD at 150 to 250 MB/s) | 50,000x |
| Cross-region round trip (same continent) | not on the slide | 30 to 80 ms | 500,000x |
| Packet CA to Netherlands and back | 150,000,000 ns | 130 to 170 ms | 1,500,000x |
The picture is on a logarithmic scale: every few steps along the bars the time grows by a factor of ten.
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 limitWhat 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.
| Scenario | Arithmetic | Result | Lesson |
|---|---|---|---|
| Page makes 100 sequential cache lookups, same datacenter | 100 x 0.5 ms | 50 ms | Use 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 ms | Join or WHERE id IN (...); see ORM pitfalls |
| Thumbnails page, 30 images, serial HDD reads | 30 x 10 ms + 30 x 256 KB / 30 MB/s | 560 ms (Dean) | Parallelise: 18 ms |
Write 1 KB with fsync on NVMe | one flush, 50 to 500 us | at most a few thousand commits per second per device | Group commit; see durability |
| User in Tehran reads from a region in Frankfurt | about 80 to 120 ms RTT, TLS adds 1 to 2 more | 160 to 360 ms before first byte | CDN 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 kind | Peak factor | Read:write | Why |
|---|---|---|---|
| B2B SaaS, office hours, one time zone | 3 to 5 (the day is 8 hours, not 24) | 10:1 to 50:1 | 8 busy hours compress 24 hours of traffic |
| Consumer social, global | 2 to 3 | 100:1 or more | Time zones flatten the curve |
| E-commerce with a sale | 10 to 50 on the sale minute | 50:1, then checkout writes spike | Campaigns and flash sales |
| Streaming or sport events | 5 to 20 around a match | read heavy | One event, one audience |
| Chat | 3 to 5 | 1:1 | Every message is written once and read by the recipient |
| Telemetry, analytics ingestion | 2 to 4 | write heavy, 1:100 or less | Machines do not sleep |
| Payments in a single country | 3 to 6 (evening, month start) | 5:1 | Salary days and bills |
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| Shortcut | Calculation | Use when |
|---|---|---|
| 1 M requests/day is about 12 QPS | 10^6 / 10^5 | Mental math in an interview |
| 100 M requests/day is about 1,200 QPS | 10^8 / 86,400 | Startup to mid-size |
| 1 B requests/day is about 11,600 QPS | 10^9 / 86,400 | A 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 concurrency | PCU / 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.
| Component | PostgreSQL | Rule of thumb |
|---|---|---|
| Page size | 8 kB (default, fixed at build time) | Rows live in 8 kB pages; a page header takes 24 bytes |
| Tuple header | 23 bytes, padded to 24 (MAXALIGN) | Add 24 bytes per row |
| Item pointer (line pointer) | 4 bytes per row | Add 4 bytes per row |
integer / bigint | 4 / 8 bytes | Choose by range, not by habit |
timestamptz, double precision | 8 bytes | Aligned to 8, padding after a 4-byte column |
uuid | 16 bytes | 2x a bigint, and random v4 keys bloat the index |
text, varchar | 1 or 4 byte header plus content | Content size plus 1 to 4 |
jsonb | content plus about 20 to 50 percent structure | Test with pg_column_size |
| B-tree index entry | about 8 to 16 bytes header and key, plus 4 pointer, at 70 to 90 percent fill | Estimate 20 to 40 bytes per entry for small keys |
| Free space and bloat | fill factor 100 by default for tables, 90 for B-tree indexes | Plan 20 to 30 percent more |
-- 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; 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| Engine | Where the overhead comes from |
|---|---|
| PostgreSQL | Tuple header 23 bytes, item pointer 4, alignment, MVCC dead tuples until VACUUM; see MVCC and VACUUM |
| MySQL InnoDB | Clustered index: the row lives in the primary key B-tree; secondary indexes store the primary key; a long PK inflates every index |
| SQLite | Variable-length record, small header; one file |
| MongoDB | BSON with field names inside every document; short field names save space; WiredTiger compresses with snappy by default |
| Cassandra/ScyllaDB | Per-cell timestamp and TTL overhead; compaction needs up to 50 percent free space for size-tiered |
| Redis | Per key overhead of tens of bytes plus encoding; hashes and listpack encodings are cheaper for small values |
| Kafka | Per-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".
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).
| Traffic | Size per message | Rate | Bandwidth at peak |
|---|---|---|---|
| JSON API response, small | 2 KB | 5,000/s | 80 Mbit/s |
| JSON API response, large list | 50 KB | 5,000/s | 2 Gbit/s |
| Web page, HTML + JS + CSS compressed | 500 KB (first visit) | 1,000 page loads/s | 4 Gbit/s |
| Image thumbnail | 20 KB | 20,000/s | 3.2 Gbit/s |
| Photo, original | 3 MB | 100 uploads/s | 2.4 Gbit/s ingress |
| Video, 1080p stream | 5 Mbit/s per viewer | 100,000 viewers | 500 Gbit/s |
| Chat message | 200 B plus 100 B of headers | 50,000/s | 120 Mbit/s |
| Kafka ingestion | 1 KB x replication 3 | 300,000/s | 2.4 Gbit/s into the cluster, plus replication traffic between brokers |
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| Placement | What it removes | When it pays |
|---|---|---|
| Compression (gzip, brotli) | 60 to 80 percent of text bytes | JSON, HTML, CSS, JS; costs CPU |
| CDN (Cloudflare, CloudFront, Fastly, Akamai) | Origin egress and latency for cacheable content | Static files, images, video, public API responses |
| Image resizing at the edge | Original-size downloads | Many device sizes |
| HTTP/2 and HTTP/3 | Head-of-line blocking, handshakes | Many small requests |
| Pagination and field selection | Over-fetching | Large lists; see pagination |
| Binary formats (protobuf) | 30 to 70 percent against JSON | Service-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 ratio | Backend reads for 10,000 read QPS | Average latency if hit 1 ms, miss 20 ms |
|---|---|---|
| 0% | 10,000 | 20 ms |
| 50% | 5,000 | 10.5 ms |
| 80% | 2,000 | 4.8 ms |
| 90% | 1,000 | 2.9 ms |
| 99% | 100 | 1.2 ms |
| Engine | Memory rule for estimates |
|---|---|
| Redis | Value 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 |
| Memcached | Slab allocator; plan 10 to 20 percent waste; item header about 50 bytes |
| PostgreSQL | shared_buffers (commonly 25 percent of RAM) plus the OS page cache; the "cache" is the hot set that fits in RAM |
| Kafka | Page cache: memory = write throughput x 30 s (Kafka documentation) |
| CDN | Disk 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 |
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 doneReal 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.
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 saturateThe 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).
| Pool | What L measures | Little applied |
|---|---|---|
PHP-FPM pm.max_children | Requests being executed | workers needed = peak QPS x mean duration per node |
Go net/http | Active handlers (goroutines) | Limited by CPU, memory, DB pool, not by a thread count; use http.Server timeouts |
| Database connection pool | Queries in flight | pool size = QPS x mean query time per app node; see connection pooling |
| Thread pool of a Java service | Requests in flight | threads = QPS x W |
| Kafka consumer group | Messages being processed | consumers = produce rate x processing time per message |
| Checkout line | Customers in the shop | The 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 time | Wasteful |
| 50% | 2x | Comfortable |
| 70% | 3.3x | Typical target at peak |
| 80% | 5x | Tail latency visibly worse |
| 90% | 10x | One slow dependency from an outage |
| 95% | 20x | Not 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.
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| Broker | What to size | Rule |
|---|---|---|
| Kafka | Partitions, disk for retention, page cache | Partitions at least the consumers you want in parallel; disk = rate x size x replication x retention; memory = write throughput x 30 s |
| RabbitMQ | Queue length, memory alarm, prefetch | Long queues live in memory or lazy on disk; set prefetch_count so consumers are not starved or flooded |
| Redis Streams | Memory | The whole stream is in RAM; trim with MAXLEN |
| Laravel queues | Workers (queue:work processes), job timeout | workers = jobs per second x seconds per job; Horizon balances by queue |
| SQS | Visibility timeout, in-flight limit | Standard 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.
| Resource | How to estimate | PostgreSQL knob or fact |
|---|---|---|
| Connections | QPS x mean query seconds, per app node, then times nodes | max_connections default is typically 100; PgBouncer in transaction mode multiplexes |
| Memory | shared_buffers + connections x work_mem x operations per query | One query can use work_mem several times (per sort or hash node) |
| Read IOPS | read QPS x (1 - hit ratio) x pages per query | NVMe: 100,000+ IOPS; gp3 EBS defaults to 3,000 IOPS; a spinning disk: about 100 to 200 |
| Write IOPS | commits per second (WAL flush) + dirty pages per checkpoint | synchronous_commit, group commit |
| WAL volume | changed 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 lag | WAL rate vs replay rate and network | See replication |
| Disk | Table + index + WAL + temp + backups | Section Storage |
-- 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; 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 archiveReal 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 line | Unit | Illustrative rate (assumption) | Where to read the real one |
|---|---|---|---|
| Object storage, standard | USD per GB-month | 0.023 | AWS S3 pricing page; Google Cloud Storage pricing page |
| General-purpose VM, 8 vCPU / 32 GB | USD per hour | 0.35 | AWS EC2 on-demand pricing; Google Compute Engine pricing |
| Managed block storage (SSD) | USD per GB-month | 0.08 to 0.12 | EBS or Persistent Disk pages |
| Internet egress, first tier | USD per GB | 0.09 | AWS EC2 data-transfer section; same dimension on every cloud |
| CDN egress, high volume | USD per GB | 0.02 to 0.08 | The CDN's own page |
| Cross-AZ traffic | USD per GB each way | about 0.01 | Provider data-transfer pages |
| Requests to object storage | USD per 1,000 or million | tiny but multiplied by billions | S3 pricing, request section |
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 errorTakeaway: 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 item | Rule of thumb |
|---|---|
| Peak margin | 2x the estimated peak, until you have measured peaks |
| Failure margin | N+1 nodes; N+2 when one node loss during maintenance is plausible |
| Zone failure | If 3 zones, each at most 60 to 66 percent so two can carry the load |
| Growth | Use the product plan, not a hope: 20 percent per quarter doubles in 4 quarters (1.2^4 = 2.07) |
| Horizon | Provision for 6 to 12 months; verify the architecture holds at 3 years |
| Storage growth | Linear with retention, or exponential with user growth: compute both |
| Lead time | Hardware or reserved capacity weeks to months; cloud minutes, but quotas take days |
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.
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 p50See 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
- 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.
- Compute QPS (average, peak, read, write) at each layer you care about.
- Compute storage per day and total over retention, with overhead, indexes and copies.
- Compute bandwidth (ingress and egress), then the effect of a CDN.
- Compute in-flight requests (Little) and nodes; compute connections for the database.
- Compute cache size from the hot fraction and the queue lag from the rates.
- Apply headroom; find the first bottleneck: the resource closest to a limit.
- Compare with one machine's limits and write the decision (choosing).
- State the uncertainty: which input would change the answer by 10x.
- Plan a measurement that would prove the estimate wrong (lab).
| Resource | Practical limit of one commodity server (2025, order of magnitude) | Source type |
|---|---|---|
Simple HTTP handler, Go net/http, small JSON | 20,000 to 100,000 requests/s per node on a few cores | Measure; Go documents the API, not throughput |
| Laravel on PHP-FPM, simple route | 100 to 500 requests/s per core, 500 to 3,000 per node | Measure; depends on bootstrap and I/O |
| Laravel Octane (Swoole, RoadRunner, FrankenPHP) | 2 to 5 times FPM for simple routes | Measure |
| PostgreSQL, primary-key reads, cached | 20,000 to 100,000 QPS per node | Measure with pgbench |
PostgreSQL, writes with fsync | 5,000 to 30,000 commits/s with group commit on NVMe | Measure |
| Redis, simple commands | 100,000+ ops/s per instance, single-threaded command execution | Redis docs, benchmark |
| Kafka broker | 100 to 500 MB/s per broker with fast disks and enough network | Kafka docs and your own test |
| 1 Gbit/s NIC | 125 MB/s | Arithmetic |
| NVMe SSD | 100,000+ IOPS, 1 to 7 GB/s | Vendor spec, then measure |
| RAM per node | 64 to 512 GB common, up to TBs | Instance 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
| Mistake | Symptom | Typical error | Fix |
|---|---|---|---|
| Ignoring the peak | Outage at 20:00 though the daily mean looked fine | 3 to 10x | Use peak factor; check the traffic graph |
| Mean instead of p99 | Page slow for 1 user in 4 | 2 to 10x latency | Plan with p99, fan-out maths |
| Forgetting replicas | Disk full, cost 3x higher | 3x | Multiply by the replication factor |
| Forgetting indexes | Storage underestimated | 1.5 to 3x | Measure pg_indexes_size |
| Bytes vs bits | Link saturated unexpectedly | 8x | Multiply by 8 for bandwidth |
| Decimal vs binary prefixes | Invoice mismatch | up to 10% at TB scale | Pick one and say it |
| Counting users, not requests | QPS far too low | 10 to 100x | Ask for requests per user |
| Not counting fan-out | Database QPS 10x the edge QPS | 5 to 50x | Multiply per layer |
| Ignoring retention | Linear growth forever | unbounded | Lifecycle rules, partition drop |
| Ignoring write amplification | SSD wears, WAL explodes | 2 to 10x | Count WAL, indexes, compaction |
| Using MAU instead of DAU | Overbuild | 3 to 10x | Convert DAU |
| Forgetting the cold start | Cache empty after a deploy | stampede | Warm up, request coalescing |
| Closed-loop load test | Test hides the saturation | misleading | Use 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
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
// 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
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:
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 daysThe Go angle
net/httpstarts 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, anddatabase/sqlSetMaxOpenConns/SetMaxIdleConns/SetConnMaxLifetime.database/sqlpool 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.Sincearound handlers and export a histogram (Prometheusclient_golang) so p50 and p99 can be read; the estimate is only as good as its W. runtime/pprofandgo test -benchanswer "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
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
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;
}
}php artisan capacity:estimate --dau=10000000 --req=1 --rw=100 --writes=0.01 --payload=500 --retention=1825The 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 = 100is 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::rememberwith 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
| Quantity | Assumption or formula | Result |
|---|---|---|
| DAU | given | 100 M |
| Requests per user per day | 40 (timeline refreshes and profile views) | 4 B per day |
| Average QPS | 4 B / 86,400 | 46,300 |
| Peak QPS | x 3 | 139,000 |
| Read:write | 20:1 (reads = timeline loads) | 6,600 writes, 132,000 reads at peak |
| Object | 2 posts per user per day, 300 B payload, 40 B overhead, indexes +50%, 3 copies | 306 GB per day |
| Retention 5 years | 306 GB x 1,825 | 558 TB (1.1 PB with 2x headroom) |
| Egress at peak | 132,000 x 10 KB x 8 | 10.6 Gbit/s |
| In flight | 139,000 x 0.1 s | 13,900 |
| Nodes | 13,900 / (500 x 0.6) | 47 (94 with headroom) |
| Cache | hot 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
| Quantity | Assumption or formula | Result |
|---|---|---|
| Redirects per user per day | 1 | 10 M per day |
| New URLs | 0.01 per user per day | 100,000 per day |
| Average / peak QPS | 116 / 347 | 344 reads, 3 writes at peak |
| Object | 500 B (long URL, metadata) + 40 overhead, indexes +50%, 3 copies | 243 MB per day |
| Retention 5 years | x 1,825 | 443 GB total, 887 GB with headroom |
| Egress | 344 x 500 B x 8 | 1.4 Mbit/s |
| In flight | 347 x 0.02 | 7 |
| Nodes | 7 / (200 x 0.6) | 1 (2 for failover) |
| Key space | base62, 7 characters | 62^7 = 3.5 trillion, enough for 100,000 per day for 95,000 years |
| Cache | 20% of one copy | 30 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
| Quantity | Assumption or formula | Result |
|---|---|---|
| Uploads | 0.2 per user per day = 1 M per day, 2 MB each | 2 TB per day |
| Replicas | 1 logical copy (an object store keeps its own copies and bills the logical size) | 2 TB per day |
| Retention 3 years | x 1,095 | 2.19 PB (4.4 PB with 2x headroom) |
| Peak QPS | 579 average, x 4 | 2,315 (2,269 reads, 46 uploads) |
| Ingress | 46 uploads/s x 2 MB x 8 | 741 Mbit/s |
| Egress | 2,269 x 200 KB x 8 | 3.6 Gbit/s |
| In flight | 2,315 x 0.3 | 694 |
| Nodes | 694 / (100 x 0.6) | 12 |
| Hot set | 1% of the data | 22 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
| Quantity | Assumption or formula | Result |
|---|---|---|
| Messages | 40 sent per user per day = 800 M per day | 800 M |
| Requests | 80 per user per day (send + receive/ack) | 1.6 B per day |
| Average / peak QPS | 18,500 / x 5 | 92,600 (46,300 reads, 46,300 writes) |
| Object | 150 B payload + 40 overhead, indexes +30%, 3 copies | 593 GB per day |
| Retention 2 years | x 730 | 433 TB (870 TB with headroom) |
| Bandwidth | 46,300 x 150 B x 8 | 56 Mbit/s each way (before headers and TLS) |
| Concurrent connections | PCU about 10% of DAU, one websocket each | 2 M open connections |
| Memory for connections | 2 M x about 10 KB | 20 GB across the gateway fleet |
| Nodes for the gateway | 2 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
| Quantity | Assumption or formula | Result |
|---|---|---|
| Events | 200 per user per day = 10 B per day | 10 B |
| Average / peak QPS | 115,700 / x 4 | 463,000 (almost all writes) |
| Payload | 400 B per event, no row overhead (columnar or log format), 3 copies | 12 TB per day |
| Retention 90 days | x 90 | 1.08 PB (2.2 PB with headroom) |
| Ingress | 458,000 x 400 B x 8 | 1.5 Gbit/s into the edge |
| Kafka memory | write throughput 183 MB/s x 30 s (Kafka docs rule) | about 5.5 GB of page cache per copy |
| In flight | 463,000 x 0.01 | 4,630 |
| Nodes for collectors | 4,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.
| Example | First bottleneck | Style it points to |
|---|---|---|
| Timeline | Read fan-out, egress 10 Gbit/s | Cache + precomputed timelines + CDN for media |
| URL shortener | None (one node) | Boring monolith; spend the time on IDs and abuse |
| Image upload | Object storage and egress | Object store + CDN + async workers; tiny metadata DB |
| Chat | Connections and writes | Event-driven gateway + sharded wide-column store + queue |
| Analytics ingestion | Write rate | Log + batch + columnar store |
Choosing: what the numbers say about architecture
| Estimated peak load | Typical single-node capability | Decision | Extra technique |
|---|---|---|---|
| Up to about 1,000 QPS, data under 1 TB | One app node, one PostgreSQL primary | Monolith, a standby for failover | Backups, one replica; no cache yet |
| 1,000 to 10,000 QPS, reads dominate | Several app nodes, one primary, read replicas | Modular monolith; add Redis cache and read replicas | Connection pooler; CDN for static files |
| 10,000 to 100,000 QPS | Multiple app nodes, sharded or partitioned data stores likely | Modular 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 relational | One primary is at the edge | Shard by key, or move that data to a log/wide-column store | Batching, async |
| Data over 5 to 10 TB in one PostgreSQL | Backups and vacuum become slow | Partition and archive; sharding thought through | See partitioning and sharding |
| Egress over 1 Gbit/s of cacheable content | A NIC and a bill | CDN | Cache headers, image sizes |
| Global users, latency target under 100 ms | Cross-region 70 to 150 ms | Regional deployments, multi-region reads | See replication topologies |
| 100,000+ QPS or PB-scale data | Not one node anywhere | Distributed data tier, dedicated platform team | Everything above |
Rules of thumb that come out of the tables (they are heuristics; confirm with a measurement):
| Rule | Reason |
|---|---|
| A monolith on one well-sized PostgreSQL is fine up to a few thousand QPS and a few TB | The 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 before | Sharding is irreversible and complicates every query |
| Add a cache when read QPS x (1 - hit ratio) is below what the database handles and latency matters | A cache is one more thing to invalidate |
| Add a CDN when static or public bytes make up most of the egress | Pays 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 overload | Little'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
| Load | Estimate shows | Typical step | Estimate to re-run |
|---|---|---|---|
| 1x (about 500 QPS, 50 GB) | One node is enough | Monolith, backups, monitoring | Baseline: write the numbers on the wiki |
| 10x (about 5,000 QPS, 500 GB) | Connections and read QPS bite | Pooler, cache, read replica, CDN for static | DB connections, hit ratio, replica lag |
| 100x (about 50,000 QPS, 5 TB) | One primary's writes or size is at the limit | Partitioning, queue for writes, possibly sharding or a different store for the hot data | Write QPS, WAL, in-flight per tier |
| 1,000x (about 500,000 QPS, 50 TB) | No single machine anywhere | Distributed data tier, regional deployment, dedicated platform | Everything, 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.
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// 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
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.
- 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).
- 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-nfor number of requests,-cfor concurrent workers,-qfor a per-worker rate limit and-zfor duration.) The shortfall from 2,500 is timer granularity and scheduling. - Change the concurrency. Run with
-c 10,-c 100,-c 500. Expected: throughput scales with-cuntil 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. - Open model,
k6. Use the script below withrate: 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. - Laravel. Repeat 2 to 4 against the Laravel route. Predict first: with PHP-FPM,
pm.max_children = 16and W = 25 ms (20 ms sleep + 5 ms framework), the ceiling is 16 / 0.025 = 640 requests/s per node. Compare. - 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).
// 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 });
} 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 queueCleanup: stop the handler (Ctrl-C). Nothing is written to disk.
Common misconceptions
| Belief | Reality |
|---|---|
| "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
| Topic | What to remember |
|---|---|
| Seconds per day | 86,400; 10^5 for mental math; 1 M per day is about 12 QPS |
| Bits vs bytes | Bandwidth in bits: multiply bytes by 8; 1 Gbit/s is 125 MB/s |
| Peak | Peak = average x 2 to 10; size for the peak |
| Read:write | 100:1 social, 10:1 SaaS, 1:1 chat, 1:100 telemetry |
| Row size | Payload + 24 header + 4 pointer + padding, then indexes (+50% to +200%) |
| Replicas | Multiply storage by copies; object stores bill logical bytes |
| Retention | Total = daily x days; no policy means linear growth forever |
| Latency ladder | Memory 100 ns, SSD 20 to 100 us, DC RTT 0.5 ms, disk seek 10 ms, cross-region 70 to 150 ms |
| Little | L = lambda x W; servers = L / (per-node concurrency x utilization) |
| Utilization | Plan 50 to 70 percent at peak; delay explodes above 80 |
| Cache | 10 to 20 percent hot set; 90 percent hit ratio cuts backend load 10x |
| Queue | Drain time = backlog / (consume - produce); never drains if not faster |
| DB | Connections = QPS x query seconds; default max_connections is typically 100; pool with PgBouncer |
| Headroom | 2x peak, N+1 nodes, check the 3-year bound |
| Cost | Storage, egress and cross-zone first; compute last; re-read prices on the day |
| Validate | Estimate, then measure with an open-model test, then fix the model |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| DAU / MAU | Daily / monthly active users; DAU is the start of a QPS estimate |
| QPS / RPS | Queries or requests per second at a named layer |
| Peak factor | Peak QPS divided by average QPS, typically 2 to 10 |
| Read:write ratio | How many reads happen per write |
| Fan-out | One request that triggers many downstream operations (a post delivered to followers) |
| Payload | The application bytes of an object, without storage overhead |
| Row overhead | Header, pointer and padding a database adds per row (PostgreSQL: 23 B header padded to 24, 4 B item pointer) |
| Index factor | Index bytes as a fraction of table bytes |
| Replication factor | Number of copies of the data |
| Retention | How long data is kept before deletion or archiving |
| Ingress / egress | Traffic into / out of your system; egress is billed by cloud providers |
| CDN | Content delivery network: edge caches near users that answer repeated requests |
| Hit ratio | Share of reads served from the cache |
| Working set / hot set | The data actually touched in a time window; what a cache must hold |
| 80/20 rule | Heuristic that 20 percent of items receive 80 percent of requests |
| Little's law | L = lambda x W: average items in a stable system equal arrival rate times average time in system |
| In flight | Requests started but not yet finished |
| Utilization | Share of a resource's capacity in use; delay explodes near 100 percent |
| Throughput | Completed requests per second |
| Latency / W | Time a request spends in the system, queueing plus service |
| p50 / p95 / p99 | Percentiles of latency |
| Tail latency | The slow end of the latency distribution; amplified by fan-out |
| Backlog / lag | Messages produced but not yet consumed |
| Drain time | Backlog divided by (consume rate minus produce rate) |
| Connection pool | A limited set of reusable database connections (PgBouncer, database/sql) |
| IOPS | Input/output operations per second a disk can do |
| WAL | Write-ahead log: PostgreSQL's durable change log; its growth rate is a sizing input |
| Page | PostgreSQL's 8 kB storage unit |
| TOAST | PostgreSQL's mechanism for out-of-line and compressed large values |
| Headroom | Spare capacity above the expected peak (2x rule) |
| N+1 | One node more than needed, so a failure does not overload the rest |
| Open / closed load model | Fixed arrival rate / new request only after the previous one finishes |
| Coordinated omission | A load test that slows down with the server and so hides latency |
| Egress cost | Per-GB charge for data leaving the cloud provider |
| Order of magnitude | A 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.
- Jeff Dean, Software Engineering Advice from Building Large-Scale Distributed Systems (Stanford CS295 slides): http://static.googleusercontent.com/media/research.google.com/en//people/jeff/stanford-295-talk.pdf (the slide "Numbers Everyone Should Know" and the thumbnail worked estimate; the PDF is undated, so we give no year).
- Colin Scott, Latency Numbers Every Programmer Should Know, interactive page by year (a model that extrapolates Norvig's 2002 numbers): https://colin-scott.github.io/personal_website/research/interactive_latency.html
- Google SRE book, Handling Overload (chapter 21), "The Pitfalls of Queries per Second": https://sre.google/sre-book/handling-overload/
- Google SRE book, Software Engineering in SRE (the Auxon capacity planning case study): https://sre.google/sre-book/software-engineering-in-sre/
- PostgreSQL documentation, Database Page Layout (8 kB pages, 24-byte page header, 4-byte item identifiers, 23-byte tuple header): https://www.postgresql.org/docs/current/storage-page-layout.html
- PostgreSQL documentation, Numeric Types: https://www.postgresql.org/docs/current/datatype-numeric.html
- PostgreSQL documentation, Connections and Authentication (
max_connections, default typically 100): https://www.postgresql.org/docs/current/runtime-config-connection.html - PostgreSQL documentation, WAL configuration and Write Ahead Log settings (
max_wal_size,full_page_writes): https://www.postgresql.org/docs/current/wal-configuration.html and https://www.postgresql.org/docs/current/runtime-config-wal.html - Redis documentation, Memory optimization (listpack thresholds, bitmap example: 100 million users in about 12 MB): https://redis.io/docs/latest/operate/oss_and_stack/management/optimization/memory-optimization/
- Apache Kafka documentation 4.1, Hardware and OS (memory = write_throughput x 30 seconds): https://kafka.apache.org/41/operations/hardware-and-os/
- AWS, Amazon S3 pricing and Amazon EC2 on-demand pricing (billing dimensions only; numeric prices are rendered dynamically): https://aws.amazon.com/s3/pricing/ and https://aws.amazon.com/ec2/pricing/on-demand/
- Little's law (statement and L = lambda W; secondary source, the 1961 paper was not fetched): https://en.wikipedia.org/wiki/Little's_law
- rakyll/hey README (flags
-n,-c,-q,-z): https://github.com/rakyll/hey - Grafana k6 documentation, Open and closed models (arrival-rate executors, coordinated omission): https://grafana.com/docs/k6/latest/using-k6/scenarios/concepts/open-vs-closed/
- Laravel 13 documentation, Artisan Console (
SignatureandDescriptionattributes,$this->table): https://laravel.com/docs/13.x/artisan - Not fetched, named from memory and flagged as such in the text: Dean and Barroso, The Tail at Scale, CACM 2013; Peter Norvig, Teach Yourself Programming in Ten Years.