System DesignVol. 12 · Part XII
0 / 0

Shelves / System Design

SD·122

Estimation

Back-of-envelope calculation as an engineering skill: powers of two and ten, latency numbers every engineer should know, daily and peak QPS from user counts, read/write ratios, storage per day and over retention with replication and indexes, bandwidth and egress, cache sizing and hit ratios, server and partition counts from per-node capacity, Little's law for concurrency and connection pools, cost estimates, sanity checks, and five fully worked estimations (URL shortener, chat, photo sharing, metrics pipeline, ride-hailing locations) plus a reusable calculator.

34 topics · ~21 min read · 30-question quiz
Updated Suggest a correction

Start here: numbers you can do in your head

Estimation is how you find out, before building anything, whether a design is one server or a thousand, one disk or a cluster. You don't need precision; you need the right order of magnitude, which comes from a handful of facts and some multiplication.

Facts worth memorising

Text
seconds in a day           86,400 ≈ 10^5   (so 1 million/day ≈ 12/s)
2^10 ≈ 10^3 (KB)   2^20 ≈ 10^6 (MB)   2^30 ≈ 10^9 (GB)   2^40 ≈ 10^12 (TB)

How long things take, measured on this machine

Text
read from memory, data fits in CPU cache (16 KiB)       1.6 ns
read from memory, 64 MiB working set (DRAM)          188   ns
uncontended mutex lock + unlock                         3.8 ns
system call                                           125   ns
SHA-256 of 20 KiB                                      15   µs
zlib-compress 20 KiB of JSON                           92   µs   (22,447 → 1,464 bytes)
localhost TCP round trip                               30   µs
SSD random 4 KiB read                                  35   µs   (p99 106 µs)
4 KiB write + fsync (durable)                         152   µs
PostgreSQL primary-key SELECT over TCP                120   µs
PostgreSQL INSERT + COMMIT                            582   µs
sequential read from SSD                            1,885   MiB/s
same-region network round trip (typical cloud)       ~0.5   ms
India ↔ US East round trip (typical)               ~200   ms

The gaps are what matter: a cache read is about 100× faster than a DRAM read; a DRAM read is about 200× faster than an SSD read; a local database query is about 1,000× slower than a cache-friendly memory access, and a cross-continent round trip about 1,000× slower than a local query. Designs are shaped by avoiding the slow end: keep hot data in memory, batch disk writes, and don't cross oceans inside a request.

Estimating storage: check your arithmetic against reality

An orders table: id bigint, customer_id bigint, kitchen_id int, status smallint, total_paise int, created_at timestamptz.

Text
estimate:  columns 8+8+4+2+4+8 = 34 bytes
           + ~24 bytes row header + 4 bytes slot pointer + alignment ≈ 64–68 bytes/row
           1,000,000 rows ≈ 65 MB of table
measured:  heap 65 MB (68.3 bytes/row)
           primary-key index 21 MB, index on (customer_id, created_at) 30 MB
           total 117 MB

The raw data was 34 MB; the database needed 3.4× that once row overhead and two indexes were counted. Add replication (×3 copies is common) and backups, and 34 MB of "data" is about 350 MB of disk. Forgetting overhead, indexes and replicas is the most common estimation mistake.

A worked estimate

The tiffin centre in two years: 500,000 orders a day, kept for 5 years.

Text
rows:     500,000 × 365 × 5 ≈ 9 × 10^8 orders
storage:  9 × 10^8 × ~117 bytes (table + indexes, from the measurement) ≈ 105 GB
          × 3 replicas ≈ 320 GB                                → fits on one large database server
writes:   500,000/day ≈ 6/s average, ~60/s at peak             → one PostgreSQL primary handles this
          (lab: one connection did a durable insert in 0.58 ms ≈ 1,700/s, sequentially)

The answer is "one well-provisioned PostgreSQL primary with replicas, partitioned by month for easy archiving", not a sharded cluster. Estimation saved you from building one.

How deep to go in estimation

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Use powers of two and ten and convert per-day figures to per-second
L2 Estimate QPS, storage, bandwidth and memory for a feature, including peaks and overheads
L3 Explain the latency hierarchy and use it to predict where a design spends its time
L4 Validate estimates with measurements and find where an estimate went wrong
L5 Do capacity planning for a system: growth, headroom, cost, and when to re-architect
L6 Run capacity and cost planning across an organisation's fleet

