Skip to content
System design · Chapter 12 of 21 Day 10: Asynchronous with NATS

Day 10: Asynchronous with NATS

Goal: Count clicks without slowing down the redirect: first synchronously in PostgreSQL, then via NATS with a dedicated worker, then durably with JetStream. You measure what each variant costs and when clicks get lost or counted twice · Duration: approx. 90 min · Prerequisite: Day 9

Briefing

  • So far kurz does everything while the user waits. Today a task is added that the user does not need: every redirect is to be counted. If kurz does that right away, every click waits for a write on s3.
  • The alternative: kurz drops the click off as a message and answers immediately. A separate service picks up the messages and writes them away. That is asynchronous processing. Between the two sits a messaging system, here NATS on s2.
  • Asynchronous means: the number in the database is correct only a little later. It also means: messages can get lost or arrive twice. How often that happens depends on what the messaging system stores and when the worker acknowledges.
Term Meaning
Subject address of a message in NATS, here klicks
Core NATS delivers only to subscribers connected right now, stores nothing
JetStream NATS with storage: a stream holds on to messages, a consumer remembers what has been read
Ack acknowledgment from the worker: this message is done
At-least-once every message arrives at least once, sometimes more often
Backlog (lag) messages that are already there but not yet processed

NATS has been running on s2 since Day 0 (user kurz, password lab-nats-123). By the end of the day kurz counts all clicks via JetStream, and the worker zaehler runs permanently on s2.

Drill 1: NATS by Hand

The nats CLI is on s1. A context saves you the address and password on every call:

# on s1
mkdir -p ~/sd/tag10 && cd ~/sd/tag10
nats context add lab --server nats://s2:4222 --user kurz --password lab-nats-123 --select
nats server check connection

Expected (abridged):

NATS Configuration Context "lab"

  Server URLs: nats://s2:4222
     Username: kurz
     Password: ************
         Path: /home/ubuntu/.config/nats/context/lab.json
   Connection: OK

OK Connection OK:connected to nats://s2:4222 in 9.982142ms OK:rtt time 1.519131ms ...

A subscriber in the background, three messages, then the subscriber’s output:

# on s1
nats sub klicks --count 3 > sub.log 2>&1 &
sleep 1
nats pub klicks "aB3xYz9"; nats pub klicks "Qw7Er5t"; nats pub klicks "aB3xYz9"
wait; cat sub.log

Expected (abridged):

