Skip to content
System design · Chapter 17 of 21 Day 15: Capacity Estimation and the Design Document

Day 15: Capacity Estimation and the Design Document

Goal: You estimate what kurz needs at 100 million redirects per day, using numbers you measured yourself instead of tables from the web. You check an estimate against reality, find the first bottleneck and write everything into a design document that a colleague understands without you · Duration: approx. 75 min · Prerequisite: Day 14

Briefing

  • So far you’ve measured what the system currently handles. Today you turn the question around: what must it handle, and is that enough? This calculation is called “back of the envelope”: rough, quick and good enough to make a decision.
  • An estimate is only as good as its inputs. Bytes per link, bytes per cache entry, requests per core: you can measure all of it in your lab. After 14 days, you have a system that delivers real numbers.
  • The design document sums it up: what the system should do, what it explicitly shouldn’t, with which numbers, from which components, what happens on failures, and which trade-offs it contains. It’s the text you bring to the whiteboard in an interview and file in the wiki in operations.
Term Meaning
average and peak average over the day and the highest value, here three times the average
working set the data that is needed often and belongs in the cache
headroom (N+1) one machine more than necessary, so that one failure doesn’t knock anything over
first bottleneck the component that hits its limit first as you grow

Today’s assignment: 100 million redirects and 1 million new links per day; links are kept for 5 years.

Drill 1: What Does a Link Cost?

Three sizes determine storage: the row in PostgreSQL including indexes, the entry in the cache and the message per click in JetStream.

# on s1
mkdir -p ~/sd/tag15 && cd ~/sd/tag15
export PGPASSWORD=lab-kurz-123
psql -h s3 -U kurz -d kurz -c "select count(*) as links, pg_size_pretty(pg_relation_size('links')) as tabelle, pg_size_pretty(pg_indexes_size('links')) as indizes, pg_size_pretty(pg_total_relation_size('links')) as gesamt, pg_total_relation_size('links') / count(*) as byte_pro_link from links"
psql -h s3 -U kurz -d kurz -c "select indexrelname, pg_size_pretty(pg_relation_size(indexrelid)) from pg_stat_user_indexes where relname = 'links'"
psql -h s3 -U kurz -d kurz -tAc "select avg(length(url))::int, avg(length(code))::int from links"
nats stream info KLICKS --json | jq -c '.state | {messages, bytes}'

Expected (your numbers will differ):

  links  | tabelle | indizes | gesamt | byte_pro_link
---------+---------+---------+--------+---------------
 2614627 | 215 MB  | 269 MB  | 484 MB |           194
(1 row)

 indexrelname  | pg_size_pretty
---------------+----------------
 links_pkey    | 77 MB
 links_url_idx | 161 MB
 links_url_neu | 31 MB
(3 rows)

37|7
{"messages":209861,"bytes":9024064}

On average 194 bytes per link, although a URL has only 37 characters and a code 7. More than half is indexes: the index on url (for the dedupe lookup from Day 7) is twice the size of the one on code. Each click takes up 9,024,064 / 209,861 = 43 bytes in the stream.

Save your progress? Sign up for free

Drill 2: What Does a Cache Entry Cost?

Valkey is almost empty right now: hardly anyone has been redirected since Day 14, and entries expire after 10 minutes. So write 100,000 real links into the cache, in the same form as kurz (link: before the code, 600 seconds lifetime), and compare memory before and after. valkey-cli --pipe takes the commands directly from psql:

# on s1
V="valkey-cli -h s3 -a lab-valkey-123 --no-auth-warning"
vor=$($V info memory | awk -F: '/^used_memory:/ {print $2}' | tr -d '\r')
psql -h s3 -U kurz -d kurz -tAc "copy (select 'SET link:' || code || ' ' || url || ' EX 600' from links order by random() limit 100000) to stdout" | $V --pipe
nach=$($V info memory | awk -F: '/^used_memory:/ {print $2}' | tr -d '\r')
$V dbsize
echo "Byte pro Eintrag: $(( (nach - vor) / 100000 ))"
$V memory usage "$($V randomkey)"