Why estimate

Estimation turns requirements into numbers that select designs. Is the data 50 GB (one Postgres instance, done) or 5 PB (distributed storage, careful partitioning)? Is it 200 requests/s (a couple of instances) or 2 million (sharding, caching tiers, edge serving)? A 10-minute calculation can rule out entire architectures and expose the real bottleneck (often storage growth, bandwidth or fan-out, not raw request rate).

Goals of back-of-envelope estimation:

  • Order of magnitude, not precision. Being within a factor of 2–3 is fine; being off by 1,000× is the failure mode to avoid.
  • Identify the dominant cost/bottleneck: storage, bandwidth, CPU, memory, IOPS, connections, or money.
  • Make assumptions explicit so others can challenge them.
  • Sanity-check designs ("this needs 4,000 database writes/s per shard; Postgres on our hardware handles ~10k simple writes/s: fine").

Numbers to know

Powers of two and ten

Power of 2 Exact Approx. Name
2¹⁰ 1,024 10³ (thousand) KiB
2²⁰ 1,048,576 10⁶ (million) MiB
2³⁰ ~1.07 × 10⁹ 10⁹ (billion) GiB
2⁴⁰ ~1.1 × 10¹² 10¹² (trillion) TiB
2⁵⁰ ~1.13 × 10¹⁵ 10¹⁵ PiB

Useful sizes: a UUID is 16 bytes (36 as text); a 64-bit integer 8 bytes; an IPv4 address 4 bytes, IPv6 16; a typical tweet-length text ~300 bytes UTF-8; a JSON API response 1–10 KB; a compressed photo 200 KB–3 MB; a minute of 1080p video ~50–100 MB at typical bitrates; a log line ~200–500 bytes.

Time

Period Seconds Rule of thumb
1 day 86,400 ~10⁵ s (round up for easy maths)
1 month ~2.6 × 10⁶ ~2.5 million
1 year ~3.15 × 10⁷ ~π × 10⁷

So: 1 million requests/day ≈ 12 requests/s average. 1 billion/day ≈ 12,000/s. Memorise "×1/86,400 ≈ ÷ 100,000".

Latency numbers (orders of magnitude)

These numbers, popularised by Jeff Dean and Peter Norvig, have shifted with hardware but the ratios are what matter:

Operation Approx. time Relative
L1 cache reference ~1 ns 1
Branch mispredict ~3 ns
L2 cache reference ~4 ns
Mutex lock/unlock (uncontended) ~15–25 ns
Main memory reference ~100 ns 100× L1
Compress 1 KB (fast codec, e.g. LZ4/Snappy) ~1–2 µs
Read 1 MB sequentially from memory ~10–50 µs
Round trip within a datacenter / AZ ~0.1–0.5 ms
NVMe SSD random read (4 KB) ~20–100 µs
Read 1 MB sequentially from NVMe ~0.1–0.3 ms
Round trip between AZs in one region ~0.5–2 ms
Redis GET over the network (same AZ) ~0.2–1 ms
Simple indexed DB query (warm cache) ~0.5–5 ms
HDD seek ~5–10 ms
Read 1 MB sequentially from HDD ~5–10 ms
Round trip same continent ~20–60 ms
Round trip India ↔ Europe / US East ↔ West Europe ~80–150 ms
Round trip India ↔ US West ~200–250 ms
TLS 1.3 handshake +1 RTT (0 with resumption + 0-RTT)

Consequences: memory is ~1,000× faster than a network hop, which is ~100× faster than a cross-continent round trip. Chatty designs (many sequential calls) die by round trips; batching and co-location win.

Throughput rules of thumb (single modern node, highly workload-dependent)

