Day 8: Asynchronous with NATS JetStream
Goal: Run NATS as a JetStream cluster across three zones, create the stream
KLICKSdeclaratively with NACK, startzaehleras a Deployment and measure what synchronous and asynchronous counting cost – then let NATS fail under load and count again what gets lost · Duration: approx. 100 min · Prerequisite: Day 7
Briefing
- In the predecessor course NATS ran as a single service on s2, and
zaehler(the counter) was a systemd service. Today both get their Kubernetes form: NATS as a StatefulSet with three Pods, one per zone, each with its own volume. The streamKLICKS(clicks) keeps every message three times. - The stream is no longer created by a human with
nats stream add, but by a controller from a Kubernetes resource: NACK (NATS Controllers for Kubernetes). That puts the stream configuration next to the manifests ofkurz, and it reaches the cluster the same way. kurzandzaehlerbring everything they need: withKURZ_KLICKS=nats://…,kurzpublishes every click on the subjectklicks;zaehlerreads the stream with a durable consumer and counts every message exactly once (version 3 from the predecessor course, imagezaehler:1.0from Day 0).
| Term | Meaning |
|---|---|
| JetStream cluster | several NATS servers that replicate streams via Raft |
| Replicas of a stream | number of servers that store each message; one of them is the leader |
| NACK | controller that turns Stream, Consumer and
Account resources into JetStream objects |
| Durable consumer | remembers on the server side up to where messages were acknowledged |
| Backlog | messages in the stream that no worker has acknowledged yet
(num_pending) |
By the end of the day, kurz counts every click via
JetStream, zaehler runs with two replicas, and you know how
many clicks an outage of the NATS leader costs.
Drill 1: NATS as a JetStream cluster
The official Helm chart nats builds a StatefulSet. You
set three things: a cluster with three servers, JetStream with file
storage on one volume per Pod, and a user kurz whose
password comes from a Secret. NATS reads environment variables in its
configuration when they are written as
<< $NAME >>; the chart passes the expression
through unchanged.
# on s1
# Working directory
mkdir -p ~/sdk/tag08 && cd ~/sdk/tag08
# Helm repository of the NATS charts
helm repo add nats https://nats-io.github.io/k8s/helm/charts/
helm repo update nats
# Values for the chart: cluster, JetStream, user, spread across the zones
cat > nats-values.yaml <<'EOF'
config:
cluster:
enabled: true
replicas: 3
jetstream:
enabled: true
fileStore:
pvc:
size: 1Gi
merge:
authorization:
users:
- user: kurz
password: << $NATS_KURZ_PASSWORT >>
container:
env:
NATS_KURZ_PASSWORT:
valueFrom:
secretKeyRef:
name: nats-kurz
key: passwort
podTemplate:
topologySpreadConstraints:
topology.kubernetes.io/zone:
maxSkew: 1
whenUnsatisfiable: DoNotSchedule
natsBox:
enabled: false
EOF
# Own namespace and the password as a Secret
kubectl create namespace nats
kubectl -n nats create secret generic nats-kurz --from-literal=passwort=lab-nats-123
# Install the version from the style guide, wait until all Pods are ready
helm install nats nats/nats --version 2.15.3 -n nats -f nats-values.yaml --wait --timeout 5m | tail -3
# One Pod per node, one volume per Pod
kubectl -n nats get pods -o wide | awk '{print $1, $2, $3, $7}'
kubectl -n nats get pvc | awk '{print $1, $2, $4}'Expected:
REVISION: 1
DESCRIPTION: Install complete
TEST SUITE: None
NAME READY STATUS NODE
nats-0 2/2 Running s1
nats-1 2/2 Running s2
nats-2 2/2 Running s3
NAME STATUS CAPACITY
nats-js-nats-0 Bound 1Gi
nats-js-nats-1 Bound 1Gi
nats-js-nats-2 Bound 1Gi
The topology rule is the same idea as for Valkey on Day 5: if a zone
fails, two of three servers remain, and Raft still has a majority.
nats-box, a helper Pod with the CLI, is off: the
nats CLI has been on s1 since the predecessor course.
Save your progress? Sign up for free
Drill 2: Connecting and being rejected
The Service nats is a ClusterIP Service. You reach it
directly from s1, because s1 is a node of the cluster.
# on s1
# Address of the Service; you build the CLI URL with it
IP=$(kubectl -n nats get svc nats -o jsonpath='{.spec.clusterIP}')
N="nats -s nats://kurz:lab-nats-123@$IP:4222"
# Who am I, which server am I connected to, is JetStream there?
$N account info | grep -E 'User:|Connected Server (Name|Version)|Streams:'
# Wrong user: must fail
nats -s nats://falsch:x@$IP:4222 pub test hallo 2>&1 | tail -1Expected:
User: kurz
Connected Server Version: 2.15.3
Connected Server Name: nats-0
Streams: 0
nats: error: nats: Authorization Violation
account info shows the password in plain text in the
line Connected URL. The CLI prints what it was given;
output like that does not belong in logs.
Save your progress? Sign up for free
Drill 3: The stream as a Kubernetes resource
You install NACK with Helm as well. The newer operating mode
controlLoop reconciles the state regularly and repairs
drift, instead of only reacting to changes of the resources.
# on s1
# NACK 0.25.0 (chart 0.36.0) in the namespace nats
helm install nack nats/nack --version 0.36.0 -n nats --set jetstream.controlLoop=true --wait | tail -1
# The new resource types
kubectl get crd | grep jetstream.nats.io | awk '{print $1}'Expected:
Thanks for using NATS JetStream Controller!
accounts.jetstream.nats.io
consumers.jetstream.nats.io
keyvalues.jetstream.nats.io
objectstores.jetstream.nats.io
streams.jetstream.nats.io
streamtemplates.jetstream.nats.io
An Account resource tells NACK where to connect and with
which credentials. The credentials are in a Secret in the namespace
kurz, which is where the stream resource lives too. The
stream itself: subject klicks, file storage, three
replicas, older messages are dropped after 24 hours – as in the
predecessor course, only with replicas.
# on s1
# Account (connection + credentials) and stream KLICKS
cat > stream.yaml <<'EOF'
apiVersion: jetstream.nats.io/v1beta2
kind: Account
metadata:
name: nats-kurz
namespace: kurz
spec:
name: nats-kurz
servers: ["nats://nats.nats.svc.cluster.local:4222"]
user:
secret:
name: nats-konto
user: benutzer
password: passwort
---
apiVersion: jetstream.nats.io/v1beta2
kind: Stream
metadata:
name: klicks
namespace: kurz
spec:
name: KLICKS
account: nats-kurz
subjects: ["klicks"]
storage: file
replicas: 3
retention: limits
discard: old
maxAge: 24h
EOF
# Credentials for NACK (and also for kurz and zaehler)
kubectl -n kurz create secret generic nats-konto --from-literal=benutzer=kurz --from-literal=passwort=lab-nats-123
kubectl apply -f stream.yaml
# NACK reports the state in the resource
sleep 5; kubectl -n kurz get streams.jetstream.nats.io klicks
# And this is how NATS sees the stream
$N stream info KLICKS --json | jq '{replicas: .config.num_replicas, storage: .config.storage, leader: .cluster.leader, replicas_on: [.cluster.replicas[].name]}'Expected:
NAME STATE STREAM NAME SUBJECTS
klicks Ready KLICKS ["klicks"]
{
"replicas": 3,
"storage": "file",
"leader": "nats-0",
"replicas_on": [
"nats-1",
"nats-2"
]
}
You do not create the consumer zaehler as a resource:
zaehler creates it itself at startup with
CreateOrUpdateConsumer. Doing both would be a fight between
two owners over the same configuration. The rule is: what operations
decides (storage, replicas, retention) belongs in the resource; what the
application needs in order to work, it may create itself.
Save your progress? Sign up for free
Drill 4: zaehler as a Deployment
zaehler gets its database URL via the pooler from Day 7
and the NATS URL with the password from the Secret. The security
settings match those of kurz, with one gap:
# on s1
# Deployment for zaehler (one replica)
cat > zaehler.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
name: zaehler
namespace: kurz
spec:
replicas: 1
selector:
matchLabels:
app: zaehler
template:
metadata:
labels:
app: zaehler
spec:
containers:
- name: zaehler
image: 172.16.0.126:5000/zaehler:1.0
env:
- name: DB_PASSWORT
valueFrom:
secretKeyRef:
name: db-kurz
key: password
- name: NATS_PASSWORT
valueFrom:
secretKeyRef:
name: nats-konto
key: passwort
- name: ZAEHLER_DB
value: postgres://kurz:$(DB_PASSWORT)@db-pooler-rw:5432/kurz?connect_timeout=2
- name: ZAEHLER_NATS
value: nats://kurz:$(NATS_PASSWORT)@nats.nats.svc.cluster.local:4222
resources:
requests:
cpu: 100m
memory: 32Mi
limits:
memory: 64Mi
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
runAsNonRoot: true
EOF
kubectl apply -f zaehler.yaml
# The Pod does not start – why?
sleep 20; kubectl -n kurz get pods -l app=zaehler
kubectl -n kurz describe pod -l app=zaehler | grep -o 'Error: container has runAsNonRoot.*cannot verify user is non-root'Expected:
NAME READY STATUS RESTARTS AGE
zaehler-6ccbc88667-smt44 0/1 CreateContainerConfigError 0 20s
Error: container has runAsNonRoot and image has non-numeric user (nonroot), cannot verify user is non-root
The image sets USER nonroot (distroless). A name does
not tell the kubelet whether UID 0 is behind it, so it refuses to start
the container. kurz does not have this problem because its
manifest has set runAsUser: 65532 since Day 1 – the UID of
nonroot in the distroless images.
# on s1
# Add the numeric UID, roll out again
sed -i 's/^ runAsNonRoot: true$/&\n runAsUser: 65532/' zaehler.yaml
kubectl apply -f zaehler.yaml
kubectl -n kurz rollout status deploy/zaehler --timeout=90s
# zaehler reports its settings
kubectl -n kurz logs deploy/zaehlerExpected:
deployment.apps/zaehler configured
deployment "zaehler" successfully rolled out
2026/11/25 10:54:49 zaehler: Batch 500, Pause 0s
Save your progress? Sign up for free
Drill 5: Three ways to count
A new k6 script sends only redirects; each one is a click. The measurement runs at 1000 requests per second through the Gateway. At 1500/s, the rate from Day 5, p95 in this lab is already above 200 ms without any counting, because k6 itself runs on s1. The comparison needs headroom.
# on s1
# Take over the codes from Day 7
cp ../tag07/codes.txt .
# k6: redirects only, rate and duration via environment
cat > klick.js <<'EOF'
import http from "k6/http";
import { check } from "k6";
import { SharedArray } from "k6/data";
// Nur Weiterleitungen: jede Anfrage ist ein Klick, der gezählt werden soll.
const codes = new SharedArray("codes", () => open("./codes.txt").split("\n").filter(Boolean));
const ZIEL = __ENV.ZIEL || "http://localhost:8080";
export const options = {
scenarios: {
klicks: {
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 () {
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 });
}
EOF
# Function xact: committed transactions of the database kurz on the current primary
xact() { kubectl -n kurz exec $(kubectl -n kurz get cluster db -o jsonpath='{.status.currentPrimary}') -c postgres -- psql -d kurz -tAc "select xact_commit from pg_stat_database where datname = 'kurz'"; }
# Function messen: 30 s of load, key figures, transactions per second
messen() { X0=$(xact); ZIEL=http://172.16.0.126 RATE=1000 DAUER=30s k6 run --quiet klick.js 2>/dev/null \
| grep -E 'http_req_duration\.|http_reqs\.|http_req_failed\.' | sed 's/ */ /g'; X1=$(xact); echo "DB-Transaktionen: $(( (X1 - X0) / 30 ))/s"; }
# Variant 1: kurz does not count at all (state of Day 7)
messenExpected:
http_req_duration..............: avg=15.31ms min=1.59ms med=9.03ms max=186.25ms p(90)=34.29ms p(95)=53.22ms
http_req_failed................: 0.00% 0 out of 29952
http_reqs......................: 29952 997.791097/s
DB-Transaktionen: 0/s
Zero transactions: every redirect comes from the cache (Day 5). Now
kurz counts synchronously, that is, with an
INSERT … ON CONFLICT in every redirect. The setting belongs
in the ConfigMap; because Pods do not re-read a changed ConfigMap on
their own, a restart follows:
# on s1
# Take over the manifest from Day 7, counting mode sync in the ConfigMap
cp ../tag07/kurz.yaml kurz.yaml
sed -i 's|^ KURZ_CACHE: valkey-cache:6379$|&\n KURZ_KLICKS: sync|' kurz.yaml
kubectl apply -f kurz.yaml
kubectl -n kurz rollout restart deploy/kurz && kubectl -n kurz rollout status deploy/kurz --timeout=120s | tail -1
# Empty the counters, measure, sum of the counted clicks
kubectl -n kurz exec db-2 -c postgres -- psql -d kurz -qc 'TRUNCATE klicks'
messen
kubectl -n kurz exec db-2 -c postgres -- psql -d kurz -tAc 'SELECT sum(anzahl) FROM klicks'Expected:
deployment "kurz" successfully rolled out
http_req_duration..............: avg=1.04s min=136.17ms med=1.04s max=1.46s p(90)=1.19s p(95)=1.24s
http_req_failed................: 0.00% 0 out of 14012
http_reqs......................: 14012 453.244125/s
DB-Transaktionen: 461/s
14012
db-2 has been the primary since Day 7; if it is a
different one for you, take the name from
kubectl -n kurz get cluster db.
Not a single error, but only 453 instead of 1000 requests per second,
and p95 jumps from 53 ms to 1.24 s. k6 did not even send the remaining
requests, because all 500 virtual users were waiting. The limit is not
in PostgreSQL but in the pool of kurz: by default pgx opens
at most four connections per Pod (or as many as CPU cores, if that is
more), two Pods, each transaction takes about 17 ms – that makes just
under 470 transactions per second. More is not possible, no matter how
fast the rest is.
Now asynchronous. The counting mode moves out of the ConfigMap and into the Deployment as an environment variable, because the URL needs the password from the Secret:
# on s1
# Remove sync again
sed -i '/^ KURZ_KLICKS: sync$/d' kurz.yaml
# Insert NATS_PASSWORT from the Secret and KURZ_KLICKS before KURZ_DB
sed -i 's|^ - name: KURZ_DB$| - name: NATS_PASSWORT\n valueFrom:\n secretKeyRef:\n name: nats-konto\n key: passwort\n - name: KURZ_KLICKS\n value: nats://kurz:$(NATS_PASSWORT)@nats.nats.svc.cluster.local:4222\n&|' kurz.yaml
# Difference to Day 7
diff ../tag07/kurz.yaml kurz.yaml
kubectl apply -f kurz.yaml && kubectl -n kurz rollout status deploy/kurz --timeout=120s | tail -1
# Empty the counters, remember the stream position, measure, check again
kubectl -n kurz exec db-2 -c postgres -- psql -d kurz -qc 'TRUNCATE klicks'
S0=$($N stream info KLICKS --json | jq .state.last_seq)
messen
sleep 5
S1=$($N stream info KLICKS --json | jq .state.last_seq); echo "Nachrichten im Stream: $((S1 - S0))"
kubectl -n kurz exec db-2 -c postgres -- psql -d kurz -tAc 'SELECT sum(anzahl) FROM klicks'Expected:
49a50,56
> - name: NATS_PASSWORT
> valueFrom:
> secretKeyRef:
> name: nats-konto
> key: passwort
> - name: KURZ_KLICKS
> value: nats://kurz:$(NATS_PASSWORT)@nats.nats.svc.cluster.local:4222
deployment "kurz" successfully rolled out
http_req_duration..............: avg=18.47ms min=1.87ms med=12.77ms max=161.92ms p(90)=37.8ms p(95)=54.22ms
http_req_failed................: 0.00% 0 out of 29845
http_reqs......................: 29845 994.366014/s
DB-Transaktionen: 2/s
Nachrichten im Stream: 29845
29845
| Variant | Requests/s | p95 | DB transactions/s | Counted |
|---|---|---|---|---|
| not at all | 998 | 53 ms | 0 | – |
| synchronous | 453 | 1.24 s | 461 | all |
| via JetStream | 994 | 54 ms | 2 | all 29,845 |
Asynchronous counting costs the redirect practically nothing, and
instead of one transaction per click the database sees two per second:
zaehler fetches up to 500 messages and writes them with one
statement. The price is delay: the number in klicks is only
correct once zaehler has caught up.
Save your progress? Sign up for free
Drill 6: The leader fails
Every stream has a leader that accepts messages and passes them on to the replicas. What happens to clicks when exactly this Pod disappears under load?
# on s1
# Who leads the stream?
L=$($N stream info KLICKS --json | jq -r .cluster.leader); echo "Leader: $L"
kubectl -n kurz exec db-2 -c postgres -- psql -d kurz -qc 'TRUNCATE klicks'
S0=$($N stream info KLICKS --json | jq .state.last_seq)
# 60 s of load in the background
(ZIEL=http://172.16.0.126 RATE=1000 DAUER=60s k6 run --quiet klick.js > k6-leader.txt 2>&1 &)
# After 15 s delete the leader and watch who takes over
sleep 15; kubectl -n nats delete pod $L --wait=false
for i in 1 2 3; do sleep 5; $N stream info KLICKS --json | jq -c '{leader: .cluster.leader, msgs: .state.messages}'; done
# Wait for the end of the load, then the balance: k6, stream, database, error messages from kurz
sleep 50; grep -E 'checks_succeeded|http_req_failed\.' k6-leader.txt | sed 's/ */ /g'
sleep 8; S1=$($N stream info KLICKS --json | jq .state.last_seq); echo "Stream: $((S1 - S0))"
kubectl -n kurz exec db-2 -c postgres -- psql -d kurz -tAc 'SELECT sum(anzahl) FROM klicks'
kubectl -n kurz logs -l app=kurz --since=2m | grep -c 'zaehle:'Expected (number of messages in the stream abridged):
Leader: nats-0
pod "nats-0" deleted from nats namespace
{"leader":"nats-1","msgs":…}
{"leader":"nats-1","msgs":…}
{"leader":"nats-1","msgs":…}
checks_succeeded...: 100.00% 59621 out of 59621
http_req_failed................: 0.00% 0 out of 59621
Stream: 59573
59573
0
After less than five seconds nats-1 leads, no user saw
an error, and zaehler counted everything that is in the
stream. Even so, 48 clicks are missing, and
kurz did not notice a single one of them. The reason is in
klicks.go from the predecessor course:
nc.Publish is core NATS, “fire and forget”.
kurz never learns whether the stream stored the message.
Messages that arrive in the gap between the old and the new leader, or
that were still on their way over the connection to the deleted Pod, are
silently gone. How to make that visible is the Challenge.
This is not yet a disorderly outage: kubectl delete pod
stops NATS with a grace period. The leader hands over leadership before
it leaves. With a hard outage (node gone), the handover takes
longer.
Save your progress? Sign up for free
Drill 7: Backlog and a second zaehler
What happens when the worker is missing for a while? With core NATS the clicks were then gone. With JetStream they pile up in the stream:
# on s1
# Stop zaehler, empty the counters, 30 s of load
kubectl -n kurz scale deploy/zaehler --replicas=0
kubectl -n kurz exec db-2 -c postgres -- psql -d kurz -qc 'TRUNCATE klicks'
messen | grep http_reqs
# Backlog: pending messages for the consumer zaehler
$N consumer info KLICKS zaehler --json | jq -c '{offen: .num_pending}'
# Two workers instead of one, watch the backlog shrink every 3 s
kubectl -n kurz scale deploy/zaehler --replicas=2
for i in $(seq 8); do sleep 3; $N consumer info KLICKS zaehler --json | jq -c '{offen: .num_pending, in_arbeit: .num_ack_pending}'; done
# After the backlog is gone: sum in the database
sleep 15; kubectl -n kurz exec db-2 -c postgres -- psql -d kurz -tAc 'SELECT sum(anzahl) FROM klicks'Expected:
http_reqs......................: 29872 994.724433/s
{"offen":29872}
{"offen":17872,"in_arbeit":1000}
{"offen":9872,"in_arbeit":1000}
{"offen":6658,"in_arbeit":1000}
{"offen":3944,"in_arbeit":1000}
{"offen":2147,"in_arbeit":1000}
{"offen":526,"in_arbeit":1000}
{"offen":0,"in_arbeit":652}
{"offen":0,"in_arbeit":652}
29872
No click lost, none counted twice. Two Pods share the consumer: each
fetches its own batch of 500, which makes the 1000 “in progress”
(in_arbeit; offen = pending). The backlog from
30 seconds of load is gone in about 20 seconds. That the two workers
count nothing twice is thanks to version 3 of zaehler: it
records every sequence number in klicks_verarbeitet and
counts a message only if its number is new.
The backlog is the number you want to scale on, not CPU:
zaehler is bored with an empty stream and is still hardly
busy with 30,000 pending messages. That is exactly what KEDA does on Day
10. zaehler stays at two replicas.
Save your progress? Sign up for free
Exercise: Speed drills
- How many messages and how many bytes are in the stream, and who is the leader right now? Target time: 1 min
- Does
zaehlerhave a backlog right now? Target time: 1 min - Do the math: is the 1 GiB volume per NATS Pod enough if
kurzconstantly publishes 1000 clicks per second and the stream keeps them for 24 hours? Target time: 3 min
Solution
# on s1
# 1: state and leader of the stream
$N stream info KLICKS --json | jq -c '{messages: .state.messages, bytes: .state.bytes, leader: .cluster.leader}'
# 2: backlog and unacknowledged messages of the consumer
$N consumer info KLICKS zaehler --json | jq -c '{pending: .num_pending, ack_pending: .num_ack_pending}'Expected (your numbers depend on your runs):
{"messages":375482,"bytes":29723883,"leader":"nats-2"}
{"pending":0,"ack_pending":0}
On 3: 29,723,883 bytes for 375,482 messages are about 79 bytes per
message (code, subject, headers). 1000 per second times 79 bytes is 79
KB/s, so about 6.8 GB in 24 hours. The volume is full after about 3.8
hours. What happens then depends on the stream: without
maxBytes no stream limit applies; once the server’s storage
is exhausted, JetStream rejects new messages. The fix is a limit that
fits the disk, for example maxBytes: 800Mi (with
discard: old the oldest clicks are then dropped), or a
shorter maxAge. The 24 hours from the predecessor course
were sized for a test, not for sustained load.
Save your progress? Sign up for free
Challenge
kurz should notice when a click did not arrive in the
stream. The redirect must not get slower. Repeat Drill 6 and compare:
how many clicks are missing, and how many does kurz
report?
Solution
JetStream acknowledges every message with an ack.
PublishAsync sends the message without waiting for the ack
and calls a handler if one does not arrive. Three settings matter:
- Timeout: without
WithPublishAsyncTimeout, a message without an answer stays pending forever – the handler is never called, and the loss stays as silent as before. - Retry when there is no leader:
WithRetryAttemptstries again when no server is currently leading the stream (“no responders”). - Msg ID: a unique ID per click lets JetStream discard a message that arrived twice (default: a two-minute duplicate window).
# on s1
# Save the old version, then a new klicks.go: JetStream with ack, timeout, reporting of lost clicks
cd ~/sdk/kurz && cp klicks.go klicks.go.core
cat > klicks.go <<'EOF'
package main
import (
"context"
"log"
"strings"
"time"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
"github.com/nats-io/nuid"
)
// 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
js jetstream.JetStream
)
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
nats.DisconnectErrHandler(func(_ *nats.Conn, err error) { log.Printf("nats getrennt: %v", err) }),
nats.ReconnectHandler(func(c *nats.Conn) { log.Printf("nats wieder da: %s", c.ConnectedServerName()) }))
if err != nil {
log.Fatalf("nats: %v", err)
}
// JetStream bestätigt jede Nachricht. Kommt binnen 3 s keine Bestätigung (z. B. weil der
// NATS-Pod, mit dem kurz verbunden war, gerade neu startet), meldet der Handler den Verlust.
// Ohne Zeitlimit bliebe so eine Nachricht für immer offen – ein stiller Verlust.
js, err = jetstream.New(nc,
jetstream.WithPublishAsyncMaxPending(4096),
jetstream.WithPublishAsyncTimeout(3*time.Second),
jetstream.WithPublishAsyncErrHandler(func(_ jetstream.JetStream, m *nats.Msg, err error) {
log.Printf("klick verloren: %s: %v", m.Data, err)
}))
if err != nil {
log.Fatalf("jetstream: %v", err)
}
log.Printf("%s: Klicks über JetStream %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 js != nil:
// Asynchron: die Weiterleitung wartet nicht auf die Bestätigung. Ohne Leader im Stream
// („no responders“) versucht der Client es bis zu 20-mal im Abstand von 250 ms;
// die Msg-ID lässt JetStream doppelte Zustellungen derselben Nachricht verwerfen.
_, err = js.PublishAsync("klicks", []byte(code),
jetstream.WithMsgID(nuid.Next()),
jetstream.WithRetryAttempts(20),
jetstream.WithRetryWait(250*time.Millisecond))
}
if err != nil {
log.Printf("zaehle: %v", err) // ein verlorener Klick, die Weiterleitung klappt trotzdem
}
}
EOF
# Tidy dependencies, vet, build image 1.1 and push it to the registry
go mod tidy && go vet .
cd ~/sdk && sudo docker build -q -t 172.16.0.126:5000/kurz:1.1 kurz && sudo docker push -q 172.16.0.126:5000/kurz:1.1
# Separate manifest with the new image, roll out
cd ~/sdk/tag08 && sed 's|kurz:1.0|kurz:1.1|' kurz.yaml > kurz-ack.yaml
kubectl apply -f kurz-ack.yaml && kubectl -n kurz rollout status deploy/kurz --timeout=120s | tail -1The Go comments in the heredoc stay as they are in the lab source. In short: the handler reports a click as lost if no ack arrives within 3 s; without a leader the client retries up to 20 times every 250 ms; the Msg ID lets JetStream discard duplicates.
Then Drill 6 once more; only the evaluation at the end changes:
# on s1
# After the run: stream, database, and what kurz reported (codes replaced by CODE)
S1=$($N stream info KLICKS --json | jq .state.last_seq); echo "Stream: $((S1 - S0))"
kubectl -n kurz logs -l app=kurz --since=3m | grep -E 'klick verloren|nats wieder' \
| sed -E 's/^.{20}//; s/verloren: [A-Za-z0-9]+/verloren: CODE/' | sort | uniq -cExpected (k6: 59,720 requests, 0 errors, p95 53 ms):
Stream: 59715
10 klick verloren: CODE: nats: timeout waiting for ack
9 klick verloren: CODE: nats: server is disconnected
1 nats wieder da: nats-1
Five clicks are missing, kurz reports 19
(klick verloren = click lost). The redirect is as fast as
before. Two things are in this result:
- No more silent loss. Every missing click is among
the reported ones. The nine “server is disconnected” came from the
kurzPod that was connected to the deleted NATS Pod. - “No ack” means “unknown”, not “lost”. 14 of the 19 reported clicks still arrived in the stream; only the acknowledgment was lost. If you want to count without guessing, you need a way to resend unacknowledged messages – with the same Msg ID, so that JetStream discards duplicates.
Happened during testing: the obvious attempt to resend immediately in the handler brought the lab to a halt (p95 15 s, 8 % errors). The handler runs in the same goroutine that processes all acks. With 4096 messages pending during the leader election, the resend blocked right there – and with it every further redirect. Resending belongs in its own queue with its own goroutine or, more robustly, in an outbox: the click lands locally first (file, table), and a background job sends it until the ack arrives.
The lab stays on the main path with kurz:1.0:
# on s1
# Keep the solution, revert the kurz source to core NATS, tidy dependencies
cp ~/sdk/kurz/klicks.go klicks-ack.go
cd ~/sdk/kurz && mv klicks.go.core klicks.go && go mod tidy && cd ~/sdk/tag08
# Manifest from Drill 5 (kurz:1.0)
kubectl apply -f kurz.yaml && kubectl -n kurz rollout status deploy/kurz --timeout=120s | tail -1Save your progress? Sign up for free
Checkpoint
# on s1
# Three NATS Pods, one per node
kubectl -n nats get pods -l app.kubernetes.io/name=nats -o custom-columns=NAME:.metadata.name,NODE:.spec.nodeName,READY:.status.containerStatuses[0].ready
# Stream resource reconciled by NACK
kubectl -n kurz get streams.jetstream.nats.io klicks -o jsonpath='{.status.conditions[0].type}={.status.conditions[0].status}{"\n"}'
# zaehler ready with two replicas
kubectl -n kurz get deploy zaehler -o jsonpath='{.status.readyReplicas}{"\n"}'
# kurz publishes clicks via NATS
kubectl -n kurz get deploy kurz -o jsonpath='{.spec.template.spec.containers[0].env[?(@.name=="KURZ_KLICKS")].value}{"\n"}'
# One click, one more message in the stream
A=$($N stream info KLICKS --json | jq .state.last_seq)
curl -s -o /dev/null -w "%{http_code}\n" http://172.16.0.126/$(head -1 codes.txt)
sleep 1; B=$($N stream info KLICKS --json | jq .state.last_seq); echo "neue Nachrichten: $((B - A))"Expected:
NAME NODE READY
nats-0 s1 true
nats-1 s2 true
nats-2 s3 true
Ready=True
2
nats://kurz:$(NATS_PASSWORT)@nats.nats.svc.cluster.local:4222
302
neue Nachrichten: 1
Interview note
- Why asynchronous? What the user does not need does not belong in their waiting time. Here: synchronous 453 requests/s at p95 1.24 s, asynchronous 994/s at 54 ms – and the database writes in batches (2 instead of 461 transactions per second).
- What does it cost? Delay (the number is only correct later) and new failure modes: lost messages when publishing, duplicates when processing. The server’s ack helps against the first, an idempotent worker against the second.
- At-least-once plus idempotency gives exactly once – but only from the stream onward. Before that, the producer decides: fire-and-forget silently lost 48 of 60,000 clicks here.
- Scale on backlog instead of CPU: a worker that
waits on I/O does not look busy under load. The right metric is
num_pending.
Enterprise note
- Streams as Kubernetes resources (NACK) are GitOps-ready: retention, replicas and limits live in the repository and get reviewed. In real environments, accounts and permissions do not belong in a Secret as a password, but as an NKey or JWT with a separate account per application.
- Stream limits (
maxBytes,maxAge,maxMsgsPerSubject) are part of capacity planning, like disk sizes. A full stream is an outage you can calculate hours in advance. - Counting clicks without loss is rarely the goal; orders are another matter. For business events the transactional outbox is the usual way: store the event in the same database transaction as the change, and a relay publishes it with a Msg ID.