Expected:

All data transferred. Waiting for the last reply...
Last reply received from server.
errors: 0, replies: 100000
100000
Byte pro Eintrag: 108
80

108 bytes per entry, measured across the whole server. memory usage reports only 80 bytes for a single key: the hash table and the expiry times come on top of that per entry. For the estimate, the whole-server number counts. The test entries disappear on their own after 10 minutes.

Save your progress? Sign up for free

Drill 3: How Much Can One Core Handle?

The staircase from Day 2, this time for redirects from the cache with everything that’s been added since: quotas, load shedding, clicks via NATS.

# on s1
cd ~/sd/tag15 && cp ~/sd/tag14/klick.js ~/sd/tag14/codes.txt .
for rate in 1500 2000 2500 3000; do
  echo "== $rate/s"
  k6 run -q -e RATE=$rate -e DAUER=20s klick.js 2>&1 | grep -E 'http_req_duration\.|http_req_failed\.|http_reqs\.|dropped'
done

Expected:

== 1500/s
    http_req_duration..............: avg=9.69ms  min=912.92µs med=4.87ms max=853.47ms p(90)=22.06ms p(95)=28.82ms
    http_req_failed................: 3.68%  1097 out of 29748
    http_reqs......................: 29748  1486.786435/s
    dropped_iterations.............: 251    12.544823/s
== 2000/s
    http_req_duration..............: avg=17.16ms min=764.37µs med=11.3ms  max=183.84ms p(90)=38.2ms  p(95)=48.63ms
    http_req_failed................: 0.47%  183 out of 38626
    http_reqs......................: 38626  1930.930185/s
    dropped_iterations.............: 1374   68.686845/s
== 2500/s
    http_req_duration..............: avg=27.6ms  min=1.14ms med=24.56ms max=256.32ms p(90)=50.28ms p(95)=61.81ms
    http_req_failed................: 5.13%  2397 out of 46647
    http_reqs......................: 46647  2327.36206/s
    dropped_iterations.............: 3352   167.241572/s
== 3000/s
    http_req_duration..............: avg=38.38ms min=1.25ms med=32.94ms max=246.8ms  p(90)=62.54ms p(95)=80.32ms
    http_req_failed................: 20.16% 10821 out of 53666
    http_reqs......................: 53666  2678.632821/s
    dropped_iterations.............: 6335   316.199063/s

The 3.68% at 1500 per second is a cold start: the 1000 codes were no longer in the cache, the first requests went to the database, and load shedding rejected them. A second run with a warm cache:

# on s1
k6 run -q -e RATE=1500 -e DAUER=20s klick.js 2>&1 | grep -E 'http_req_duration\.|http_req_failed\.|http_reqs\.|dropped'

Expected:

    http_req_duration..............: avg=8.02ms min=874.18µs med=5.08ms max=153.71ms p(90)=17.95ms p(95)=25.31ms
    http_req_failed................: 0.01%  3 out of 29954
    http_reqs......................: 29954  1497.266899/s
    dropped_iterations.............: 47     2.34932/s

Almost error-free up to 2000 per second; above that, load shedding kicks in, at 3000 for every fifth request. Which process needs how much CPU is shown by top under a load of 1500 per second:

# on s1
k6 run -q -e RATE=1500 -e DAUER=20s klick.js > last.log 2>&1 &
sleep 10
top -bn2 -d 3 -p "$(pgrep -d, -x haproxy),$(pgrep -d, -x kurz),$(pgrep -d, -x k6)" | awk '/^ *PID/ {n++} n==2 && $1 ~ /^[0-9]+$/ {print $9"% "$12}'
ssh s3 "top -bn2 -d 3 -p \$(pgrep -d, -x valkey-server),\$(pgrep -d, -x pgbouncer) | awk '/^ *PID/ {n++} n==2 && \$1 ~ /^[0-9]+\$/ {print \$9\"% \"\$12}'"
wait; grep -E 'http_req_failed\.' last.log

Expected (values fluctuate):