Component Order of magnitude
Stateless HTTP service (Go/Java/Rust), simple JSON endpoint 10k–100k req/s per instance (less with heavy logic)
Nginx/Envoy proxying 10k–100k+ req/s per core-heavy instance
PostgreSQL/MySQL simple primary-key reads (cached) 10k–100k+ queries/s per node
PostgreSQL simple single-row writes with fsync 1k–20k transactions/s (batching/commit grouping helps)
Redis/Valkey GET/SET 100k–1M ops/s per node (pipelining, multi-threaded I/O)
Kafka partition ~10 MB/s+ per partition; a broker handles hundreds of MB/s
NVMe SSD 100k–1M IOPS; 2–7 GB/s sequential
10/25/100 Gbit NIC 1.25 / 3.1 / 12.5 GB/s

Always validate with your own benchmarks (Vol. 11 ch. 119); use these only to sanity-check.

The estimation toolkit

assumptionsDAUactions / userobject sizesretentionpeak factor trafficreq / dayavg QPS ÷ 10⁵peak QPSread : write resourcesstoragebandwidthcache sizeconcurrency capacityinstancesshardspartitions₹ / month write each step down · round to 1–2 significant figures · state the conclusion
The estimation chain. Start from business assumptions (daily active users, actions per user, object sizes, retention), derive traffic (average and peak QPS split into reads and writes), then the resources that traffic implies: storage over retention, bandwidth, cache size, concurrency, and finally instance, shard and partition counts and monthly cost. Each arrow is one multiplication or division you can show.

From users to requests per second

Text
DAU (daily active users)
  × actions per user per day
  = requests per day
  ÷ 86,400 (~10⁵)
  = average QPS
  × peak factor (2–10×; diurnal peak ≈ 2–3×, events/sales 5–10×+)
  = peak QPS

Example: 50 M DAU, each viewing 20 pages/day, each page making 5 API calls: 50M × 20 × 5 = 5 × 10⁹ calls/day ≈ 58,000 req/s average; peak ×3 ≈ 175,000 req/s.

Split by operation type because reads and writes stress different components:

Text
writes: 50M DAU × 2 posts/day = 10⁸/day ≈ 1,160/s avg, ~3.5k/s peak
reads:  50M DAU × 200 post views/day = 10¹⁰/day ≈ 116k/s avg, ~350k/s peak
read:write ≈ 100:1

Storage

Text
objects per day × size per object = raw bytes per day
× retention (days)
× replication factor (e.g. 3 for databases; object storage handles internally)
× overhead (indexes 1.2–2×, encoding/compression 0.2–1×, free-space headroom 1.3–1.5×)

Example: 10⁸ posts/day × 1 KB (text + metadata) = 100 GB/day raw; × 365 × 5 years ≈ 180 TB; × 3 replicas ≈ 550 TB; plus indexes. That's a sharded/distributed database decision, not a single node. Media (photos) usually dominate by orders of magnitude and go to object storage with a CDN.

Bandwidth

Text
ingress = write QPS × request size
egress  = read QPS × response size

Example: 350k reads/s × 10 KB = 3.5 GB/s ≈ 28 Gbit/s egress at peak. Image-heavy: 50k image views/s × 300 KB = 15 GB/s = 120 Gbit/s: that's CDN territory, and egress cost (cents per GB) becomes a top budget line: 15 GB/s × 86,400 s × 30 ≈ 39 PB/month if sustained (actual average lower than peak).

Cache sizing and hit ratio

Access frequency usually follows a skewed (Zipf-like) distribution: a small fraction of items gets most of the traffic. The "80/20" heuristic: caching the hottest ~20% of daily-read items often serves ~80% of reads (measure the real curve when you can).

Text
cache size ≈ (unique items read per day) × (fraction to cache) × (item size + overhead)
backend load = read QPS × (1 − hit ratio)

Example: 50M unique posts read per day, cache 20% × 1 KB × 1.5 overhead ≈ 15 GB: fits in a small Redis cluster. With 350k reads/s and 90% hit ratio, the database sees 35k reads/s; at 99%, 3.5k/s. Each extra nine of hit ratio cuts backend load 10×, which is why hit ratio is one of the most important numbers in read-heavy designs.

Servers, shards and partitions

Text
instances = peak QPS ÷ (per-instance capacity × target utilisation)

Target utilisation 50–70% leaves headroom for spikes, failover (losing one AZ of three means the other two must absorb 50% more), and latency (queueing delay grows sharply above ~70–80% utilisation, Vol. 9 ch. 105).

