Skip to content
System design · Chapter 11 of 21 Day 9: IDs and Sharding

Day 9: IDs and Sharding

Goal: Measure when random codes collide and when a code space is full, distribute the links across two databases, migrate the existing data and see what distribution costs · Duration: approx. 90 min · Prerequisite: Day 8

Briefing

  • Every link needs a code that occurs only once. Since Day 1, kurz rolls seven characters and, on a collision, tries again up to three times. Today you measure how long that works out.
  • The replicas from Day 8 distribute the reads. Writes still go only to s3. If one database is no longer enough for the writes or the amount of data, you split up the data: sharding.
  • With sharding, a shard key decides which database holds a row. This choice determines which queries stay cheap and which suddenly have to ask all shards.
Term Meaning
Code space all possible codes: alphabet to the power of length, 57⁷ for kurz
Birthday paradox with n random values from N possibilities, there are about n²/2N collisions
Shard an independent database with a part of the rows
Shard key the field from which a row’s shard is calculated, here the code
Resharding redistributing data when shards are added or removed

Today a second PostgreSQL cluster is created on s2 next to the replica, as a shard. By the end of the day it is gone again, and the lab is as it was after Day 8.

Drill 1: How Often Does Chance Collide?

On Day 1 you created 100,000 test links with the first seven characters of an MD5 hash and found 21 duplicate codes. PostgreSQL recalculates this for larger amounts without storing anything:

# on s1
mkdir -p ~/sd/tag09 && cd ~/sd/tag09
export PGPASSWORD=lab-kurz-123
time psql -h s3 -U kurz -d kurz -c "
select n, n - (select count(distinct substr(md5(i::text), 1, 7)) from generate_series(1, n) i) as kollisionen,
       round(n::numeric ^ 2 / (2 * 16::numeric ^ 7), 1) as erwartet
from unnest(array[100000, 1000000, 2000000]) n"

Expected:

    n    | kollisionen | erwartet
---------+-------------+----------
  100000 |          21 |     18.6
 1000000 |        1846 |   1862.6
 2000000 |        7373 |   7450.6
(3 rows)


real    0m18.326s

Seven hex characters give 16⁷ ≈ 268 million codes. With ten times as many links there are a hundred times as many collisions: the formula grows with n², and the measurement follows it exactly. So a space with 268 million slots is anything but empty at just one million entries.

kurz uses 57 characters (without easily confused ones like 0, O, 1, l, I). How full is its space?

# on s1
psql -h s3 -U kurz -d kurz -c "
select count(*) as links, 57::numeric ^ 7 as moeglich,
       round(100 * count(*) / 57::numeric ^ 7, 5) as prozent_belegt,
       round(count(*)::numeric ^ 2 / (2 * 57::numeric ^ 7), 2) as kollisionen_bisher
from links where length(code) = 7"

Expected:

  links  |      moeglich      | prozent_belegt | kollisionen_bisher
---------+--------------------+----------------+--------------------
 2229541 | 1954897493193.0000 |        0.00011 |               1.27
(1 row)

Almost two trillion codes, one millionth of them taken. The probability that a new code is already taken is exactly that fraction: 0.0001%. So the retry in anlegen runs about once per million links. The difference matters: the formula n²/2N counts collisions across all links. For a single new link, only the fraction n/N counts.

Save your progress? Sign up for free

Drill 2: A Code Space Fills Up

A deliberately tiny space shows what happens when the fraction gets large. For this, kurz gets a configurable code length:

# on s1
cd ~/kurz && cp main.go /tmp/main.go.tag08 && cp cache.go /tmp/cache.go.tag08
perl -0pi -e 's/\t"os"\n/\t"os"\n\t"strconv"\n/' main.go
perl -0pi -e 's/(\tinstanz = env\("KURZ_INSTANZ", "kurz"\)\n)/$1\t\/\/ Codelänge, Standard 7. Nur zum Ausprobieren kleiner Code-Räume\n\tcodeLaenge, _ = strconv.Atoi(env("KURZ_CODELAENGE", "7"))\n/' main.go
sed -i 's/b := make(\[\]byte, 7)/b := make([]byte, codeLaenge)/' main.go
diff /tmp/main.go.tag08 main.go
go vet . && go build -o kurz . && echo gebaut

Expected:

12a13
>   "strconv"
25a27,28
>   // Codelänge, Standard 7. Nur zum Ausprobieren kleiner Code-Räume
>   codeLaenge, _ = strconv.Atoi(env("KURZ_CODELAENGE", "7"))
37c40
<   b := make([]byte, 7)
---
>   b := make([]byte, codeLaenge)
gebaut

Two characters give 57² = 3249 codes. A drop-in on both instances and the deploy loop from Day 4:

# on s1
for s in s1 s2; do
  ssh $s "printf '[Service]\nEnvironment=KURZ_CODELAENGE=2\n' \
    | sudo tee /etc/systemd/system/kurz.service.d/code.conf >/dev/null && sudo systemctl daemon-reload"
done
for s in s1 s2; do
  echo "set server kurz/$s state drain" | sudo nc -U /run/haproxy/admin.sock >/dev/null; sleep 2
  scp -q kurz $s:/tmp/kurz
  ssh $s "sudo install /tmp/kurz /usr/local/bin/kurz && sudo systemctl restart kurz"
  until curl -sf http://$s:8080/readyz >/dev/null; do sleep 0.5; done
  echo "set server kurz/$s state ready" | sudo nc -U /run/haproxy/admin.sock >/dev/null
done
curl -s -X POST localhost/api/links -d '{"url":"https://example.org/klein/1"}'; echo

Expected (your code will be different):

{"code":"6p","url":"https://example.org/klein/1"}

Now four rounds with 1000 new URLs each, with the fill level after each round:

# on s1
cd ~/sd/tag09
cat > voll.js <<'EOF'
import http from "k6/http";
import { check } from "k6";
const ZIEL = __ENV.ZIEL || "http://localhost";
export const options = {
  scenarios: { voll: { executor: "constant-arrival-rate", rate: 50, timeUnit: "1s",
    duration: "20s", preAllocatedVUs: 20, maxVUs: 100 } },
};
// Nur neue Adressen, damit jede Anfrage einen neuen Code braucht
export default function () {
  const url = `https://example.org/klein/${__ENV.RUNDE}-${__VU}-${__ITER}`;
  const r = http.post(`${ZIEL}/api/links`, JSON.stringify({ url }),
    { headers: { "Content-Type": "application/json" } });
  check(r, { "201": (x) => x.status === 201 });
}
EOF
for runde in 1 2 3 4; do
  k6 run -q -e RUNDE=$runde voll.js | grep checks_failed
  psql -h s3 -U kurz -d kurz -tAc "select count(*) || ' von 3249 Codes belegt' from links where length(code) = 2"
done

Expected:

    checks_failed......: 0.70%  7 out of 1000
994 von 3249 Codes belegt
    checks_failed......: 9.19%  92 out of 1001
1903 von 3249 Codes belegt
    checks_failed......: 36.00% 360 out of 1000
2543 von 3249 Codes belegt
    checks_failed......: 64.73% 648 out of 1001
2896 von 3249 Codes belegt

At a fill level p, one attempt fails with probability p, all three attempts with p³. In round 3, the fill level rises from 59 to 78%, so p³ rises from 0.2 to 0.48. Measured: 36% kein freier Code (“no free code”). The errors don’t come slowly but with the third power. Anyone who rolls dice therefore needs a space that stays almost empty permanently.

Back to seven characters; the test links go away:

# on s1
for s in s1 s2; do
  ssh $s "sudo rm /etc/systemd/system/kurz.service.d/code.conf && sudo systemctl daemon-reload"
  echo "set server kurz/$s state drain" | sudo nc -U /run/haproxy/admin.sock >/dev/null; sleep 2
  ssh $s "sudo systemctl restart kurz"
  until curl -sf http://$s:8080/readyz >/dev/null; do sleep 0.5; done
  echo "set server kurz/$s state ready" | sudo nc -U /run/haproxy/admin.sock >/dev/null
done
psql -h s3 -U kurz -d kurz -c "delete from links where length(code) = 2"
curl -s -X POST localhost/api/links -d '{"url":"https://example.org/wieder-sieben"}'; echo

Expected:

DELETE 2896
{"code":"jbU2nhk","url":"https://example.org/wieder-sieben"}

Rolling dice is not the only option:

Method Length Coordination Catch
Random + retry (kurz) 7 none, the database checks space must stay almost empty
Counter (sequence) + Base57 1–6 one central sequence codes are guessable; whoever counts knows all links
Ranges from the counter (Hi/Lo) 1–6 one access per block, e.g. 1000 codes gaps after restarts, still guessable
Snowflake (time + instance + counter) 11 each instance needs its own number long, clocks must be right
UUIDv7 (uuidv7() since PostgreSQL 18) 22–36 none far too long for a short link

