Day 1: The app and the first measurement
Goal: Build and run the URL shortener
kurzand measure it under load for the first time, after first estimating what the result should be · Duration: approx. 75 min · Prerequisite: Day 0
Briefing
- A URL shortener has two paths: create
(
POST /api/links, long address in, short code out) and redirect (GET /<code>, response 302 with the target address). Redirects happen much more often than creates. We assume 9 to 1. - Version 1 is deliberately plain: one instance on s1, one table in PostgreSQL on s3, no cache, no queue. Everything added over the next days has to prove itself against this baseline.
- Before you measure, you estimate. An estimate that is off by a factor of 10 is a finding: either your model is wrong or the system has a problem.
k6 (s1) ──HTTP──▶ kurz :8080 (s1) ──SQL──▶ PostgreSQL :5432 (s3)
GET /<code> → SELECT url FROM links WHERE code = …
POST /api/links → INSERT INTO links …
Drill 1: The code
The whole app is one file. The database driver is pgx, the most widely used PostgreSQL driver for Go, with its built-in connection pool:
# on s1
mkdir -p ~/kurz && cd ~/kurz
go mod init kurz
cat > main.go <<'EOF'
// kurz: ein kleiner URL-Shortener. Version 1: eine Instanz, eine Datenbank.
package main
import (
"context"
"crypto/rand"
"encoding/json"
"errors"
"log"
"net/http"
"net/url"
"os"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
)
const alphabet = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789"
var (
db *pgxpool.Pool
instanz = env("KURZ_INSTANZ", "kurz")
)
func env(key, def string) string {
if v := os.Getenv(key); v != "" {
return v
}
return def
}
// neuerCode erzeugt 7 zufällige Zeichen (57^7 ≈ 1,9 Billionen Möglichkeiten).
func neuerCode() string {
b := make([]byte, 7)
rand.Read(b)
for i := range b {
b[i] = alphabet[int(b[i])%len(alphabet)]
}
return string(b)
}
func anlegen(w http.ResponseWriter, r *http.Request) {
var in struct {
URL string `json:"url"`
}
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
http.Error(w, "JSON erwartet", http.StatusBadRequest)
return
}
u, err := url.Parse(in.URL)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
http.Error(w, "ungültige URL", http.StatusBadRequest)
return
}
for versuch := 0; versuch < 3; versuch++ {
code := neuerCode()
_, err := db.Exec(r.Context(),
"INSERT INTO links (code, url) VALUES ($1, $2)", code, in.URL)
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
continue // Code schon vergeben: neuer Versuch
}
if err != nil {
log.Printf("anlegen: %v", err)
http.Error(w, "Datenbankfehler", http.StatusServiceUnavailable)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(map[string]string{"code": code, "url": in.URL})
return
}
http.Error(w, "kein freier Code", http.StatusInternalServerError)
}
func weiterleiten(w http.ResponseWriter, r *http.Request) {
var ziel string
err := db.QueryRow(r.Context(), "SELECT url FROM links WHERE code = $1",
r.PathValue("code")).Scan(&ziel)
if errors.Is(err, pgx.ErrNoRows) {
http.NotFound(w, r)
return
}
if err != nil {
log.Printf("weiterleiten: %v", err)
http.Error(w, "Datenbankfehler", http.StatusServiceUnavailable)
return
}
http.Redirect(w, r, ziel, http.StatusFound)
}
func bereit(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), time.Second)
defer cancel()
if err := db.Ping(ctx); err != nil {
http.Error(w, "Datenbank nicht erreichbar", http.StatusServiceUnavailable)
return
}
w.Write([]byte("bereit\n"))
}
func main() {
var err error
dsn := env("KURZ_DB", "postgres://kurz:lab-kurz-123@s3:5432/kurz")
db, err = pgxpool.New(context.Background(), dsn)
if err != nil {
log.Fatal(err)
}
if _, err := db.Exec(context.Background(), `CREATE TABLE IF NOT EXISTS links (
code text PRIMARY KEY,
url text NOT NULL,
angelegt timestamptz NOT NULL DEFAULT now())`); err != nil {
log.Fatal(err)
}
mux := http.NewServeMux()
mux.HandleFunc("POST /api/links", anlegen)
mux.HandleFunc("GET /{code}", weiterleiten)
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok\n"))
})
mux.HandleFunc("GET /readyz", bereit)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Kurz-Instanz", instanz)
mux.ServeHTTP(w, r)
})
addr := env("KURZ_ADDR", ":8080")
log.Printf("%s lauscht auf %s", instanz, addr)
log.Fatal(http.ListenAndServe(addr, handler))
}
EOFExpected:
go: creating new go.mod: module kurz
Three spots are worth a second look:
| Spot | Why |
|---|---|
neuerCode() |
7 characters from 57 letters and digits, without easily confused
ones like 0/O and
1/l. That makes 57⁷ ≈ 1.9 trillion codes |
Loop with 23505 |
If a code is already taken, PostgreSQL reports a unique violation, and the app rolls again. How often that happens, you measure on Day 9 |
X-Kurz-Instanz |
Every response says which instance delivered it. From Day 3 on, this lets you see the load balancer at work |
Build:
# on s1
go mod tidy 2>&1 | grep found
go vet . && go build -o kurz .
ls -l kurz | awk '{print $5, $9}'
grep '^require github' go.modExpected:
go: found github.com/jackc/pgx/v5 in github.com/jackc/pgx/v5 v5.13.0
go: found github.com/jackc/pgx/v5/pgconn in github.com/jackc/pgx/v5 v5.13.0
16035249 kurz
require github.com/jackc/pgx/v5 v5.13.0
A single 16 MB file, with no further dependencies. That is also how it gets to s2 from Day 3 on.
Save your progress? Sign up for free
Drill 2: Running it as a service
# on s1
sudo install kurz /usr/local/bin/kurz
sudo tee /etc/systemd/system/kurz.service >/dev/null <<'EOF'
[Unit]
Description=kurz URL-Shortener
After=network-online.target
[Service]
Environment=KURZ_INSTANZ=s1
Environment=KURZ_DB=postgres://kurz:lab-kurz-123@s3:5432/kurz
DynamicUser=yes
ExecStart=/usr/local/bin/kurz
Restart=on-failure
[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now kurz
journalctl -u kurz --no-pager -n 1 | cut -c1-80
curl -s localhost:8080/readyzExpected:
Created symlink /etc/systemd/system/multi-user.target.wants/kurz.service → /etc/systemd/system/kurz.service.
Nov 22 18:50:52 s1 kurz[7752]: 2026/11/22 18:50:52 s1 lauscht auf :8080
bereit
DynamicUser=yes makes systemd create an unprivileged
user for the service that exists only as long as the service runs. And
the two paths:
# on s1
curl -s -X POST localhost:8080/api/links -d '{"url":"https://kubernetes.io/docs/"}'; echo
C=$(curl -s -X POST localhost:8080/api/links -d '{"url":"https://example.org/"}' | jq -r .code)
curl -si localhost:8080/$C | grep -E '^HTTP|^Location|^X-Kurz'
curl -si localhost:8080/gibtsnicht | head -1
curl -s -X POST localhost:8080/api/links -d '{"url":"ftp://x"}'Expected:
{"code":"MPKfz5D","url":"https://kubernetes.io/docs/"}
HTTP/1.1 302 Found
Location: https://example.org/
X-Kurz-Instanz: s1
HTTP/1.1 404 Not Found
ungültige URL
Save your progress? Sign up for free
Drill 3: Test data
We do not measure against an empty table. 100,000 links, each with a code from the first seven characters of an MD5 hash:
# on s1
mkdir -p ~/sd/tag01 && cd ~/sd/tag01
export PGPASSWORD=lab-kurz-123
psql -h s3 -U kurz -d kurz -c "INSERT INTO links (code, url)
SELECT substr(md5(i::text), 1, 7), 'https://example.org/seite/' || i
FROM generate_series(1, 100000) i ON CONFLICT DO NOTHING"
psql -h s3 -U kurz -d kurz -tAc "select code from links order by random() limit 1000" > codes.txt
wc -l codes.txtExpected:
INSERT 0 99979
1000 codes.txt
99,979 instead of 100,000: 21 hashes had the same first seven
characters, and ON CONFLICT DO NOTHING discarded the
duplicates. With 16⁷ ≈ 268 million possible prefixes, the birthday
paradox predicts n²/2N ≈ 18.6 collisions. The topic comes back on Day
9.
Save your progress? Sign up for free
Drill 4: Estimate first
How much space does a link need? The database tells you:
# on s1
psql -h s3 -U kurz -d kurz -c "select count(*) as links,
pg_size_pretty(pg_table_size('links')) as tabelle,
pg_size_pretty(pg_indexes_size('links')) as index,
pg_total_relation_size('links') / count(*) as bytes_pro_link from links"Expected:
links | tabelle | index | bytes_pro_link
--------+---------+---------+----------------
100577 | 7568 kB | 2616 kB | 103
(1 row)
A good 100 bytes per link, index included. This gives the first back-of-the-envelope calculation, as it comes up in every system design interview:
| Assumption | Calculation | Result |
|---|---|---|
| 100M new links per month | 100M / (30 × 86,400 s) | ≈ 40 writes/s |
| Read : write = 9 : 1 | 40 × 9 | ≈ 360 redirects/s |
| Peak = 3 × average | 400 × 3 | ≈ 1200 requests/s |
| Keep for 5 years | 100M × 60 × 103 bytes | ≈ 620 GB |
And how long does a redirect take? A network hop s1 → s3 costs under one millisecond (Day 0), the query itself:
# on s1
psql -h s3 -U kurz -d kurz -c "explain analyze select url from links where code = 'MPKfz5D'" \
| sed -n 3,6p | cut -c1-100Expected:
Index Scan using links_pkey on links (cost=0.29..8.31 rows=1 width=31) (actual time=0.099..0.10
Index Cond: (code = 'MPKfz5D'::text)
Index Searches: 1
Buffers: shared hit=3
0.1 ms via the primary key, three pages from memory. The estimate for a redirect: one round trip to the database plus HTTP on s1, so a few milliseconds.
Save your progress? Sign up for free
Drill 5: Then measure
k6 generates load according to plan. The script mixes 90% redirects with 10% new links and sends a fixed rate of requests per second, no matter how fast the responses come:
# on s1
cat > mix.js <<'EOF'
import http from "k6/http";
import { check } from "k6";
import { SharedArray } from "k6/data";
const codes = new SharedArray("codes", () => open("./codes.txt").split("\n").filter(Boolean));
const ZIEL = __ENV.ZIEL || "http://localhost:8080";
export const options = {
scenarios: {
mix: {
executor: "constant-arrival-rate",
rate: Number(__ENV.RATE || 200), timeUnit: "1s",
duration: __ENV.DAUER || "30s",
preAllocatedVUs: 50, maxVUs: 500,
},
},
thresholds: { http_req_failed: ["rate<0.01"], http_req_duration: ["p(95)<200"] },
};
export default function () {
if (Math.random() < 0.9) {
const code = codes[Math.floor(Math.random() * codes.length)];
const r = http.get(`${ZIEL}/${code}`, { redirects: 0, tags: { name: "weiterleiten" } });
check(r, { "302": (x) => x.status === 302 });
} else {
const r = http.post(`${ZIEL}/api/links`, JSON.stringify({ url: `https://example.org/neu/${__VU}-${__ITER}` }),
{ headers: { "Content-Type": "application/json" }, tags: { name: "anlegen" } });
check(r, { "201": (x) => x.status === 201 });
}
}
EOF
k6 run --quiet mix.js | grep -E 'http_req_duration\.|http_req_failed\.|http_reqs\.|checks_succeeded'Expected:
checks_succeeded...: 100.00% 6001 out of 6001
http_req_duration..............: avg=2.16ms min=1.01ms med=1.83ms max=54.66ms p(90)=3.23ms p(95)=3.99ms
http_req_failed................: 0.00% 0 out of 6001
http_reqs......................: 6001 200.017189/s
| Value | Meaning |
|---|---|
http_reqs 200/s |
the planned rate was held |
med 1.8 ms |
half of all requests were faster |
p(95) 4.0 ms |
95% were faster; this is the number for commitments |
max 55 ms |
an outlier. Why there are outliers is explained on Day 2 |
http_req_failed 0% |
no errors |
The estimate “a few milliseconds” is spot on. The baseline for
everything that follows: 200 requests/s, p95 4 ms, 0
errors. The thresholds in the script (thresholds)
turn this into a test: if p95 goes above 200 ms or the error rate above
1%, k6 exits with an error code.
Save your progress? Sign up for free
Exercise: Speed drills
- Create a link and call it. Target time: 1 min
- Show how many links exist. Target time: 30 s
- Start k6 with 100 requests per second for 10 seconds. Target time: 1 min
Solution
# on s1
C=$(curl -s -X POST localhost:8080/api/links -d '{"url":"https://go.dev/"}' | jq -r .code)
curl -si localhost:8080/$C | grep ^Location
psql -h s3 -U kurz -d kurz -tAc "select count(*) from links"
RATE=100 DAUER=10s k6 run --quiet mix.js | grep 'http_reqs\.'Save your progress? Sign up for free
Checkpoint
# on s1
systemctl is-active kurzExpected: active
# on s1
cd ~/sd/tag01 && k6 run --quiet mix.js > /dev/null; echo "Exit: $?"Expected: Exit: 0 (all thresholds
met)
Challenge
How many links fit before the table reaches the 620 GB from the back-of-the-envelope calculation, and how many of the 1.9 trillion possible codes are taken by then? At what fill level would you start worrying about collisions when creating links?
Hint: The loop in anlegen() tries three
times.
Solution
620 GB / 103 bytes ≈ 6 billion links. With 1.9 trillion possible codes, that is a fill level of about 0.3%. The probability that a new code is already taken equals the fill level: 0.3% on the first attempt, 0.3% × 0.3% on the second. Three failed attempts in a row then happen about once in 37 million creates. It only becomes critical at a fill level of a few percent. Then a longer code or a different way of generating IDs helps (Day 9).
Save your progress? Sign up for free
Clean-up
Nothing. kurz keeps running, and the test data stays for
the next days.
Interview note
- How do you approach a back-of-the-envelope calculation? From usage to load: users or operations per month → per second (a month has about 2.6 million seconds), read-to-write ratio, factor for peaks, then storage per record times retention period.
- Why 302 and not 301? The browser may cache a 301 forever. Then it never comes back, and you can neither count nor change the target. 302 costs load, but gives you control.
Enterprise note
- Real shorteners check target addresses against lists of known phishing and malware sites; otherwise they become a tool for attackers. That is a separate component with its own latency.
- Load is estimated before a service launches and measured after launch. Both belong in the design document (Day 15), so that later teams know what the system was designed for.