Example: 175k req/s peak ÷ (10k req/s per instance × 0.6) ≈ 30 instances; spread across 3 AZs, ensure 2 AZs can carry peak: 175k ÷ (20 instances × 10k) = 0.875 utilisation: too hot, so deploy ~45 (15 per AZ).

For databases: shards = max(data size ÷ comfortable size per node, write QPS ÷ comfortable writes per node). For Kafka: partitions ≥ max(throughput ÷ per-partition throughput, max consumer parallelism needed).

Concurrency with Little's law

L = λ × W: items in the system = arrival rate × time each spends there.

  • In-flight requests: 175k req/s × 0.05 s average latency ≈ 8,750 concurrent requests across the fleet (≈ 200 per instance for 45 instances): affects thread pools, event loops, memory.
  • Database connections: if each request holds a connection for 5 ms and the service makes 20k queries/s, it needs ≈ 100 connections busy on average; size pools with headroom but remember Postgres handles hundreds, not tens of thousands, of connections well (use PgBouncer/RDS Proxy).
  • WebSocket connections: 10 M concurrent users with open connections, at ~50k–200k connections per gateway node (memory-bound, ~10–50 KB each) → 50–200 nodes.
  • Queue depth: if consumers process 5k msg/s and producers send 6k/s for 10 minutes, the backlog grows by 600k messages; at 5k/s it takes forever to drain unless producers slow: capacity must exceed peak arrival rate.

Cost

Multiply resources by unit prices (on-demand or committed): instance-hours, GB-months of storage per class, GB transferred (cross-AZ, cross-region, internet egress), requests (object storage, serverless), managed service units. Express as cost per unit of business value (per order, per 1,000 redirects, per monthly active user) to compare designs and track efficiency. Prices vary by provider, region and contract; look them up rather than memorising.