135.5% k6
64.1% haproxy
49.5% kurz
0.0% haproxy
19.0% valkey-+
0.0% pgbounc+
    http_req_failed................: 0.00%  0 out of 29944

kurz on s1 gets half, so 750 requests per second, and at 49.5% sits exactly at its limit of half a core (Day 3). So one full core handles about 1500 redirects per second. HAProxy needs 64% of a core for 1500 per second, Valkey 19%. k6 itself is the biggest consumer, which is why things end at 3000 per second on s1 anyway.

Save your progress? Sign up for free

Drill 4: The Estimate and Its Check

Now do the math. awk is enough as a calculator, and the calculation stays readable in the terminal history. First a check: does the average of 194 bytes also hold for new links? Create 10,000 new links and measure how much the table grows:

# on s1
cd ~/sd/tag15 && cp ~/sd/tag14/anlegen.js .
groesse() { psql -h s3 -U kurz -d kurz -tAc "select pg_total_relation_size('links'), count(*) from links"; }
vor=$(groesse); echo "vorher: $vor"
k6 run -q -e RATE=500 -e DAUER=20s anlegen.js 2>&1 | grep -A1 -E '^ +[✓✗] 201'
nach=$(groesse); echo "nachher: $nach"
echo "$vor $nach" | awk -F'[| ]' '{printf "Byte pro neuem Link: %.0f\n", ($3-$1)/($4-$2)}'

Expected:

vorher: 507617280|2614627
    ✗ 201
      ↳  99% — ✓ 9970 / ✗ 31
nachher: 511361024|2624597
Byte pro neuem Link: 376

376 instead of 194 bytes, almost double. New links additionally land in the partial index links_url_neu from Day 11, their URLs are longer than the existing stock, and PostgreSQL allocates new pages in blocks. The average over old data would have underestimated the disk by half. So the calculation uses 376:

# on s1
awk 'BEGIN {
  klicks = 100e6; neu = 1e6; spitze = 3; tag = 86400
  printf "Weiterleitungen: %6.0f/s im Mittel, %6.0f/s Spitze\n", klicks/tag, spitze*klicks/tag
  printf "Anlegen:         %6.1f/s im Mittel, %6.1f/s Spitze\n", neu/tag, spitze*neu/tag
  printf "PostgreSQL:      %6.0f MB/Tag, %4.0f GB in 5 Jahren\n", neu*376/1e6, neu*376*365*5/1e9
  printf "Cache 7 Tage:    %6.0f MB\n", 7*neu*108/1e6
  printf "JetStream 24 h:  %6.1f GB\n", klicks*43/1e9
  printf "kurz:            %6.1f Kerne in der Spitze\n", spitze*klicks/tag/1500
}'
for s in s2 s3; do ssh $s "hostname; df -h / | tail -1"; done
awk 'BEGIN { printf "%.0f Tage bis die Platte von s3 voll ist\n", 24e9 / (1e6*376) }'

Expected:

Weiterleitungen:   1157/s im Mittel,   3472/s Spitze
Anlegen:           11.6/s im Mittel,   34.7/s Spitze
PostgreSQL:         376 MB/Tag,  686 GB in 5 Jahren
Cache 7 Tage:       756 MB
JetStream 24 h:     4.3 GB
kurz:               2.3 Kerne in der Spitze
s2
/dev/sda1        29G  4.5G   24G  16% /
s3
/dev/sda1        29G  4.5G   24G  16% /
64 Tage bis die Platte von s3 voll ist

What the numbers say:

  • Compute is not a problem. 3472 redirects per second need 2.3 cores for kurz. With one instance of headroom and room for peaks above three times the average: four instances with one core each.
  • Link creation is not a problem. 35 per second at peak; measured, the system handles 1050.
  • The cache is too small. If the links of the last week are to be in the cache, Valkey needs 756 MB; 256 MB is configured (Day 0). No crash: allkeys-lru evicts the oldest, and the hit rate drops.
  • The disk is the first bottleneck. After 64 days, s3 is full, and s2 as the replica at the same time. 686 GB in five years fits on none of the lab machines. This is where the question from Day 9 begins: bigger disk or sharding.