For a URL shortener, random codes from a large space are the simplest choice. For tables with many writes, time-ordered IDs like UUIDv7 are better, because new rows end up next to each other in the index instead of scattered.

Save your progress? Sign up for free

Drill 3: A Second Shard

On s2, the replica runs on port 5432. A second cluster on port 5433 becomes the second shard:

# on s1
ssh s2 "sudo pg_createcluster 18 shard2 --port 5433 --start -- --auth-local=peer" >/dev/null 2>&1
ssh s2 "sudo -u postgres psql -p 5433 -c \"ALTER SYSTEM SET listen_addresses = '*'\" \
  -c \"CREATE ROLE kurz LOGIN PASSWORD 'lab-kurz-123'\" -c 'CREATE DATABASE kurz OWNER kurz'"
ssh s2 "echo 'host  kurz  kurz  172.16.0.0/24  scram-sha-256' | sudo tee -a /etc/postgresql/18/shard2/pg_hba.conf"
ssh s2 "sudo systemctl restart postgresql@18-shard2 && pg_lsclusters"
psql -h s2 -p 5433 -U kurz -d kurz -tAc "select inet_server_port(), pg_is_in_recovery()"

Expected:

ALTER SYSTEM
CREATE ROLE
CREATE DATABASE
host  kurz  kurz  172.16.0.0/24  scram-sha-256
Ver Cluster Port Status Owner    Data directory                Log file
18  main    5432 online postgres /var/lib/postgresql/18/main   /var/log/postgresql/postgresql-18-main.log
18  shard2  5433 online postgres /var/lib/postgresql/18/shard2 /var/log/postgresql/postgresql-18-shard2.log
5433|f

f means: not a replica, writes are allowed here. kurz creates the table at startup only on db, so the new shard gets it by hand, including the index on the URL:

# on s1
psql -h s2 -p 5433 -U kurz -d kurz -c "CREATE TABLE links (
  code text PRIMARY KEY, url text NOT NULL, angelegt timestamptz NOT NULL DEFAULT now())" \
  -c "CREATE INDEX links_url_idx ON links (url)"

Expected:

CREATE TABLE
CREATE INDEX

In real environments, each shard runs on its own hardware. Here, the replica and the shard share the two CPUs of s2. That is enough for the mechanics, but not for load measurements.

Save your progress? Sign up for free

Drill 4: The Shard Function

A link’s shard should be computable from its code: in Go when kurz writes or reads, and in SQL when you migrate data. CRC32 is in Go’s standard library and, since PostgreSQL 18, available as an SQL function. Both must return the same:

# on s1
psql -h s3 -U kurz -d kurz -tAc "select crc32('abc'::bytea)"
echo -n abc | python3 -c "import zlib,sys;print(zlib.crc32(sys.stdin.buffer.read()))"

Expected:

891568578
891568578

Python uses the same checksum as Go’s crc32.ChecksumIEEE. How does crc32 % 2 distribute the existing links?

# on s1
psql -h s3 -U kurz -d kurz -c "select crc32(code::bytea) % 2 as shard, count(*) from links group by 1 order by 1"

Expected:

 shard |  count
-------+---------
     0 | 1115127
     1 | 1114415
(2 rows)

Almost exactly half and half, because the codes are random. With sequential codes and a split by ranges (aaa–mzz on shard 0, the rest on shard 1), all new links would land on the same shard. A hash distributes evenly but makes range queries across multiple shards necessary.

Save your progress? Sign up for free

Drill 5: kurz Distributes the Links

Before anything changes, the baseline for creating links:

# on s1
cd ~/sd/tag09 && cp ../tag08/anlegen.js ../tag08/codes.txt ../tag08/sofort.js .
k6 run -q -e RATE=200 anlegen.js | grep -E "checks_failed|http_req_duration|http_reqs"

Expected:

    checks_failed......: 0.00%   0 out of 6001
    http_req_duration..............: avg=5.13ms min=1.63ms med=4.53ms max=175.81ms p(90)=7.53ms p(95)=9.02ms
    http_reqs......................: 6001   199.996749/s

The shard code goes into its own file. shards[0] is the existing database; KURZ_SHARDS names further ones:

# on s1
cd ~/kurz && cp main.go /tmp/main.go.alt && cp cache.go /tmp/cache.go.alt
cat > shards.go <<'EOF'
package main

import (
    "context"
    "errors"
    "hash/crc32"
    "log"
    "strings"

    "github.com/jackc/pgx/v5"
    "github.com/jackc/pgx/v5/pgxpool"
)

// shards[0] ist db. KURZ_SHARDS nennt weitere Datenbanken, durch Leerzeichen getrennt.
var shards []*pgxpool.Pool

func initShards() {
    shards = []*pgxpool.Pool{db}
    for _, dsn := range strings.Fields(env("KURZ_SHARDS", "")) {
        p, err := pgxpool.New(context.Background(), dsn)
        if err != nil {
            log.Fatal(err)
        }
        shards = append(shards, p)
    }
    log.Printf("%s: %d Shard(s)", instanz, len(shards))
}

// shardFuer: Welcher Shard einen Link hält, entscheidet allein sein Code.
// Dieselbe Rechnung in SQL: crc32(code::bytea) % Anzahl der Shards.
func shardFuer(code string) int {
    return int(crc32.ChecksumIEEE([]byte(code)) % uint32(len(shards)))
}

// sucheURL fragt jeden Shard nach der Adresse. Sie ist nicht der Shard-Schlüssel,
// also kann sie auf jedem Shard liegen.
func sucheURL(ctx context.Context, url string) (string, error) {
    var code string
    for _, s := range shards {
        err := s.QueryRow(ctx, "SELECT code FROM links WHERE url = $1 LIMIT 1", url).Scan(&code)
        if !errors.Is(err, pgx.ErrNoRows) {
            return code, err
        }
    }
    return "", pgx.ErrNoRows
}
EOF

Three small changes in main.go and one in cache.go: the check for an existing URL asks all shards, the insert goes to the code’s shard, and finde reads codes from shard 1 and higher directly there. For shard 0, everything stays as on Day 8, with the replica and the fallback:

# on s1
perl -0pi -e 's/\tvar vorhanden string\n\terr = db.QueryRow\(r.Context\(\),\n\t\t"SELECT code FROM links WHERE url = \$1 LIMIT 1", in.URL\).Scan\(&vorhanden\)\n/\tvorhanden, err := sucheURL(r.Context(), in.URL)\n/' main.go
perl -0pi -e 's/_, err := db.Exec\(r.Context\(\),/_, err := shards[shardFuer(code)].Exec(r.Context(),/' main.go
perl -0pi -e 's/(\tmux := http.NewServeMux\(\)\n)/\tinitShards()\n$1/' main.go
perl -0pi -e 's/(\t\tvar ziel string\n)/$1\t\tif i := shardFuer(code); i > 0 {\n\t\t\terr := shards[i].QueryRow(ctx, "SELECT url FROM links WHERE code = \$1", code).Scan(&ziel)\n\t\t\treturn ziel, err\n\t\t}\n/' cache.go
diff /tmp/main.go.alt main.go; diff /tmp/cache.go.alt cache.go
go vet . && go build -o kurz . && echo gebaut

Expected:

62,64c62
<   var vorhanden string
<   err = db.QueryRow(r.Context(),
<       "SELECT code FROM links WHERE url = $1 LIMIT 1", in.URL).Scan(&vorhanden)
---
>   vorhanden, err := sucheURL(r.Context(), in.URL)
72c70
<       _, err := db.Exec(r.Context(),
---
>       _, err := shards[shardFuer(code)].Exec(r.Context(),
133a132
>   initShards()
56a57,60
>       if i := shardFuer(code); i > 0 {
>           err := shards[i].QueryRow(ctx, "SELECT url FROM links WHERE code = $1", code).Scan(&ziel)
>           return ziel, err
>       }
gebaut

The primary key stays unique even though each shard checks only its own codes: a code can only ever land on a single shard. That is the advantage when the shard key is also the ID.

Drop-in with the second shard, then roll out:

# on s1
for s in s1 s2; do
  ssh $s "printf '[Service]\nEnvironment=\"KURZ_SHARDS=postgres://kurz:lab-kurz-123@s2:5433/kurz?pool_max_conns=16\"\n' \
    | sudo tee /etc/systemd/system/kurz.service.d/shards.conf >/dev/null && sudo systemctl daemon-reload"
done
for s in s1 s2; do
  echo "set server kurz/$s state drain" | sudo nc -U /run/haproxy/admin.sock >/dev/null; sleep 2
  scp -q kurz $s:/tmp/kurz
  ssh $s "sudo install /tmp/kurz /usr/local/bin/kurz && sudo systemctl restart kurz"
  until curl -sf http://$s:8080/readyz >/dev/null; do sleep 0.5; done
  echo "set server kurz/$s state ready" | sudo nc -U /run/haproxy/admin.sock >/dev/null
done
ssh s2 "journalctl -u kurz --since '-1min' -o cat | grep Shard"

Expected:

2026/11/23 10:28:04 s2: 2 Shard(s)

Create new links and call them immediately with sofort.js from Day 8, then count where they ended up:

# on s1
cd ~/sd/tag09
k6 run -q sofort.js | grep -E "checks_failed"
psql -h s3 -U kurz -d kurz -tAc "select 's3: ' || count(*) from links
  where url like 'https://example.org/sofort/%' and angelegt > now() - interval '2 min'"
psql -h s2 -p 5433 -U kurz -d kurz -tAc "select 's2:5433: ' || count(*) from links"

Expected:

    checks_failed......: 0.00%   0 out of 2002
s3: 517
s2:5433: 484

Every new link is found, and the 1001 links split roughly half and half across the two shards.

Save your progress? Sign up for free

Drill 6: The Old Links

And the 2.2 million links from before? codes.txt contains 1000 of them:

# on s1
cat > alt.js <<'EOF'
import http from "k6/http";
import { check } from "k6";
import { SharedArray } from "k6/data";
const ZIEL = __ENV.ZIEL || "http://localhost";
const codes = new SharedArray("codes", () => open("codes.txt").split("\n").filter(Boolean));
export const options = {
  scenarios: { alt: { executor: "constant-arrival-rate", rate: 200, timeUnit: "1s",
    duration: "20s", preAllocatedVUs: 20, maxVUs: 100 } },
};
// 1000 Links, die es schon vor dem Sharding gab
export default function () {
  const r = http.get(`${ZIEL}/${codes[__ITER % codes.length]}`, { redirects: 0 });
  check(r, { "302": (x) => x.status === 302 });
}
EOF
k6 run -q alt.js | grep checks_failed
psql -h s3 -U kurz -d kurz -tAc "select count(*) || ' der 1000 Codes gehören auf Shard 1' from links
  where code in ($(sed "s/.*/'&'/" codes.txt | paste -sd,)) and crc32(code::bytea) % 2 = 1"

Expected:

    checks_failed......: 47.48% 1900 out of 4001
474 der 1000 Codes gehören auf Shard 1

Almost half of the old links are broken. kurz looks for them on shard 1, but they are still on s3. The error rate matches the fraction of codes whose hash points to shard 1. So sharding also means: migrating data. Copy first, then delete on s3, so that no link goes missing in between:

# on s1
time psql -h s3 -U kurz -d kurz -c "\copy (select code, url, angelegt from links where crc32(code::bytea) % 2 = 1) to stdout" \
  | psql -h s2 -p 5433 -U kurz -d kurz -c "\copy links from stdin"
k6 run -q alt.js | grep checks_failed

Expected:

COPY 1115954

real    0m28.648s
    checks_failed......: 0.00%   0 out of 4001

There are no conflicts: the 484 new links on shard 1 have new codes that were never on s3. Now delete the copied rows on s3 and check whether every row is on the right shard:

# on s1
time psql -h s3 -U kurz -d kurz -c "delete from links where crc32(code::bytea) % 2 = 1"
psql -h s3 -U kurz -d kurz -tAc "select 's3:      ' || count(*) from links"
psql -h s2 -p 5433 -U kurz -d kurz -tAc "select 's2:5433: ' || count(*) from links"
psql -h s3 -U kurz -d kurz -tAc "select 'falsch auf s3: ' || count(*) from links where crc32(code::bytea) % 2 = 1"
psql -h s2 -p 5433 -U kurz -d kurz -tAc "select 'falsch auf s2: ' || count(*) from links where crc32(code::bytea) % 2 = 0"

Expected:

DELETE 1115954

real    0m4.668s
s3:      1117142
s2:5433: 1116438
falsch auf s3: 0
falsch auf s2: 0

28 seconds for 1.1 million rows over the lab network. With a billion rows it would be seven hours, and during that time the application keeps writing. That’s why you plan sharding before the database is full, not after. The delete leaves dead rows on s3, which autovacuum cleans up later. The replica on s2:5432 replays the delete as well.

Save your progress? Sign up for free

Drill 7: What Sharding Costs

The same measurement as at the start of Drill 5:

# on s1
k6 run -q -e RATE=200 anlegen.js | grep -E "checks_failed|http_req_duration|http_reqs"

Expected:

    checks_failed......: 0.00%   0 out of 6001
    http_req_duration..............: avg=5.87ms min=1.87ms med=5.47ms max=67.98ms p(90)=9.03ms p(95)=10.47ms
    http_reqs......................: 6001   199.996669/s

p95 rises from 9.0 to 10.5 ms. Every new URL now asks both shards whether it already exists, because the URL is not the shard key. With ten shards, that would be ten queries. Such a query to all shards is called scatter-gather, and its latency is determined by the slowest shard.

The second bill comes when a third shard is added. With crc32 % 3 instead of % 2, many codes change shards. The alternative is fixed slots: crc32 % 64 gives one of 64 slots, and a table says which shard holds which slot. For a third shard, you hand it 21 slots. How many rows would have to move in each case?

# on s1
for ziel in "-h s3" "-h s2 -p 5433"; do
  psql $ziel -U kurz -d kurz -tA -F' | ' -c "select inet_server_port(), count(*) as links,
    count(*) filter (where crc32(code::bytea) % 3 <> crc32(code::bytea) % 2) as umzug_modulo,
    count(*) filter (where crc32(code::bytea) % 64 < 21) as umzug_slots
  from links"
done

Expected:

5432 | 1118634 | 746525 | 383771
5433 | 1117926 | 745545 | 349111

With modulo, 1,492,070 of 2,236,560 rows move, two thirds of all data. With slots it is 732,882, one third, and that is the minimum: after all, the new shard is supposed to hold a third. With modulo, by contrast, rows also move between the two old shards. Valkey Cluster works with 16,384 such slots; Cassandra and DynamoDB use consistent hashing on the same principle.

Save your progress? Sign up for free

Exercise: Speed drills

  1. Calculate in SQL which of the two shards the code MPKfz5D is on. Target time: 1 min
  2. Count the links on both shards. Target time: 1 min
  3. Show the PostgreSQL clusters on s2. Target time: 30 s

Solution

# on s1
psql -h s3 -U kurz -d kurz -tAc "select crc32('MPKfz5D'::bytea) % 2"
for ziel in "-h s3" "-h s2 -p 5433"; do psql $ziel -U kurz -d kurz -tAc "select count(*) from links"; done
ssh s2 pg_lsclusters

Expected:

0
1119747
1118186
Ver Cluster Port Status Owner    Data directory                Log file
18  main    5432 online postgres /var/lib/postgresql/18/main   /var/log/postgresql/postgresql-18-main.log
18  shard2  5433 online postgres /var/lib/postgresql/18/shard2 /var/log/postgresql/postgresql-18-shard2.log

Save your progress? Sign up for free

Checkpoint

# on s1
ssh s2 systemctl show kurz -p Environment | grep -o 's2:5433[^ "]*'

Expected: s2:5433/kurz?pool_max_conns=16

# on s1
psql -h s3 -U kurz -d kurz -tAc "select count(*) from links where crc32(code::bytea) % 2 = 1"

Expected: 0

# on s1
curl -s -o /dev/null -w '%{http_code}\n' localhost/MPKfz5D

Expected: 302

Challenge

Shard 2 fails. What do users notice when redirecting, when creating, and when creating a URL that already exists? Guess first, then measure with alt.js, sofort.js and anlegen.js. Afterwards, check whether the outage left traces in the data.

Hint: Think of the cache from Day 5 and of sucheURL.

Solution

# on s1
ssh s2 "sudo systemctl stop postgresql@18-shard2"
k6 run -q alt.js | grep checks_failed
k6 run -q sofort.js | grep -E "checks_failed|↳"
k6 run -q -e RATE=100 -e DAUER=10s anlegen.js | grep -E "checks_failed"
ssh s2 "sudo systemctl start postgresql@18-shard2"
sleep 2
k6 run -q -e RATE=100 -e DAUER=10s anlegen.js | grep -E "checks_failed"

Expected:

    checks_failed......: 0.00%   0 out of 4000
    checks_failed......: 32.80% 494 out of 1506
      ↳  50% — ✓ 506 / ✗ 494
    checks_failed......: 41.75% 418 out of 1001
    checks_failed......: 0.00%   0 out of 1001
  • Redirecting: no errors. alt.js had only just fetched the 1000 old codes, so they are all in Valkey. The cache hides the outage until the entries expire. Monitoring that only looks at error rates for redirects sees nothing for ten minutes.
  • New links: half fail, namely all whose rolled code points to shard 1. The 506 successful ones were also found afterwards.
  • Existing URLs: sucheURL gets a connection error from shard 1 instead of “not there”. anlegen treats every error during the search as if the URL didn’t exist and creates a new link. If the URL actually lives on shard 1, a duplicate is created:
# on s1
psql -h s2 -p 5433 -U kurz -d kurz -c "\copy (select url from links where url like 'https://example.org/artikel/%') to stdout" \
  | psql -h s3 -U kurz -d kurz -c "create temp table drueben (url text)" -c "\copy drueben from stdin" \
    -c "select date_trunc('minute', l.angelegt) as minute, count(*) from links l join drueben using (url) group by 1 order by 1"

Expected (your time will differ):

CREATE TABLE
COPY 995630
         minute         | count
------------------------+-------
 2026-11-23 10:32:00+00 |   118
(1 row)

118 URLs now exist twice, all from the minute of the outage. No user saw an error, but the rule “one URL, one code” is broken. The cause has been in the code since Day 1: the check doesn’t distinguish between “not found” and “couldn’t check”. With one database this went unnoticed, because the insert then failed as well. The duplicates stay in the lab; they don’t interfere with the following days.

Save your progress? Sign up for free

Clean-up

From Day 10 on, the lab works with one database again. First switch the instances over, then bring the rows back. In between, half of the old links are missing for about half a minute, which is fine in the lab:

# on s1
for s in s1 s2; do
  ssh $s "sudo rm /etc/systemd/system/kurz.service.d/shards.conf && sudo systemctl daemon-reload"
  echo "set server kurz/$s state drain" | sudo nc -U /run/haproxy/admin.sock >/dev/null; sleep 2
  ssh $s "sudo systemctl restart kurz"
  until curl -sf http://$s:8080/readyz >/dev/null; do sleep 0.5; done
  echo "set server kurz/$s state ready" | sudo nc -U /run/haproxy/admin.sock >/dev/null
done
psql -h s2 -p 5433 -U kurz -d kurz -c "\copy links to stdout" | psql -h s3 -U kurz -d kurz -c "\copy links from stdin"
psql -h s3 -U kurz -d kurz -tAc "select count(*) from links"
ssh s2 "sudo pg_dropcluster 18 shard2 --stop && pg_lsclusters"
ssh s2 "journalctl -u kurz --since '-2min' -o cat | grep Shard"
cd ~/sd/tag09 && k6 run -q alt.js | grep checks_failed

Expected:

COPY 1118186
2237933
Ver Cluster Port Status Owner    Data directory              Log file
18  main    5432 online postgres /var/lib/postgresql/18/main /var/log/postgresql/postgresql-18-main.log
2026/11/23 10:34:22 s2: 1 Shard(s)
    checks_failed......: 0.00%   0 out of 4000

The code in shards.go stays. Without KURZ_SHARDS there is exactly one shard, and shardFuer always returns 0. The configurable code length stays too; without the drop-in it is seven characters.

Interview note

  • How do you generate short, unique IDs? Random values from a large space, checked by a unique index, or a counter with Base62 encoding. Do the math: with n links from N codes, a new code collides with probability n/N; in total there are about n²/2N collisions. Mention that counters are guessable.
  • How do you choose the shard key? By the most frequent query. For a URL shortener, that is “code → URL”, so the code. Everything else (search by URL, statistics per user) becomes more expensive or needs a second index that is itself sharded.
  • What happens when a shard is added? With modulo, most of the data moves; with fixed slots or consistent hashing, only the new shard’s share. Plan sharding before the bottleneck; exhaust caches, replicas and bigger machines first.

Enterprise note

  • The application rarely distributes data itself. For PostgreSQL there is Citus (tables distributed across nodes, queries are forwarded); for MySQL, Vitess. Many teams get further than they think with partitioning within one database (PARTITION BY HASH) and a bigger machine.
  • Resharding in production runs without downtime: dual writes, copy in the background, compare, switch reads, empty the old shard. Tools like Vitess ship this as a workflow. Copying with a gap as in this lab is only acceptable for practice.

Contents

More