Sanity checks and common errors

  • Units: bits vs bytes (network in bits/s, storage in bytes: ×8); KB vs KiB rarely matters at estimation precision; per second vs per day.
  • Peak vs average: provisioning for average guarantees overload daily.
  • Replication and overhead: forgetting ×3 replicas, indexes, backups, and headroom routinely underestimates storage by 5–10×.
  • Fan-out: one user action can trigger many internal calls or writes (a post to 1,000 followers' timelines = 1,000 writes with fan-out-on-write).
  • Growth: design for 2–3× the current numbers, plan for 10×; beyond that, expect to redesign.
  • Cross-check: compare with known systems ("this would be larger than all of Wikipedia's text, really?") and with first principles (can a human generate that many actions per day?).
  • Round aggressively: 86,400 → 10⁵; 2.6 M s/month; use powers of ten and keep one or two significant figures.

Worked estimation 1: URL shortener

Assumptions: 100 M new links/month; 100:1 reads; links kept 5 years; average long URL 100 bytes.

Quantity Calculation Result
Write QPS (avg) 10⁸ ÷ 2.6×10⁶ s ~40/s (peak ~400/s)
Read QPS (avg) 40 × 100 ~4,000/s (peak ~40,000/s)
Total links (5 yr) 10⁸ × 60 6 × 10⁹
Record size code 7 B + URL 100 B + metadata ~150 B ~300 B (~500 B with index overhead)
Storage 6×10⁹ × 500 B ~3 TB (× replicas: ~9 TB)
Code length base62⁷ = 3.5 × 10¹² ≫ 6 × 10⁹ 7 characters suffice (sparse enough to resist enumeration)
Cache hottest 20% of a day's ~10⁸ distinct reads × 500 B ~10 GB in memory
Click events 4,000/s × 200 B 0.8 MB/s ≈ 70 GB/day raw → aggregate

Conclusion: modest storage (one sharded key-value store or partitioned Postgres), modest write rate, read path dominated by cache/CDN, analytics via a stream with aggregation.

Worked estimation 2: chat messaging

Assumptions: 500 M DAU; 40 messages sent per user per day; average message 100 bytes + 200 bytes metadata; average group size 5 (each message delivered to ~4 recipients on average); messages stored 1 year server-side; 50% of DAU online at peak with a persistent connection.

Quantity Calculation Result
Messages/day 5×10⁸ × 40 2 × 10¹⁰
Send QPS avg / peak 2×10¹⁰ ÷ 10⁵ ; ×3 200k/s ; ~600k/s
Deliveries/s peak 600k × 4 ~2.4 M/s
Storage/day 2×10¹⁰ × 300 B 6 TB/day
Storage/year (×3 replicas) 6 TB × 365 × 3 ~6.6 PB
Concurrent connections 0.5 × 5×10⁸ 250 M
Gateway nodes 250M ÷ 500k connections per node (tuned) ~500 nodes (more for headroom/AZs)
Bandwidth (delivery) 2.4M × 300 B ~720 MB/s ≈ 6 Gbit/s (small per node)

Conclusion: the hard parts are connection management (hundreds of millions of long-lived connections), delivery fan-out, and storage at PB scale with per-conversation access patterns (wide-column or sharded storage keyed by conversation), not raw bandwidth.

Worked estimation 3: photo sharing

Assumptions: 200 M DAU; 10% upload 2 photos/day; each upload stored in 4 sizes totalling 3 MB; users view 100 photos/day, average served size 200 KB; photos kept forever.

Quantity Calculation Result
Uploads/day 2×10⁸ × 0.1 × 2 4 × 10⁷
Upload QPS avg 4×10⁷ ÷ 10⁵ ~400/s (peak ~1,200/s)
New storage/day 4×10⁷ × 3 MB 120 TB/day
Per year 120 TB × 365 ~44 PB/year (object storage, internal redundancy)
Views/day 2×10⁸ × 100 2 × 10¹⁰
Egress/day 2×10¹⁰ × 200 KB 4 PB/day
Peak egress 4 PB ÷ 10⁵ × 3 ~120 GB/s ≈ 1 Tbit/s

Conclusion: storage growth and egress dominate; a CDN with high hit ratio and tiered storage (hot/warm/cold classes, lifecycle policies) is essential; metadata (who posted what, likes) is comparatively tiny.

Worked estimation 4: metrics/observability pipeline

Assumptions: 20,000 hosts/containers; each exports 1,000 active series; scraped every 15 s; each sample ~16 bytes raw, ~1.5 bytes after time-series compression; retention 30 days at full resolution.

Quantity Calculation Result
Active series 2×10⁴ × 10³ 2 × 10⁷ (20 M)
Samples/s 2×10⁷ ÷ 15 ~1.3 M samples/s
Compressed bytes/day 1.3M × 1.5 B × 86,400 ~170 GB/day
30 days × 30 ~5 TB (+ replication)
Index memory 20 M series × ~1–4 KB in-memory overhead 20–80 GB RAM

Conclusion: cardinality (number of series, and its memory cost) is the constraint, not bytes on disk; controlling label cardinality is the key design lever (Vol. 9 ch. 100).

Worked estimation 5: ride-hailing location updates

Assumptions: 1 M drivers online at peak; location update every 4 s; update ~100 bytes; riders' apps poll or subscribe for nearby drivers; history kept 30 days for analytics.

Quantity Calculation Result
Updates/s 10⁶ ÷ 4 250k writes/s
Ingress 250k × 100 B 25 MB/s
Latest-position store 10⁶ × ~200 B ~200 MB: fits in memory (geo-indexed, sharded by region)
History/day 250k × 100 B × 86,400 ~2.2 TB/day (compress/columnar)
Nearby-driver queries 10 M rider sessions × 1 query/10 s 1 M queries/s: needs in-memory geo-index (geohash/H3 cells), regional sharding

Conclusion: the current-state problem is small in bytes but huge in operation rate: keep it in memory, partitioned geographically; history goes to a stream and columnar storage.

A reusable estimation calculator

Writing estimates as a tiny script keeps assumptions explicit and lets you vary them:

# estimate.py — explicit assumptions, derived numbers, quick what-ifs
from dataclasses import dataclass

DAY = 86_400

@dataclass
class Workload:
    dau: float
    writes_per_user: float
    reads_per_write: float
    write_bytes: float
    read_bytes: float
    retention_days: float
    replicas: int = 3
    overhead: float = 1.5
    peak_factor: float = 3.0
    cache_hit: float = 0.9

    def report(self):
        w_avg = self.dau * self.writes_per_user / DAY
        r_avg = w_avg * self.reads_per_write
        storage = w_avg * DAY * self.write_bytes * self.retention_days * self.replicas * self.overhead
        egress_peak = r_avg * self.peak_factor * self.read_bytes
        db_reads_peak = r_avg * self.peak_factor * (1 - self.cache_hit)
        for k, v in {
            "write QPS avg/peak": f"{w_avg:,.0f} / {w_avg*self.peak_factor:,.0f}",
            "read QPS avg/peak": f"{r_avg:,.0f} / {r_avg*self.peak_factor:,.0f}",
            "storage total": human(storage),
            "peak egress": human(egress_peak) + "/s",
            "DB reads/s at peak after cache": f"{db_reads_peak:,.0f}",
        }.items():
            print(f"{k:32} {v}")

def human(b: float) -> str:
    for unit in ["B", "KB", "MB", "GB", "TB", "PB", "EB"]:
        if b < 1000:
            return f"{b:,.1f} {unit}"
        b /= 1000
    return f"{b:,.1f} ZB"

Workload(dau=50e6, writes_per_user=2, reads_per_write=100, write_bytes=1_000,
         read_bytes=10_000, retention_days=5 * 365).report()

Output for the example: ~1,157 writes/s average (~3,472 peak), ~115,741 reads/s (~347,222 peak), ~821 TB total storage, ~3.5 GB/s peak egress, ~34,722 database reads/s after a 90% cache hit ratio. Changing cache_hit to 0.99 drops the last number to ~3,472, which is the kind of insight that justifies investment in caching.

Presenting estimates

In a design document or interview:

  1. State assumptions in a short list (with sources: analytics, market size, product targets).
  2. Show the 4–6 derived numbers that matter (peak QPS by operation, storage over retention, peak bandwidth, concurrency, cache size).
  3. Draw the conclusion: "storage and egress dominate; request rates are moderate" → which shapes the design.
  4. Revisit when assumptions change, and replace estimates with measurements as soon as a prototype or production data exists.

Lab: measuring the numbers you estimate with

The lab machine is a 2-vCPU cloud VM with an NVMe-backed virtual disk. Tools: a C program compiled with gcc -O2, fio 3 with direct=1 (bypassing the page cache), PostgreSQL 16 and Redis 7 on the same machine, and Python 3. Your numbers will differ; the ratios between levels are what carry over.

Experiment 1: the memory hierarchy

A pointer-chasing loop reads one random element at a time from an array of a given size, so each read depends on the previous one and the CPU can't prefetch:

Text
random read, working set 16 KiB (fits L1)              1.6 ns
random read, working set 256 KiB (L2)                  5.4 ns
random read, working set 4 MiB (L3)                   45.5 ns
random read, working set 64 MiB (DRAM)               188.2 ns
random read, working set 512 MiB (DRAM, TLB misses)  259.0 ns
uncontended mutex lock+unlock                          3.8 ns
system call (getpid)                                 124.8 ns

On bare metal DRAM latency is usually 80–120 ns; the VM adds address-translation overhead, and the 512 MiB case also misses the TLB (the cache of page-table entries). The 4 MiB figure is high because the VM's share of the last-level cache is small. The system call costs 125 ns here because of virtualisation and kernel side-channel mitigations; on bare metal without them it can be under 100 ns.

Experiment 2: storage

Text
SSD random 4 KiB read, queue depth 1:  35 µs mean, p99 106 µs, 18,854 IOPS
sequential 1 MiB reads, depth 8:       1,885 MiB/s
4 KiB write + fsync:                   152 µs per fsync, 6,258 durable writes/s
Shell
fio --name=rr --rw=randread --bs=4k --direct=1 --ioengine=libaio --iodepth=1 --size=512M --runtime=8
fio --name=fs --rw=write --bs=4k --fsync=1 --ioengine=sync --size=64M --runtime=6

At queue depth 1, IOPS is just 1 ÷ latency (1 ÷ 35 µs ≈ 28,000; measured 18,854 including submission overhead). Real databases issue many I/Os in parallel and group commits, so they reach far more than 6,258 commits per second on this disk; the fsync figure is the floor for "one transaction at a time, each waiting for its own flush".

Experiment 3: network and services

Text
localhost TCP round trip (Python):           29.7 µs
Redis GET round trip:                       107.5 µs
PostgreSQL primary-key SELECT (TCP):        120.3 µs
PostgreSQL INSERT + COMMIT (durable):       581.9 µs
zlib compress 20 KiB JSON:                   92.4 µs  (22,447 → 1,464 bytes)
SHA-256 of 20 KiB:                           14.8 µs

Most of the Redis and PostgreSQL time here is the Python client and the loopback round trip, not the server's work; redis-benchmark from C reports far less per request. That is itself an estimation lesson: per-request cost is usually dominated by round trips and serialisation, so batching (pipelines, multi-row inserts) changes throughput by an order of magnitude more than a faster server does. Compression shrank the menu 15×, which matters more for bandwidth than its 92 µs of CPU.

Experiment 4: storage estimate against reality

SQL
create table est_orders(id bigint primary key, customer_id bigint, kitchen_id int,
                        status smallint, total_paise int, created_at timestamptz);
insert into est_orders select g, … from generate_series(1, 1000000) g;   -- 2.19 s
create index on est_orders(customer_id, created_at);
Object Size Per row
raw column data 34 MB 34 B
table (heap) 65 MB 68.3 B
primary key index 21 MB 22 B
(customer_id, created_at) index 30 MB 31 B
total 117 MB ≈117 B

A million rows loaded in 2.2 s (one statement, one commit, about 450,000 rows per second), compared with 0.58 ms per single-row insert and commit (about 1,700 per second). That 260× gap is batching.

Try it yourself

  1. Rerun the pointer chase with sequential instead of random order. How much faster is DRAM when the prefetcher can help?
  2. Run the fio random read at --iodepth=32. How do IOPS and latency change, and what does Little's law say about the relationship?
  3. Insert the million rows in batches of 1, 10, 100 and 1,000 per transaction and plot rows per second.
  4. Estimate the storage for one year of order status events (5 per order, 500,000 orders a day) and then measure 1 million of them.

Revision sheet: estimation

Key ideas

  • Order of magnitude is the goal; state assumptions, round aggressively, sanity-check against known systems.
  • Traffic: users × actions per user per day ÷ 86,400 = average QPS; × peak factor (2–10×); split reads and writes.
  • Storage: rows × (data + overhead + indexes) × replicas × retention, plus backups and growth headroom.
  • Bandwidth: QPS × response size; compression changes it dramatically.
  • Memory: working set (hot fraction × size) for caches; connections × per-connection memory.
  • Latency hierarchy: cache ns → DRAM ~100 ns → SSD tens of µs → same-DC network ~0.5 ms → cross-continent ~100–200 ms.
  • Batching amortises round trips and fsyncs; it's usually the biggest lever.
  • Capacity: measure one instance, then instances = peak load ÷ (per-instance capacity × target utilisation).

Numbers to remember

  • 86,400 s/day; 1 M/day ≈ 12/s; 1 B/day ≈ 12,000/s.
  • Lab: DRAM 188 ns, SSD read 35 µs, fsync 152 µs, local PG query 120 µs, PG insert+commit 582 µs.
  • Lab: PostgreSQL row ≈ 68 B for 34 B of columns; with two indexes ≈ 117 B (3.4×).
  • Lab: one-statement bulk load ≈ 450,000 rows/s vs ≈ 1,700/s with one commit per row.
  • Light in fibre ≈ 200,000 km/s → ~1 ms round trip per 100 km, before routing.

Pitfalls

  • Averages without peaks; forgetting write amplification, indexes and replicas.
  • Precision theatre (five significant figures on a guess).
  • Mixing bits and bytes (Mbit/s vs MB/s, ×8).
  • Assuming per-request cost from server time while ignoring round trips.
  • Never checking estimates against a measurement.

Glossary

  • Peak factor: peak load ÷ average load.
  • Working set: the data actively accessed in a period.
  • Write amplification: bytes physically written per byte of logical data.
  • Headroom: spare capacity kept for spikes and failures.
  • IOPS: I/O operations per second.