Save your progress? Sign up for free

Drill 5: The Design Document

Everything you’ve built and measured in 15 days, on one page. Every number with its source, every trade-off with the price it costs:

# on s1
cd ~/sd/tag15
cat > design.md <<'EOF'
# Design: kurz, URL-Shortener

## Ziele und Nicht-Ziele
- Ziel: kurze Codes anlegen, schnell weiterleiten, Klicks zählen.
- Ziel: Weiterleitungen überleben den Ausfall einer Datenbank oder Instanz.
- Nicht-Ziel: eigene Wunsch-Codes, Statistik in Echtzeit, Löschen von Links.

## Annahmen und Zahlen
| Größe | Wert | Quelle |
|---|---|---|
| Weiterleitungen | 100 Mio./Tag, Spitze 3472/s | Auftrag, Spitze = 3 × Mittel |
| neue Links | 1 Mio./Tag, Spitze 35/s | Auftrag |
| Speicher je Link | 376 Byte | Tag 15, Drill 4 (gemessen) |
| Cache je Eintrag | 108 Byte | Tag 15, Drill 2 (gemessen) |
| Nachricht je Klick | 43 Byte | Tag 15, Drill 1 (gemessen) |
| Weiterleitungen je Kern | 1500/s | Tag 15, Drill 3 (gemessen) |
| Anlegen gesamt | 1050/s | Tag 12, Drill 1 (gemessen) |

## Architektur
HAProxy (Kontingent pro Schlüssel, Lastabwurf) → kurz-Instanzen (zustandslos) →
Valkey (Cache-Aside) → PostgreSQL Primär + Replikat (Lesen vom Replikat, Rückgriff auf Primär).
Klicks: kurz → NATS JetStream (24 h) → zaehler (Batch, genau einmal) → PostgreSQL.

## Kapazität
- kurz: 2,3 Kerne in der Spitze, mit N+1 und Reserve 4 Instanzen à 1 Kern.
- PostgreSQL: 376 MB/Tag, 686 GB in 5 Jahren → Platte ist der erste Engpass (heute 64 Tage).
- Valkey: Links der letzten 7 Tage = 756 MB → maxmemory 1 GB statt 256 MB.
- JetStream: 4,3 GB für 24 h Aufbewahrung auf s2.

## Ausfälle und Verhalten
| Ausfall | Verhalten | Tag |
|---|---|---|
| eine kurz-Instanz | Health-Check nimmt sie raus, Retry bei GET | 4, 13 |
| Valkey | Weiterleitungen aus der Datenbank, langsamer | 6 |
| Replikat | Rückgriff auf Primär nach 300 ms | 13 |
| Primär | Anlegen scheitert schnell (Sicherung), Failover von Hand | 13, 14 |
| NATS | Klicks im Puffer von kurz, danach nachgereicht | 10 |
| Überlast | 429 pro Schlüssel, 503 bei voller Warteschlange | 12 |

## Abwägungen
- Asynchrone Replikation: kein Warten beim Schreiben, aber Verlust möglich beim Failover.
- Klicks über NATS: Weiterleitung schnell, Zahlen hinken Sekunden hinterher.
- Failover von Hand: kein Split Brain durch Automatik, dafür Minuten statt Sekunden.

## Offene Fragen
- Ab wann Sharding statt größerer Platte (Tag 9)?
- Automatischer Failover mit Mehrheitsentscheid (drei Knoten)?
EOF
grep -c '^## ' design.md; wc -l design.md

Expected:

7
47 design.md

Seven sections, 47 lines. More important than the length: for every number, a reader finds where it comes from, and for every decision, what it costs. The table “Ausfälle und Verhalten” (failures and behavior) is the one someone in operations looks for at night.

Save your progress? Sign up for free

Exercise: Speed drills

  1. How many bytes does a link take up on average in PostgreSQL, including indexes? Target time: 1 min
  2. How many entries does the cache have right now, and how much memory does it use? Target time: 30 s
  3. How many bytes does a click take up in the stream? Target time: 30 s

Solution