12:34:35 Published 7 bytes to "klicks"
12:34:35 Published 7 bytes to "klicks"
12:34:35 Published 7 bytes to "klicks"
12:34:34 Subscribing on klicks
[#1] Received on "klicks"
aB3xYz9

[#2] Received on "klicks"
Qw7Er5t

[#3] Received on "klicks"
aB3xYz9

Now the other way round: publish first, then subscribe.

# on s1
nats pub klicks "verloren?"
timeout 3 nats sub klicks; echo "rc=$?"

Expected:

12:34:40 Published 9 bytes to "klicks"
12:36:51 Subscribing on klicks
rc=124

The message never arrives. Core NATS delivers only to subscribers connected at that moment and stores nothing. That is not a bug, but the reason NATS is so fast:

# on s1
nats bench pub bench.klicks --msgs 1000000 --size 7 --no-progress 2>&1 | tail -1

Expected:

NATS Core NATS publisher stats: 1,064,029 msgs/sec ~ 7.1 MiB/sec ~ min: 0.13us ~ avg: 0.64us ~ max: 4,455.73us ~ P50: 0.36us ~ P90: 0.60us ~ P99: 1.13us ~ P99.9: 65.95us

Just over a million messages per second from a single client, a median of 0.36 microseconds per message. Publishing costs kurz practically nothing.

Save your progress? Sign up for free

Drill 2: Counting Clicks Synchronously

First the baseline. klick.js only requests redirects, popular links much more often than rare ones, like schief.js from Day 5:

# on s1
cd ~/sd/tag10 && cp ~/sd/tag08/codes.txt .
cat > klick.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";

export const options = {
  scenarios: {
    klicks: {
      executor: "constant-arrival-rate",
      rate: Number(__ENV.RATE || 1500), timeUnit: "1s",
      duration: __ENV.DAUER || "30s",
      preAllocatedVUs: 50, maxVUs: 500,
    },
  },
};

// nur Weiterleitungen, beliebte Links viel häufiger als seltene
export default function () {
  const code = codes[Math.floor(Math.pow(Math.random(), 3) * codes.length)];
  const r = http.get(`${ZIEL}/${code}`, { redirects: 0 });
  check(r, { "302": (x) => x.status === 302 });
}
EOF
export PGPASSWORD=lab-kurz-123
tx() { psql -h s3 -U kurz -d kurz -tAc "select xact_commit from pg_stat_database where datname = 'kurz'"; }
a=$(tx)
k6 run -q klick.js | grep -E 'http_req_failed\.|http_req_duration\.'
echo "s3 Tx/s: $(( ($(tx) - a) / 30 ))"

Expected:

    http_req_duration..............: avg=5.23ms min=828.58µs med=3.35ms max=76.19ms  p(90)=10.68ms p(95)=15.82ms
    http_req_failed................: 0.00%  0 out of 44925
s3 Tx/s: 0

Not a single access to s3: all 1000 codes are in Valkey. Now the table for counting and the simplest solution, one upsert per redirect:

# on s1
psql -h s3 -U kurz -d kurz -c "CREATE TABLE klicks (code text PRIMARY KEY, anzahl bigint NOT NULL)"
cd ~/kurz && cp main.go /tmp/main.go.alt
cat > klicks.go <<'EOF'
package main

import (
    "context"
    "log"
)

// KURZ_KLICKS legt fest, wie kurz Weiterleitungen zählt:
// leer = gar nicht, "sync" = jede Weiterleitung schreibt sofort in PostgreSQL.
var klicksModus = env("KURZ_KLICKS", "")

// zaehle wird bei jeder Weiterleitung aufgerufen, bevor die Antwort rausgeht.
func zaehle(ctx context.Context, code string) {
    if klicksModus != "sync" {
        return
    }
    _, err := db.Exec(ctx, `INSERT INTO klicks (code, anzahl) VALUES ($1, 1)
        ON CONFLICT (code) DO UPDATE SET anzahl = klicks.anzahl + 1`, code)
    if err != nil {
        log.Printf("zaehle: %v", err) // ein verlorener Klick, die Weiterleitung klappt trotzdem
    }
}
EOF
perl -0pi -e 's/(\thttp.Redirect\(w, r, ziel, http.StatusFound\))/\tzaehle(r.Context(), r.PathValue("code"))\n$1/' main.go
diff /tmp/main.go.alt main.go
go vet . && go build -o kurz . && echo gebaut

Expected:

CREATE TABLE
99a100
>   zaehle(r.Context(), r.PathValue("code"))
gebaut

An error while counting must not break the redirect. That is why zaehle only logs it. Roll out with the drop-in klicks.conf, as on Day 9:

# on s1
for s in s1 s2; do
  ssh $s "printf '[Service]\nEnvironment=KURZ_KLICKS=sync\n' \
    | sudo tee /etc/systemd/system/kurz.service.d/klicks.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
cd ~/sd/tag10
a=$(tx)
k6 run -q klick.js | grep -E 'http_req_failed\.|http_req_duration\.|checks_succeeded'
echo "s3 Tx/s: $(( ($(tx) - a) / 30 ))"
psql -h s3 -U kurz -d kurz -c "select sum(anzahl) as klicks, count(*) as links, max(anzahl) as beliebtester from klicks"

Expected:

    checks_succeeded...: 100.00% 44356 out of 44356
    http_req_duration..............: avg=37.85ms min=2.4ms  med=25.49ms max=594.2ms  p(90)=84.92ms p(95)=110.31ms
    http_req_failed................: 0.00%  0 out of 44356
s3 Tx/s: 1458
 klicks | links | beliebtester
--------+-------+--------------
  44356 |  1000 |         4492
(1 row)

The count is exact to the click. In return, the median has risen from 3.4 to 25 ms, the p95 from 16 to 110 ms. The cache from Day 5 has become worthless, because every click writes to s3 again, with one commit per click. A look during the load shows where it gets stuck:

# on s1
k6 run -q klick.js > sync.log 2>&1 &
sleep 15
psql -h s3 -p 6432 -U kurz -d pgbouncer -tAc "show pools" | grep "^kurz|kurz"
ssh s3 "top -bn1 | head -3 | tail -1"
wait

Expected (values fluctuate):

kurz|kurz|27|5|0|0|20|0|0|0|0|0|0|0|9690|transaction|
%Cpu(s): 37.5 us, 41.7 sy,  0.0 ni,  8.3 id,  0.0 wa,  0.0 hi,  8.3 si,  4.2 st

All 20 server connections of PgBouncer are in use, 5 clients are waiting (fourth field), the oldest for 9.7 ms (second-to-last number, in microseconds). s3 is at 92% utilization. A side matter, the statistics, slows down the main matter, the redirect.

Save your progress? Sign up for free

Drill 3: Clicks as Messages

kurz should only publish the click. That needs the NATS library and a new version of klicks.go:

# on s1
cd ~/kurz && cp main.go /tmp/main.go.alt
go get github.com/nats-io/[email protected]
cat > klicks.go <<'EOF'
package main

import (
    "context"
    "log"
    "strings"

    "github.com/nats-io/nats.go"
)

// KURZ_KLICKS legt fest, wie kurz Weiterleitungen zählt: leer = gar nicht,
// "sync" = jede Weiterleitung schreibt sofort in PostgreSQL,
// "nats://…" = jede Weiterleitung veröffentlicht eine Nachricht, ein Worker zählt.
var (
    klicksModus = env("KURZ_KLICKS", "")
    nc          *nats.Conn
)

func initKlicks() {
    if !strings.HasPrefix(klicksModus, "nats://") {
        return
    }
    var err error
    nc, err = nats.Connect(klicksModus, nats.Name(instanz),
        nats.RetryOnFailedConnect(true), // kurz startet auch, wenn NATS gerade fehlt
        nats.MaxReconnects(-1))          // und gibt das Wiederverbinden nie auf
    if err != nil {
        log.Fatalf("nats: %v", err)
    }
    log.Printf("%s: Klicks über NATS %s", instanz, nc.ConnectedUrlRedacted())
}

// zaehle wird bei jeder Weiterleitung aufgerufen, bevor die Antwort rausgeht.
func zaehle(ctx context.Context, code string) {
    var err error
    switch {
    case klicksModus == "sync":
        _, err = db.Exec(ctx, `INSERT INTO klicks (code, anzahl) VALUES ($1, 1)
            ON CONFLICT (code) DO UPDATE SET anzahl = klicks.anzahl + 1`, code)
    case nc != nil:
        err = nc.Publish("klicks", []byte(code)) // wartet auf niemanden
    }
    if err != nil {
        log.Printf("zaehle: %v", err) // ein verlorener Klick, die Weiterleitung klappt trotzdem
    }
}
EOF
perl -0pi -e 's/(\tinitCache\(\)\n)/$1\tinitKlicks()\n/' main.go
diff /tmp/main.go.alt main.go
go mod tidy && go vet . && go build -o kurz . && grep nats go.mod

Expected:

145a146
>   initKlicks()
    github.com/nats-io/nats.go v1.56.0
    github.com/nats-io/nkeys v0.4.16 // indirect
    github.com/nats-io/nuid v1.0.1 // indirect

Two options matter. Without RetryOnFailedConnect, kurz would not start at all if NATS is missing, and a side matter would cripple the redirect. Without MaxReconnects(-1), the client gives up after 60 attempts, so with two seconds between them after about two minutes, and every further click would be lost silently.

Now the worker. It is a small program of its own with its own module. Version 1 subscribes to klicks and writes each message away individually:

# on s1
mkdir -p ~/zaehler && cd ~/zaehler
go mod init zaehler
go get github.com/jackc/pgx/[email protected] github.com/nats-io/[email protected]
cat > main.go <<'EOF'
// zaehler: liest Klicks aus NATS und zählt sie in PostgreSQL. Version 1: Core NATS.
package main

import (
    "context"
    "log"
    "os"
    "sync/atomic"
    "time"

    "github.com/jackc/pgx/v5/pgxpool"
    "github.com/nats-io/nats.go"
)

func env(key, def string) string {
    if v := os.Getenv(key); v != "" {
        return v
    }
    return def
}

const upsert = `INSERT INTO klicks (code, anzahl) VALUES ($1, 1)
    ON CONFLICT (code) DO UPDATE SET anzahl = klicks.anzahl + 1`

func main() {
    ctx := context.Background()
    db, err := pgxpool.New(ctx, env("ZAEHLER_DB", "postgres://kurz:lab-kurz-123@s3:6432/kurz"))
    if err != nil {
        log.Fatal(err)
    }
    nc, err := nats.Connect(env("ZAEHLER_NATS", "nats://kurz:lab-nats-123@s2:4222"),
        nats.Name("zaehler"), nats.MaxReconnects(-1))
    if err != nil {
        log.Fatal(err)
    }
    var gezaehlt atomic.Int64
    sub, err := nc.Subscribe("klicks", func(m *nats.Msg) {
        if _, err := db.Exec(ctx, upsert, string(m.Data)); err != nil {
            log.Printf("zählen: %v", err)
            return
        }
        gezaehlt.Add(1)
    })
    if err != nil {
        log.Fatal(err)
    }
    for range time.Tick(5 * time.Second) {
        verloren, _ := sub.Dropped()
        log.Printf("gezählt %d, verworfen %d", gezaehlt.Load(), verloren)
    }
}
EOF
go mod tidy && go vet . && go build -o zaehler . && echo gebaut

Expected (abridged):

go: creating new go.mod: module zaehler
go: added github.com/jackc/pgx/v5 v5.13.0
go: added github.com/nats-io/nats.go v1.56.0
gebaut

The worker runs on s2, next to NATS, as its own systemd service:

# on s1
scp -q zaehler s2:/tmp/zaehler
ssh s2 "sudo install /tmp/zaehler /usr/local/bin/zaehler"
ssh s2 "sudo tee /etc/systemd/system/zaehler.service >/dev/null" <<'EOF'
[Unit]
Description=zaehler: Klicks aus NATS nach PostgreSQL
After=network-online.target nats.service
[Service]
DynamicUser=yes
ExecStart=/usr/local/bin/zaehler
Restart=on-failure
[Install]
WantedBy=multi-user.target
EOF
ssh s2 "sudo systemctl daemon-reload && sudo systemctl enable --now zaehler && sleep 6 && journalctl -u zaehler -o cat -n 1"

Expected:

Created symlink /etc/systemd/system/multi-user.target.wants/zaehler.service → /etc/systemd/system/zaehler.service.
2026/11/23 12:42:48 gezählt 0, verworfen 0

Roll out kurz with the NATS address, empty the count and measure:

# on s1
cd ~/kurz
for s in s1 s2; do
  ssh $s "printf '[Service]\nEnvironment=KURZ_KLICKS=nats://kurz:lab-nats-123@s2:4222\n' \
    | sudo tee /etc/systemd/system/kurz.service.d/klicks.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 NATS"
cd ~/sd/tag10
psql -h s3 -U kurz -d kurz -c "TRUNCATE klicks"
a=$(tx)
k6 run -q klick.js | grep -E 'http_req_failed\.|http_req_duration\.|checks_succeeded'
echo "s3 Tx/s: $(( ($(tx) - a) / 30 ))"
sleep 5
psql -h s3 -U kurz -d kurz -tAc "select 'gezählt: ' || sum(anzahl) from klicks"

Expected:

2026/11/23 12:43:13 s2: Klicks über NATS nats://kurz:xxxxx@s2:4222
TRUNCATE TABLE
    checks_succeeded...: 100.00% 44844 out of 44844
    http_req_duration..............: avg=7.27ms min=819.56µs med=4.97ms max=215.13ms p(90)=14.47ms p(95)=20.48ms
    http_req_failed................: 0.00%  0 out of 44844
s3 Tx/s: 294
gezählt: 11399

The redirect is almost as fast again as without counting (p95 20 instead of 110 ms). But after the load only 11,399 of 44,844 clicks are counted. The worker manages only about 300 upserts per second: the callback for a subscription always runs sequentially, and each message waits for its own commit. Watch the worker catch up:

# on s1
for i in 1 2 3 4 5 6; do
  psql -h s3 -U kurz -d kurz -tAc "select now()::time(0) || '  gezählt: ' || sum(anzahl) from klicks"; sleep 20
done

Expected:

12:44:00  gezählt: 15426
12:44:21  gezählt: 24540
12:44:41  gezählt: 33363
12:45:01  gezählt: 42288
12:45:21  gezählt: 44844
12:45:41  gezählt: 44844

After just under two minutes the number is correct. The clicks not yet counted sat as a backlog in the worker’s memory in the meantime: Core NATS delivered them long ago. What happens to this backlog when the worker restarts?

# on s1
psql -h s3 -U kurz -d kurz -qc "TRUNCATE klicks"
k6 run -q klick.js | grep -E 'checks_succeeded'
ssh s2 "sudo systemctl restart zaehler"
sleep 60
psql -h s3 -U kurz -d kurz -tAc "select 'gezählt: ' || sum(anzahl) from klicks"

Expected:

    checks_succeeded...: 100.00% 44691 out of 44691
gezählt: 10001

34,690 clicks are gone, without an error message. A perfectly normal deployment of the worker is enough for that.

Save your progress? Sign up for free

Drill 4: A Stream Stores the Clicks

JetStream writes messages to disk before any worker sees them. A stream catches everything that arrives on the subject klicks. kurz does not have to change anything for this:

# on s1
nats stream add KLICKS --subjects klicks --storage file --retention limits --discard old --max-age 24h --defaults \
  | grep -E "Subjects|Storage|Maximum (Messages|Age)"

Expected:

                     Subjects: klicks
                      Storage: File
             Maximum Messages: unlimited
                  Maximum Age: 1d0h0m0s

The old worker is stopped, then load comes in:

# on s1
ssh s2 "sudo systemctl stop zaehler"
psql -h s3 -U kurz -d kurz -qc "TRUNCATE klicks"
k6 run -q klick.js | grep -E 'checks_succeeded'
nats stream info KLICKS --json | jq '.state | {messages, bytes, first_seq, last_seq}'

Expected:

    checks_succeeded...: 100.00% 44947 out of 44947
{
  "messages": 44947,
  "bytes": 1932721,
  "first_seq": 1,
  "last_seq": 44947
}

Every click is in the stream, around 43 bytes per message including headers. No worker is running, and still nothing is missing.

Version 2 of the worker reads from the stream instead of the subject. A durable consumer named zaehler remembers on the server which messages are acknowledged. The worker fetches them in batches (pull consumer), writes each batch with a single statement and acknowledges only after the commit:

# on s1
cd ~/zaehler
cat > main.go <<'EOF'
// zaehler: liest Klicks aus dem JetStream-Stream KLICKS und zählt sie in PostgreSQL.
// Version 2: Pull-Consumer, ein Statement pro Batch, Bestätigung erst nach dem Commit.
package main

import (
    "context"
    "log"
    "os"
    "strconv"
    "time"

    "github.com/jackc/pgx/v5/pgxpool"
    "github.com/nats-io/nats.go"
    "github.com/nats-io/nats.go/jetstream"
)

func env(key, def string) string {
    if v := os.Getenv(key); v != "" {
        return v
    }
    return def
}

// Ein Statement für den ganzen Batch: PostgreSQL zählt die Codes selbst zusammen.
const upsert = `INSERT INTO klicks (code, anzahl)
    SELECT code, count(*) FROM unnest($1::text[]) AS code GROUP BY code
    ON CONFLICT (code) DO UPDATE SET anzahl = klicks.anzahl + excluded.anzahl`

func main() {
    ctx := context.Background()
    batch, _ := strconv.Atoi(env("ZAEHLER_BATCH", "500"))
    pause, _ := time.ParseDuration(env("ZAEHLER_PAUSE", "0s"))
    db, err := pgxpool.New(ctx, env("ZAEHLER_DB", "postgres://kurz:lab-kurz-123@s3:6432/kurz"))
    if err != nil {
        log.Fatal(err)
    }
    nc, err := nats.Connect(env("ZAEHLER_NATS", "nats://kurz:lab-nats-123@s2:4222"),
        nats.Name("zaehler"), nats.MaxReconnects(-1))
    if err != nil {
        log.Fatal(err)
    }
    js, err := jetstream.New(nc)
    if err != nil {
        log.Fatal(err)
    }
    // Durable: Der Server merkt sich, bis wohin "zaehler" gelesen und bestätigt hat.
    cons, err := js.CreateOrUpdateConsumer(ctx, "KLICKS", jetstream.ConsumerConfig{
        Durable:   "zaehler",
        AckPolicy: jetstream.AckExplicitPolicy,
    })
    if err != nil {
        log.Fatal(err)
    }
    log.Printf("zaehler: Batch %d, Pause %s", batch, pause)
    gezaehlt, letzte := 0, time.Now()
    for {
        msgs, err := cons.Fetch(batch, jetstream.FetchMaxWait(time.Second))
        if err != nil {
            log.Printf("fetch: %v", err)
            time.Sleep(time.Second)
            continue
        }
        var codes []string
        var liste []jetstream.Msg
        for m := range msgs.Messages() {
            codes = append(codes, string(m.Data()))
            liste = append(liste, m)
        }
        if len(liste) == 0 {
            continue
        }
        if _, err := db.Exec(ctx, upsert, codes); err != nil {
            log.Printf("zählen: %v", err) // nicht bestätigt: JetStream liefert sie erneut
            continue
        }
        time.Sleep(pause) // nur für Drill 7: eine Lücke zwischen Commit und Bestätigung
        for _, m := range liste {
            m.Ack()
        }
        gezaehlt += len(liste)
        if time.Since(letzte) >= 5*time.Second {
            log.Printf("gezählt %d", gezaehlt)
            letzte = time.Now()
        }
    }
}
EOF
go vet . && go build -o zaehler . && echo gebaut
scp -q zaehler s2:/tmp/zaehler && ssh s2 "sudo install /tmp/zaehler /usr/local/bin/zaehler"

Expected: gebaut (“built”)

First without batches: with ZAEHLER_BATCH=1 the worker fetches each message individually, like version 1. It starts with a backlog of 44,947 clicks, and the loop waits until the consumer has nothing outstanding:

# on s1
cd ~/sd/tag10
ssh s2 "sudo mkdir -p /etc/systemd/system/zaehler.service.d \
  && printf '[Service]\nEnvironment=ZAEHLER_BATCH=1\n' | sudo tee /etc/systemd/system/zaehler.service.d/batch.conf >/dev/null \
  && sudo systemctl daemon-reload"
start=$(date +%s); ssh s2 "sudo systemctl start zaehler"
sleep 2
until [ "$(nats consumer info KLICKS zaehler --json | jq '.num_pending + .num_ack_pending')" = 0 ]; do sleep 1; done
echo "aufgeholt in $(( $(date +%s) - start )) s"
psql -h s3 -U kurz -d kurz -tAc "select 'gezählt: ' || sum(anzahl) from klicks"

Expected:

aufgeholt in 158 s
gezählt: 44947

Not a single click is missing, even though the worker was not running when the stream was created. num_pending counts messages the consumer has not yet delivered, num_ack_pending delivered ones without acknowledgment. When both are 0, the backlog is worked off. That is the most important metric of every asynchronous system.

Save your progress? Sign up for free

Drill 5: Batches

284 clicks per second are not enough for 1500 redirects per second. The backlog would grow without end. The same experiment with the default of 500 messages per batch:

# on s1
ssh s2 "sudo systemctl stop zaehler && sudo rm /etc/systemd/system/zaehler.service.d/batch.conf && sudo systemctl daemon-reload"
psql -h s3 -U kurz -d kurz -qc "TRUNCATE klicks"
k6 run -q klick.js | grep -E 'checks_succeeded'
nats consumer info KLICKS zaehler --json | jq '{num_pending, num_ack_pending, delivered: .delivered.stream_seq}'
start=$(date +%s); ssh s2 "sudo systemctl start zaehler"
sleep 1
until [ "$(nats consumer info KLICKS zaehler --json | jq '.num_pending + .num_ack_pending')" = 0 ]; do sleep 1; done
echo "aufgeholt in $(( $(date +%s) - start )) s"
psql -h s3 -U kurz -d kurz -tAc "select 'gezählt: ' || sum(anzahl) from klicks"

Expected:

    checks_succeeded...: 100.00% 44301 out of 44301
{
  "num_pending": 44301,
  "num_ack_pending": 0,
  "delivered": 44947
}
aufgeholt in 6 s
gezählt: 44301

6 instead of 158 seconds, including the service start. The database no longer gets 44,301 small transactions but 89 large ones, and PostgreSQL combines identical codes before writing. The consumer was at sequence 44,947 and continued exactly there.

Now under running load:

# on s1
psql -h s3 -U kurz -d kurz -qc "TRUNCATE klicks"
a=$(tx)
k6 run -q klick.js | grep -E 'http_req_failed\.|http_req_duration\.|checks_succeeded'
echo "s3 Tx/s: $(( ($(tx) - a) / 30 ))"
nats consumer info KLICKS zaehler --json | jq -c '{num_pending, num_ack_pending}'
sleep 2; psql -h s3 -U kurz -d kurz -tAc "select 'gezählt: ' || sum(anzahl) from klicks"

Expected:

    checks_succeeded...: 100.00% 44783 out of 44783
    http_req_duration..............: avg=6.77ms min=865.66µs med=4.14ms max=143.52ms p(90)=14.18ms p(95)=20.93ms
    http_req_failed................: 0.00%  0 out of 44783
s3 Tx/s: 2
{"num_pending":0,"num_ack_pending":283}
gezählt: 44783

The comparison of the three variants at 1500 redirects per second:

Variant p95 redirect Transactions/s on s3 counted after end of load
no counting 15.8 ms 0 –
synchronous 110.3 ms 1458 all immediately
Core NATS, one by one 20.5 ms 294 after ~2 min, restart loses backlog
JetStream, batch 500 20.9 ms 2 after ~2 s, nothing lost

At the end of the load only 283 clicks were in flight, one batch that was just being written. So the number in the database lags behind by less than a second.

Save your progress? Sign up for free

Drill 6: NATS Fails

NATS is now a building block that every redirect depends on. Load at 1500 per second; after 10 seconds you stop NATS on s2 and start it again 10 seconds later:

# on s1
psql -h s3 -U kurz -d kurz -qc "TRUNCATE klicks"
k6 run -q klick.js > ausfall.log 2>&1 &
sleep 10; ssh s2 "sudo systemctl stop nats"; echo "$(date +%T) NATS gestoppt"
sleep 10; ssh s2 "sudo systemctl start nats"; echo "$(date +%T) NATS gestartet"
wait; grep -E 'http_req_failed\.|http_req_duration\.|checks_succeeded' ausfall.log
sleep 8
psql -h s3 -U kurz -d kurz -tAc "select 'gezählt: ' || sum(anzahl) from klicks"

Expected:

13:07:49 NATS gestoppt
13:08:00 NATS gestartet
    checks_succeeded...: 100.00% 44919 out of 44919
    http_req_duration..............: avg=6.17ms min=896.96µs med=4ms    max=85.22ms p(90)=12.88ms p(95)=18.96ms
    http_req_failed................: 0.00%  0 out of 44919
gezählt: 44871

The users notice nothing. While NATS is missing, the client in kurz collects the messages in a reconnect buffer (default 8 MB, at 25 bytes per click well over 100,000 messages) and sends them afterwards. Half a minute later:

# on s1
psql -h s3 -U kurz -d kurz -tAc "select 'gezählt: ' || sum(anzahl) from klicks"
ssh s2 "journalctl -u nats --since '-5min' -o cat | grep -E 'Shutdown|restore'"

Expected:

gezählt: 44918
[4271] 2026/11/23 13:07:49.014843 [INF] Initiating Shutdown...
[4271] 2026/11/23 13:07:49.014965 [INF] Initiating JetStream Shutdown...
[4271] 2026/11/23 13:07:49.028745 [INF] JetStream Shutdown
[20458] 2026/11/23 13:08:00.850401 [INF]   Starting restore for stream '$G > KLICKS'

44,918 of 44,919. One click was lost: it had already been sent to the server when the server shut down. nc.Publish had reported it as done. Core publish is “fire and forget”; kurz never learns whether JetStream really stored a message. Anyone who needs to know uses js.Publish and waits for the server’s acknowledgment. Then every click costs a network round trip again, and when NATS fails, kurz has to decide whether the redirect goes out anyway.

Save your progress? Sign up for free

Drill 7: Counted Twice

JetStream promises at least once: a message without acknowledgment is redelivered after the ack wait (default 30 s). What if the worker dies after the commit but before the acknowledgment? ZAEHLER_PAUSE widens this gap to three seconds so you can hit it:

# on s1
ssh s2 "printf '[Service]\nEnvironment=ZAEHLER_PAUSE=3s\n' | sudo tee /etc/systemd/system/zaehler.service.d/pause.conf >/dev/null \
  && sudo systemctl daemon-reload && sudo systemctl restart zaehler"
psql -h s3 -U kurz -d kurz -qc "TRUNCATE klicks"
k6 run -q -e RATE=500 -e DAUER=10s klick.js | grep -E 'checks_succeeded'
ssh s2 "sudo pkill -9 -x zaehler"; echo "$(date +%T) zaehler abgeschossen"
sleep 5; nats consumer info KLICKS zaehler --json | jq -c '{num_pending, num_ack_pending}'
sleep 45
until [ "$(nats consumer info KLICKS zaehler --json | jq '.num_pending + .num_ack_pending')" = 0 ]; do sleep 1; done
psql -h s3 -U kurz -d kurz -tAc "select 'gezählt: ' || sum(anzahl) from klicks"

Expected:

    checks_succeeded...: 100.00% 5001 out of 5001
13:10:07 zaehler abgeschossen
{"num_pending":2479,"num_ack_pending":1000}
gezählt: 5501

5001 clicks, 5501 counted. Exactly one batch of 500 is duplicated: it was already stored in PostgreSQL, but the acknowledgment never reached NATS. systemd restarted the worker, and after 30 seconds JetStream delivered the unacknowledged messages once more.

Reversing the order does not help: if the worker acknowledges before the commit, a crash loses clicks instead of duplicating them. Without help from the database there is only “at most once” or “at least once”. How to turn that into “exactly once” is the topic of Day 11. Remove the pause again:

# on s1
ssh s2 "sudo rm /etc/systemd/system/zaehler.service.d/pause.conf && sudo systemctl daemon-reload && sudo systemctl restart zaehler"

Save your progress? Sign up for free

Exercise: Speed drills

  1. How many messages does the stream KLICKS currently hold? Target time: 30 s
  2. Which link was clicked most often? Target time: 1 min
  3. Is the worker lagging behind? Target time: 30 s

Solution

# on s1
nats stream info KLICKS --json | jq .state.messages
psql -h s3 -U kurz -d kurz -tAc "select code, anzahl from klicks order by anzahl desc limit 1"
nats consumer info KLICKS zaehler --json | jq .num_pending

Expected (your numbers will differ, the last line 0 without load):

10000
c170720|1011
0

Save your progress? Sign up for free

Checkpoint

# on s1
ssh s2 systemctl is-active nats zaehler

Expected:

active
active

A click must show up in the table after a short time:

# on s1
psql -h s3 -U kurz -d kurz -tAc "select anzahl from klicks where code = 'c170720'"
curl -s -o /dev/null -w '%{http_code}\n' localhost/c170720; sleep 2
psql -h s3 -U kurz -d kurz -tAc "select anzahl from klicks where code = 'c170720'"

Expected: 302 and a number 1 higher than before, for example 1011 and 1012.

# on s1
nats consumer info KLICKS zaehler --json | jq .num_pending

Expected: 0

Challenge

The stream should not grow without limit. Someone limits KLICKS to 10,000 messages with --discard old. Then the worker fails while 1000 redirects per second arrive for 20 seconds. How many clicks are counted after the restart? How can you tell from the stream and consumer that clicks are missing, without recounting in PostgreSQL?

Hint: Compare the first sequence number in the stream with the consumer’s last acknowledged one.

Solution

# on s1
nats stream edit KLICKS --max-msgs 10000 -f | grep "Maximum Messages"
ssh s2 "sudo systemctl stop zaehler"
psql -h s3 -U kurz -d kurz -qc "TRUNCATE klicks"
k6 run -q -e RATE=1000 -e DAUER=20s klick.js | grep -E 'checks_succeeded'
nats stream info KLICKS --json | jq -c '.state | {messages, first_seq, last_seq}'
nats consumer info KLICKS zaehler --json | jq -c '{num_pending, delivered: .delivered.stream_seq, ack_floor: .ack_floor.stream_seq}'
ssh s2 "sudo systemctl start zaehler"; sleep 8
psql -h s3 -U kurz -d kurz -tAc "select 'gezählt: ' || sum(anzahl) from klicks"

Expected:

             Maximum Messages: 10,000
    checks_succeeded...: 100.00% 19954 out of 19954
{"messages":10000,"first_seq":198905,"last_seq":208904}
{"num_pending":10000,"delivered":188950,"ack_floor":188950}
gezählt: 10000

Only 10,000 of 19,954 clicks. The stream deleted the oldest messages to stay under the limit and told no one. The trace is in the sequence numbers: the consumer has acknowledged up to 188,950, the stream only begins at 198,905. The 9954 numbers in between no longer exist. Monitoring on first_seq > ack_floor + 1 reports exactly this loss.

A limit is still right. But it has to match the longest worker outage you want to bridge, and --discard new is the alternative: then the stream rejects new messages, and the error lands with the sender instead of in the void. Lift the limit again:

# on s1
nats stream edit KLICKS --max-msgs=-1 -f | grep "Maximum Messages"

Expected:

             Maximum Messages: unlimited

Save your progress? Sign up for free

Clean-up

Nothing to tear down. From now on kurz counts all redirects via the stream KLICKS (24 hours of retention, no size limit), and zaehler runs on s2 with batches of 500. Check that no drop-ins for the worker are left over:

# on s1
ssh s2 "ls /etc/systemd/system/zaehler.service.d/"

Expected: no output.

Interview note

  • When asynchronous? For everything the user does not need to see immediately: statistics, e-mails, thumbnails, search index. Say what it costs: the data is correct only later, and you need an eye on the backlog.
  • Which delivery guarantee? At most once (acknowledge before processing), at least once (acknowledge afterwards) or exactly once, which in practice means: at least once plus idempotent processing. Show what a crash does at each point.
  • What if the queue is full? Drop the oldest, reject new ones or slow down the sender. Each choice moves the problem somewhere else; none solves it. Monitor the backlog and measure the worker’s capacity, as here with batch 1 versus 500.

Enterprise note

  • In production, JetStream runs as a cluster of three servers with streams created with --replicas 3. Then a stream survives the failure of one server, and a restart like in Drill 6 loses nothing.
  • Kafka is the common alternative for very large data volumes with long retention, RabbitMQ for classic work queues with routing. The questions of this day stay the same for all of them: storage, acknowledgment, limits, backlog.
  • If a database change and the corresponding message must happen together, you write the message into a table in the same transaction (transactional outbox), and a separate process publishes it from there.

Contents

More