# on s1
psql -h s3 -U kurz -d kurz -tAc "select pg_total_relation_size('links') / count(*) from links"
valkey-cli -h s3 -a lab-valkey-123 --no-auth-warning dbsize
valkey-cli -h s3 -a lab-valkey-123 --no-auth-warning info memory | grep used_memory_human
nats stream info KLICKS --json | jq '.state.bytes / .state.messages | floor'

Expected (your numbers will differ):

194
100956
used_memory_human:12.01M
43

Save your progress? Sign up for free

Checkpoint

# on s1
grep -c "^## " ~/sd/tag15/design.md

Expected: 7

# on s1
grep -c "gemessen" ~/sd/tag15/design.md

Expected: 5, five numbers come from your lab.

# on s1
grep "^- PostgreSQL" ~/sd/tag15/design.md

Expected:

- PostgreSQL: 376 MB/Tag, 686 GB in 5 Jahren → Platte ist der erste Engpass (heute 64 Tage).

Challenge

Marketing is planning for ten times as much: one billion redirects a day. Which component is the first to need more than one machine with a few cores? Use the CPU values from Drill 3.

Hint: HAProxy, kurz and Valkey each needed a measurable share of a core at 1500 requests per second. kurz on s1 got only half of those.

Solution

# on s1
awk 'BEGIN { s = 10 * 3 * 100e6 / 86400; printf "Spitze: %.0f/s\n", s; printf "HAProxy: %.1f Kerne\n", s / 1500 * 0.641; printf "kurz:    %.1f Kerne\n", s / 750 * 0.495; printf "Valkey:  %.1f Kerne\n", s / 1500 * 0.19; printf "Anlegen: %.0f/s von 1050/s\n", 10 * 3 * 1e6 / 86400 }'

Expected:

Spitze: 34722/s
HAProxy: 14.8 Kerne
kurz:    22.9 Kerne
Valkey:  4.4 Kerne
Anlegen: 347/s von 1050/s

kurz needs the most cores, but it’s stateless: 23 instances behind the load balancer, done. The real bottleneck is HAProxy with almost 15 cores. A single load balancer is a single process on one machine. From here on you need several, distributed via DNS or anycast, or a leaner layer 4 load balancer. Part of the 64% goes into logging every request (option httplog to /dev/log); that would be the first knob to turn.

Valkey with 4.4 cores is the quiet candidate: it processes commands in one main thread. So a single instance doesn’t simply scale with more cores. Read replicas or a cluster help here.

Be careful when extrapolating: scaling 19% at 1500 per second linearly to twenty times as much often underestimates what Valkey manages with pipelined requests. An estimate tells you where to measure next, not what the result is.

Save your progress? Sign up for free

Clean-up

Nothing to tear down. The 100,000 test entries in Valkey expire after 10 minutes; the 10,000 new links from Drill 4 stay in the table like all load test links. The design document lives in ~/sd/tag15/design.md and comes up again on Day 16.

Ten minutes after Drill 2:

# on s1
valkey-cli -h s3 -a lab-valkey-123 --no-auth-warning dbsize

Expected: a small number instead of just over 100,000; the test entries are gone. In my case: 457

Interview note

  • Calculate out loud and round boldly. 100 million a day is just over 1000 per second (a day has roughly 100,000 seconds). Peak = 2 to 3 × average. Storage = count × size × time. State the assumptions first, then the calculation.
  • Look at reads and writes separately. For a URL shortener, the ratio is 100 to 1. That decides where cache and replicas help and where they don’t.
  • Name the first bottleneck and say what you’ll do then: bigger machine, more machines, sharding, a different data model.

Enterprise note

  • In operations, capacity planning runs continuously: growth per week from monitoring, thresholds for disk, memory and CPU with lead time for procurement. An estimate like today’s is the start; monitoring keeps it current.
  • Depending on the company, design documents are called RFC, ADR (Architecture Decision Record) or design doc. What they have in common: goals, non-goals, alternatives and why they were rejected.
  • Load tests at the scale of the target run on dedicated infrastructure, not from a laptop. As here, the load generator itself is often the bottleneck before the system is.

Contents

More