Skip to content
System design · Chapter 13 of 21 Day 11: Reliable Delivery – Idempotency, Retries, Backoff

Day 11: Reliable Delivery – Idempotency, Retries, Backoff

Goal: Repetitions must not do anything twice. You create duplicate links with a perfectly normal client that resends after a timeout, measure what backoff changes and what it does not, build an idempotency key for POST /api/links and make the click counter count every message exactly once · Duration: approx. 90 min · Prerequisite: Day 10

Briefing

  • Two numbers from the last few days are wrong: on Day 9, 118 addresses were created twice, and on Day 10, 5001 clicks turned into 5501. Both times nobody made a mistake. A part of the system repeated something because it could not know whether the first attempt had worked.
  • That is the normal case in distributed systems. A timeout only says: the answer did not arrive in time. Whether the work is done, the sender does not know. Whoever never repeats loses work. Whoever repeats sometimes does it twice.
  • The way out is called idempotency: an operation is idempotent if it changes nothing the second time. Then anyone may repeat as often as they like. For that, every operation needs an identifier by which the receiver recognizes the repetition.
Term Meaning
Retry a new attempt after an error or timeout
Backoff growing wait time between attempts, usually doubled
Jitter randomness in the wait time, so that not all clients come back at the same time
Idempotency key identifier the client generates per operation and sends along with every repetition
Message ID the same for messages: in NATS the header Nats-Msg-Id
Exactly-once in practice: deliver at least once and process idempotently

By the end of the day kurz accepts an Idempotency-Key, new addresses are guaranteed to get only one code, and zaehler counts every click exactly once.

Drill 1: One Timeout, Two Links

A repetition only creates a duplicate if it overtakes the first attempt. At 6 ms per creation that rarely happens. So that you can trigger it deliberately, kurz gets a pause before the INSERT that is set only today, like ZAEHLER_PAUSE on Day 10:

# on s1
mkdir -p ~/sd/tag11
cd ~/kurz && cp main.go /tmp/main.go.alt
perl -0pi -e 's/(\tcodeLaenge, _ = .*\n)/$1\t\/\/ Nur für Tag 11: Pause vor dem INSERT\n\tverzoegerung, _ = time.ParseDuration(env("KURZ_VERZOEGERUNG", "0s"))\n/' main.go
perl -0pi -e 's/(\tfor versuch := 0; versuch < 3; versuch\+\+ \{\n)/\ttime.Sleep(verzoegerung)\n$1/' main.go
diff /tmp/main.go.alt main.go
go vet . && go build -o kurz . && echo gebaut

Expected:

28a29,30
>   // Nur für Tag 11: Pause vor dem INSERT
>   verzoegerung, _ = time.ParseDuration(env("KURZ_VERZOEGERUNG", "0s"))
67a70
>   time.Sleep(verzoegerung)
gebaut

Roll out with a 300 ms pause, using a drop-in and the loop from Day 9:

# on s1
for s in s1 s2; do
  ssh $s "printf '[Service]\nEnvironment=KURZ_VERZOEGERUNG=300ms\n' \
    | sudo tee /etc/systemd/system/kurz.service.d/verzoegerung.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

Now curl behaves like an impatient client: after 250 ms it gives up and sends the same request again.

# on s1
cd ~/sd/tag11
export PGPASSWORD=lab-kurz-123
U=https://example.org/tag11/einmal
curl -s -m 0.25 -X POST localhost/api/links -d "{\"url\":\"$U\"}"; echo "rc=$?"
curl -s -X POST -w ' %{http_code}\n' localhost/api/links -d "{\"url\":\"$U\"}"
sleep 1
psql -h s3 -U kurz -d kurz -c "select code, angelegt::time(3) from links where url = '$U' order by angelegt"

Expected (codes and times will differ):

rc=28
{"code":"bj9aFyz","url":"https://example.org/tag11/einmal"}
 201
  code   |   angelegt
---------+--------------
 VzYuqDN | 19:10:58.011
 bj9aFyz | 19:10:58.29
(2 rows)

rc=28 is the curl timeout. The client never got an answer, and still the first attempt created a link, 280 ms before the second. The check “does the address already exist?” from Day 7 does not help: when the second attempt looked, the first was not yet stored. Checking and creating are two steps, and there is room for someone else in between.

Save your progress? Sign up for free

Drill 2: Retrying With and Without Backoff

A client as you often see it: up to four attempts, timeout 250 ms. MODUS=sofort retries immediately, MODUS=backoff waits a random time between 0 and 100, 200, 400 ms before the next attempt. Each iteration creates its own address, and LAUF separates the runs in the database:

# on s1
cat > wieder.js <<'EOF'
import http from "k6/http";
import { sleep } from "k6";
import { Counter } from "k6/metrics";

const ZIEL = __ENV.ZIEL || "http://localhost";
const LAUF = __ENV.LAUF || "a";              // trennt die Läufe in der Datenbank
const MODUS = __ENV.MODUS || "sofort";       // sofort | backoff
const SCHLUESSEL = __ENV.SCHLUESSEL === "1"; // Idempotency-Key mitschicken?
const geschafft = new Counter("geschafft");
const aufgegeben = new Counter("aufgegeben");

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

// Wartezeit vor dem nächsten Versuch: exponentiell wachsend, zufällig verteilt ("full jitter")
function warte(versuch) {
  if (MODUS === "backoff") sleep(Math.random() * Math.min(2, 0.1 * 2 ** versuch));
}

export default function () {
  const url = `https://example.org/tag11/${LAUF}/${__VU}-${__ITER}`;
  const headers = { "Content-Type": "application/json" };
  if (SCHLUESSEL) headers["Idempotency-Key"] = `${LAUF}-${__VU}-${__ITER}`;
  for (let versuch = 0; versuch < 4; versuch++) {
    const r = http.post(`${ZIEL}/api/links`, JSON.stringify({ url }),
      { headers, timeout: __ENV.TIMEOUT || "250ms" });
    if (r.status === 200 || r.status === 201) {
      geschafft.add(1);
      return;
    }
    warte(versuch);
  }
  aufgegeben.add(1);
}
EOF
doppelt() { psql -h s3 -U kurz -d kurz -tAc "select count(*) || ' Zeilen, ' || count(distinct url) || ' Adressen' from links where url like 'https://example.org/tag11/$1/%'"; }
k6 run -q -e LAUF=sofort wieder.js 2>&1 | grep -E 'geschafft|aufgegeben|http_reqs\.'
sleep 1; doppelt sofort

Expected:

    geschafft......................: 600    19.697792/s
    http_reqs......................: 1800   59.093376/s
1200 Zeilen, 600 Adressen

All 600 operations succeeded; from the client’s point of view everything is fine. In the database every address is there twice, and kurz received 1800 instead of 600 requests. The sequence per operation: attempt 1 runs into the timeout after 250 ms, attempt 2 starts immediately, finds nothing and creates a second link after 300 ms, but itself runs into the timeout. Attempt 3 finally finds the first link and gets 200. Now with backoff:

# on s1
k6 run -q -e LAUF=backoff -e MODUS=backoff wieder.js 2>&1 | grep -E 'geschafft|aufgegeben|http_reqs\.'
sleep 1; doppelt backoff

Expected:

    geschafft......................: 601    19.551803/s
    http_reqs......................: 1484   48.277665/s
883 Zeilen, 601 Adressen

Backoff helps: 18% fewer requests and 282 instead of 600 duplicates, because many repetitions arrive only after the commit of the first attempt. The duplicates are not gone. Backoff protects the server from an avalanche of repetitions when it is already slow. It does not protect against duplicate work. For that, the server has to recognize the repetition.

Save your progress? Sign up for free

Drill 3: Idempotency Key

The common pattern for HTTP: the client generates a key per operation and sends it with every attempt in the header Idempotency-Key. The server stores the response for the key. If the key comes again, it sends the stored response instead of repeating the work. If the same key comes with a different request, that is a client error: 422.

# on s1
psql -h s3 -U kurz -d kurz <<'EOF'
CREATE TABLE idempotenz (
  schluessel text PRIMARY KEY,
  anfrage    bytea NOT NULL,            -- SHA-256 des Request-Bodys
  status     int NOT NULL DEFAULT 0,
  antwort    bytea,
  angelegt   timestamptz NOT NULL DEFAULT now()
);
EOF

Expected: CREATE TABLE

The key is checked by a separate handler that sits in front of anlegen. It begins a transaction and inserts the key. If a second request with the same key comes at the same time, its INSERT waits until the first transaction is done. That is the whole trick against the overtaking from Drill 1:

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

import (
    "bytes"
    "crypto/sha256"
    "io"
    "log"
    "net/http"
)

// aufnahme hält Status und Body einer Antwort fest, statt sie gleich zu senden.
type aufnahme struct {
    header http.Header
    status int
    body   bytes.Buffer
}

func (a *aufnahme) Header() http.Header         { return a.header }
func (a *aufnahme) Write(b []byte) (int, error) { return a.body.Write(b) }
func (a *aufnahme) WriteHeader(status int)      { a.status = status }

// idempotent: Kommt ein Idempotency-Key, den es schon gibt, antwortet kurz
// mit der gespeicherten Antwort, statt die Anfrage noch einmal auszuführen.
func idempotent(next http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        schluessel := r.Header.Get("Idempotency-Key")
        if schluessel == "" {
            next(w, r)
            return
        }
        if len(schluessel) > 200 {
            http.Error(w, "Idempotency-Key zu lang", http.StatusBadRequest)
            return
        }
        body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
        if err != nil {
            http.Error(w, "Body nicht lesbar", http.StatusBadRequest)
            return
        }
        hash := sha256.Sum256(body)
        ctx := r.Context()
        tx, err := db.Begin(ctx)
        if err != nil {
            http.Error(w, "Datenbankfehler", http.StatusServiceUnavailable)
            return
        }
        defer tx.Rollback(ctx) // ohne Commit gibt es den Schlüssel nicht
        // Läuft eine Anfrage mit demselben Schlüssel, wartet das INSERT auf ihr Ende.
        tag, err := tx.Exec(ctx, `INSERT INTO idempotenz (schluessel, anfrage)
            VALUES ($1, $2) ON CONFLICT (schluessel) DO NOTHING`, schluessel, hash[:])
        if err != nil {
            log.Printf("idempotenz: %v", err)
            http.Error(w, "Datenbankfehler", http.StatusServiceUnavailable)
            return
        }
        if tag.RowsAffected() == 0 { // Schlüssel schon benutzt
            var anfrage, antwort []byte
            var status int
            err := tx.QueryRow(ctx, `SELECT anfrage, status, antwort FROM idempotenz
                WHERE schluessel = $1`, schluessel).Scan(&anfrage, &status, &antwort)
            if err != nil {
                http.Error(w, "Datenbankfehler", http.StatusServiceUnavailable)
                return
            }
            if !bytes.Equal(anfrage, hash[:]) {
                http.Error(w, "Idempotency-Key gehört zu einer anderen Anfrage",
                    http.StatusUnprocessableEntity)
                return
            }
            if status < 300 {
                w.Header().Set("Content-Type", "application/json")
            }
            w.Header().Set("Idempotent-Replayed", "true")
            w.WriteHeader(status)
            w.Write(antwort)
            return
        }
        a := &aufnahme{header: w.Header(), status: http.StatusOK}
        r.Body = io.NopCloser(bytes.NewReader(body))
        next(a, r)
        // Serverfehler nicht speichern: Ein neuer Versuch soll es neu probieren.
        if a.status < 500 {
            _, err = tx.Exec(ctx, `UPDATE idempotenz SET status = $2, antwort = $3
                WHERE schluessel = $1`, schluessel, a.status, a.body.Bytes())
            if err == nil {
                err = tx.Commit(ctx)
            }
            if err != nil {
                log.Printf("idempotenz: %v", err)
            }
        }
        w.WriteHeader(a.status)
        w.Write(a.body.Bytes())
    }
}
EOF
perl -pi -e 's/"POST \/api\/links", anlegen\)/"POST \/api\/links", idempotent(anlegen))/' main.go
diff /tmp/main.go.alt main.go
go vet . && go build -o kurz . && echo gebaut

Expected:

138c138
<   mux.HandleFunc("POST /api/links", anlegen)
---
>   mux.HandleFunc("POST /api/links", idempotent(anlegen))
gebaut

Without the header everything works as before. Roll out with the loop from Drill 1 (only the second part, the pause stays set), then the experiment from Drill 1 with a key:

# on s1
cd ~/sd/tag11
U=https://example.org/tag11/mit-schluessel
K=bestellung-4711
curl -s -m 0.25 -X POST -H "Idempotency-Key: $K" localhost/api/links -d "{\"url\":\"$U\"}"; echo "rc=$?"
curl -s -i -X POST -H "Idempotency-Key: $K" localhost/api/links -d "{\"url\":\"$U\"}" | grep -iE '^HTTP|replayed|^\{'
sleep 1
psql -h s3 -U kurz -d kurz -c "select code, angelegt::time(3) from links where url = '$U'"
curl -s -i -X POST -H "Idempotency-Key: $K" localhost/api/links -d '{"url":"https://example.org/etwas-anderes"}' | grep -E '^HTTP|Idempotency'

Expected:

rc=28
HTTP/1.1 201 Created
idempotent-replayed: true
{"code":"ya6U7PE","url":"https://example.org/tag11/mit-schluessel"}
  code   |  angelegt
---------+-------------
 ya6U7PE | 19:14:06.48
(1 row)

HTTP/1.1 422 Unprocessable Entity
Idempotency-Key gehört zu einer anderen Anfrage

The second attempt came while the first was still stuck in its pause. Its INSERT waited until the first was done and then got its response: 201 with the same code, marked as a repetition. There is one link in the table. Now the load test from Drill 2 with a key, once with immediate retry, once with backoff:

# on s1
k6 run -q -e LAUF=schluessel -e SCHLUESSEL=1 wieder.js 2>&1 | grep -E 'geschafft|aufgegeben|http_reqs\.'
sleep 1; doppelt schluessel
k6 run -q -e LAUF=beides -e SCHLUESSEL=1 -e MODUS=backoff wieder.js 2>&1 | grep -E 'geschafft|aufgegeben|http_reqs\.'
sleep 1; doppelt beides

Expected:

    geschafft......................: 600    19.820944/s
    http_reqs......................: 1202   39.707958/s
600 Zeilen, 600 Adressen
    geschafft......................: 601    19.796649/s
    http_reqs......................: 1202   39.593298/s
601 Zeilen, 601 Adressen
Client Requests Links duplicated
retry immediately 1800 1200 600
with backoff 1484 883 282
with key 1202 600 0
with key and backoff 1202 601 0

No more duplicates, and the number of requests drops too: the second attempt waits for the first and gets its response, instead of running into the timeout itself.

What does the key cost in normal operation? Remove the pause, then 300 creations per second with a generous timeout, without and with a key:

# on s1
for s in s1 s2; do
  ssh $s "sudo rm /etc/systemd/system/kurz.service.d/verzoegerung.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
for k in 0 1; do
  k6 run -q -e LAUF=kosten$k -e SCHLUESSEL=$k -e RATE=300 -e TIMEOUT=10s wieder.js 2>&1 | grep -E 'geschafft|http_req_duration\.'
done

Expected:

    geschafft......................: 8969   298.906846/s
    http_req_duration..............: avg=10.87ms min=2.48ms med=6.14ms max=468.98ms p(90)=11.35ms p(95)=15.13ms
    geschafft......................: 2253   44.313261/s
    http_req_duration..............: avg=4.71s   min=8.37ms med=40.63ms max=10s      p(90)=10s     p(95)=10s

With a key, kurz collapses: 2253 instead of 9000 operations, p95 at 10 seconds, the timeout. The log shows what the requests died of:

# on s1
journalctl -u kurz --since "-3min" -o cat | sort | uniq -c | sort -rn | head -3

Expected:

     11 2026/11/23 19:17:09 anlegen: context canceled
     11 2026/11/23 19:16:49 anlegen: context canceled
     10 2026/11/23 19:16:59 anlegen: context canceled

anlegen never got a connection. Every request with a key holds one connection for its transaction and needs a second one from the same pool for sucheURL and the INSERT. The pool has 16 connections per instance (Day 7). If 16 requests are in their transaction at the same time, each waits for a second connection that only one of the others could release. None gets any further until the client gives up. That is a deadlock in the connection pool, and at 20 requests per second in Drill 3 it just went unnoticed.

Save your progress? Sign up for free

Drill 4: One Transaction for Everything

The fix removes two weaknesses at once: everything a request with a key does on db runs through the same transaction. Then it needs only one connection, and link and key are stored together or not at all. The transaction travels along in the request’s context. For this, anlegen moves into a file of its own and gets two more changes:

  • The INSERT uses ON CONFLICT (code) DO NOTHING instead of catching the error 23505. An error in a transaction aborts it, and the next attempt with a new code would then be lost too.
  • If sucheURL fails with a real error, anlegen creates nothing but answers 503. Until now every error counted as “address unknown”. That is exactly how the 118 duplicates came about on Day 9, when a shard was missing.
# on s1
cd ~/kurz && mkdir -p /tmp/vor4 && cp *.go /tmp/vor4/
perl -0pi -e 's/func anlegen\(.*?\n\}\n\n//s' main.go
perl -ni -e 'print unless /^\t"(encoding\/json|net\/url)"$/ || /^\t"github.com\/jackc\/pgx\/v5\/pgconn"$/' main.go
cat > anlegen.go <<'EOF'
package main

import (
    "context"
    "encoding/json"
    "errors"
    "log"
    "net/http"
    "net/url"
    "time"

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

// ausfuehrer: ein Pool oder eine laufende Transaktion, beide können Exec und QueryRow.
type ausfuehrer interface {
    Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
    QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
}

type txSchluessel struct{}

// verbindung: Hält die Anfrage schon eine Transaktion auf db (Idempotency-Key),
// läuft alles auf db über sie. Sonst nimmt sie eine freie Verbindung aus dem Pool.
func verbindung(ctx context.Context, p *pgxpool.Pool) ausfuehrer {
    if tx, ok := ctx.Value(txSchluessel{}).(pgx.Tx); ok && p == db {
        return tx
    }
    return p
}

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
    }
    ctx := r.Context()
    // Gibt es die Adresse schon, liefert kurz den vorhandenen Code statt eines neuen
    vorhanden, err := sucheURL(ctx, in.URL)
    if err == nil {
        w.Header().Set("Content-Type", "application/json")
        json.NewEncoder(w).Encode(map[string]string{"code": vorhanden, "url": in.URL})
        return
    }
    if !errors.Is(err, pgx.ErrNoRows) { // unklar, ob es sie gibt: lieber nichts anlegen
        log.Printf("anlegen: %v", err)
        http.Error(w, "Datenbankfehler", http.StatusServiceUnavailable)
        return
    }
    time.Sleep(verzoegerung)
    for versuch := 0; versuch < 3; versuch++ {
        code := neuerCode()
        // ON CONFLICT statt Fehler 23505: Ein Fehler bräche die Transaktion ab.
        tag, err := verbindung(ctx, shards[shardFuer(code)]).Exec(ctx,
            `INSERT INTO links (code, url) VALUES ($1, $2)
            ON CONFLICT (code) DO NOTHING`, code, in.URL)
        if err != nil {
            log.Printf("anlegen: %v", err)
            http.Error(w, "Datenbankfehler", http.StatusServiceUnavailable)
            return
        }
        if tag.RowsAffected() == 0 {
            continue // Code schon vergeben: neuer Versuch
        }
        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)
}
EOF
perl -pi -e 's/^(\t\terr := )s\.QueryRow\(ctx, (".*?"), url\)/$1verbindung(ctx, s).QueryRow(ctx,\n\t\t\t$2, url)/' shards.go
perl -0pi -e 's/\t\tnext\(a, r\)\n/\t\tnext(a, r.WithContext(context.WithValue(ctx, txSchluessel{}, tx)))\n/; s/import \(\n\t"bytes"\n/import (\n\t"bytes"\n\t"context"\n/' idempotenz.go
diff /tmp/vor4/shards.go shards.go; diff /tmp/vor4/idempotenz.go idempotenz.go
go vet . && go build -o kurz . && echo gebaut

Expected:

40c40,41
<       err := s.QueryRow(ctx, "SELECT code FROM links WHERE url = $1 LIMIT 1", url).Scan(&code)
---
>       err := verbindung(ctx, s).QueryRow(ctx,
>           "SELECT code FROM links WHERE url = $1 LIMIT 1", url).Scan(&code)
4a5
>   "context"
80c81
<       next(a, r)
---
>       next(a, r.WithContext(context.WithValue(ctx, txSchluessel{}, tx)))
gebaut

In the process, main.go has lost anlegen and three imports that only anlegen needed. With shards, the shared transaction only applies to links on db. A link on another shard is written over that shard’s own connection, so key and link are then no longer atomic together. More on that in the Enterprise note. Roll out with the loop from Drill 1, then the same measurement again:

# on s1
cd ~/sd/tag11
for k in 0 1; do
  k6 run -q -e LAUF=kosten3-$k -e SCHLUESSEL=$k -e RATE=300 -e TIMEOUT=10s wieder.js 2>&1 | grep -E 'geschafft|http_req_duration\.'
done

Expected (second run; the first, right after the rollout, scattered more):

    geschafft......................: 8966   298.807739/s
    http_req_duration..............: avg=9.22ms min=2.47ms med=5.87ms max=399.02ms p(90)=9.95ms  p(95)=12.35ms
    geschafft......................: 9001   299.893365/s
    http_req_duration..............: avg=17.86ms min=6.07ms med=15.33ms max=114.07ms p(90)=27.89ms p(95)=33.09ms

All 9001 operations with a key succeed. The key costs 9.5 ms more in the median and just under 21 ms more in the p95: four additional round trips to the database (BEGIN, INSERT, UPDATE, COMMIT), all via PgBouncer. In return, every creation can be repeated any number of times. That is why the key is offered to the client and not made mandatory.

Save your progress? Sign up for free

Drill 5: Message ID When Sending

Now the clicks. A message can be duplicated at two points: when sending, if the sender publishes again after a timeout, and when processing, as on Day 10. Against the first, JetStream has a built-in brake: if a message carries the header Nats-Msg-Id, the stream stores the same ID only once within the duplicate window.

# on s1
psql -h s3 -U kurz -d kurz -tAc "select anzahl from klicks where code = 'c170720'"
nats stream info KLICKS --json | jq '.config.duplicate_window / 1e9'
for i in 1 2 3; do nats pub --jetstream -H Nats-Msg-Id:klick-0815 klicks c170720; done
sleep 2
psql -h s3 -U kurz -d kurz -tAc "select anzahl from klicks where code = 'c170720'"

Expected (your numbers will differ):

1012
120
19:20:49 Published 7 bytes to "klicks"
19:20:49 Stored in Stream: KLICKS Sequence: 208,906
19:20:49 Published 7 bytes to "klicks"
19:20:49 Stored in Stream: KLICKS Sequence: 208,906 Duplicate: true
19:20:49 Published 7 bytes to "klicks"
19:20:49 Stored in Stream: KLICKS Sequence: 208,906 Duplicate: true
1013

Published three times, stored once, counted once. --jetstream waits for the server’s acknowledgment, which reports Duplicate: true. The window is 120 seconds: a repetition must not take longer than that, otherwise it counts as a new message.

kurz does not need this today: it publishes with core publish and never retries (Day 10, Drill 6). Anyone who waits for the acknowledgment and resends after a timeout must send the ID along, and the same one with every attempt. A new ID per attempt turns every repetition into a new message.

Save your progress? Sign up for free

Drill 6: Counting Exactly Once

The second point is the worker: commit succeeded, acknowledgment lost, JetStream delivers again after 30 seconds. No setting in NATS helps against that. The database has to remember which messages it has already counted, and in the same statement as the counting. Every message has a sequence number in the stream that does not change on redelivery. That is the key:

# on s1
psql -h s3 -U kurz -d kurz -c "CREATE TABLE klicks_verarbeitet (seq bigint PRIMARY KEY)"
cd ~/zaehler && cp main.go /tmp/zaehler.alt
perl -0pi -e 's/Version 2: Pull-Consumer, ein Statement pro Batch, Bestätigung erst nach dem Commit\./Version 3: wie Version 2, aber jede Nachricht zählt genau einmal./' main.go
perl -0pi -e 's/\/\/ Ein Statement für den ganzen Batch:.*?excluded\.anzahl`\n/\/\/ Ein Statement für den ganzen Batch. Es merkt sich jede Sequenznummer und zählt nur\n\/\/ Nachrichten, deren Nummer neu ist. Beides gelingt zusammen oder gar nicht.\nconst zaehlen = `WITH neu AS (\n\tINSERT INTO klicks_verarbeitet (seq) SELECT unnest(\$1::bigint[])\n\tON CONFLICT DO NOTHING RETURNING seq)\nINSERT INTO klicks (code, anzahl)\n\tSELECT k.code, count(*) FROM unnest(\$1::bigint[], \$2::text[]) AS k(seq, code)\n\tJOIN neu USING (seq) GROUP BY k.code\n\tON CONFLICT (code) DO UPDATE SET anzahl = klicks.anzahl + excluded.anzahl`\n/s' main.go
perl -0pi -e 's/\t\tvar codes \[\]string\n/\t\tvar seqs []int64\n\t\tvar codes []string\n/; s/\t\t\tcodes = append\(codes, string\(m.Data\(\)\)\)\n/\t\t\tmeta, err := m.Metadata()\n\t\t\tif err != nil {\n\t\t\t\tcontinue \/\/ ohne Sequenznummer nicht zählen: kommt nach AckWait wieder\n\t\t\t}\n\t\t\tseqs = append(seqs, int64(meta.Sequence.Stream))\n\t\t\tcodes = append(codes, string(m.Data()))\n/; s/db.Exec\(ctx, upsert, codes\)/db.Exec(ctx, zaehlen, seqs, codes)/' main.go
perl -0pi -e 's/(\t\t\tlog.Printf\("gezählt %d", gezaehlt\)\n)/$1\t\t\t\/\/ Bis ack_floor ist alles bestätigt und kommt nie wieder: Nummern wegräumen\n\t\t\tif info, err := cons.Info(ctx); err == nil {\n\t\t\t\tdb.Exec(ctx, "DELETE FROM klicks_verarbeitet WHERE seq <= \$1",\n\t\t\t\t\tint64(info.AckFloor.Stream))\n\t\t\t}\n/' main.go
diff /tmp/zaehler.alt main.go
go vet . && go build -o zaehler . && echo gebaut

Expected:

CREATE TABLE
2c2
< // Version 2: Pull-Consumer, ein Statement pro Batch, Bestätigung erst nach dem Commit.
---
> // Version 3: wie Version 2, aber jede Nachricht zählt genau einmal.
24,26c24,31
< // 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
---
> // Ein Statement für den ganzen Batch. Es merkt sich jede Sequenznummer und zählt nur
> // Nachrichten, deren Nummer neu ist. Beides gelingt zusammen oder gar nicht.
> const zaehlen = `WITH neu AS (
>   INSERT INTO klicks_verarbeitet (seq) SELECT unnest($1::bigint[])
>   ON CONFLICT DO NOTHING RETURNING seq)
> INSERT INTO klicks (code, anzahl)
>   SELECT k.code, count(*) FROM unnest($1::bigint[], $2::text[]) AS k(seq, code)
>   JOIN neu USING (seq) GROUP BY k.code
62a68
>       var seqs []int64
65a72,76
>           meta, err := m.Metadata()
>           if err != nil {
>               continue // ohne Sequenznummer nicht zählen: kommt nach AckWait wieder
>           }
>           seqs = append(seqs, int64(meta.Sequence.Stream))
72c83
<       if _, err := db.Exec(ctx, upsert, codes); err != nil {
---
>       if _, err := db.Exec(ctx, zaehlen, seqs, codes); err != nil {
82a94,98
>           // Bis ack_floor ist alles bestätigt und kommt nie wieder: Nummern wegräumen
>           if info, err := cons.Info(ctx); err == nil {
>               db.Exec(ctx, "DELETE FROM klicks_verarbeitet WHERE seq <= $1",
>                   int64(info.AckFloor.Stream))
>           }
gebaut

The CTE neu inserts all numbers of the batch and returns only those that were really new. Only their codes are counted. Because both are one statement, there is no moment in which something is counted but not remembered. The table does not grow without end: everything up to ack_floor has been ticked off by JetStream as acknowledged and will never be delivered again, so the worker may delete these numbers.

First the speed, as on Day 10 with a 30-second backlog:

# on s1
scp -q zaehler s2:/tmp/zaehler && ssh s2 "sudo install /tmp/zaehler /usr/local/bin/zaehler"
cd ~/sd/tag11 && cp ~/sd/tag10/klick.js ~/sd/tag10/codes.txt .
ssh s2 "sudo systemctl stop zaehler"
psql -h s3 -U kurz -d kurz -qc "TRUNCATE klicks, klicks_verarbeitet"
k6 run -q klick.js | grep -E 'checks_succeeded'
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% 44458 out of 44458
aufgeholt in 7 s
gezählt: 44458

7 instead of 6 seconds: remembering costs hardly anything, because it stays one statement per batch. Now the crash from Day 10, Drill 7, with a pause between commit and acknowledgment. New is the look at the consumer before and after: consumer_seq counts every delivery, stream_seq every message.

# 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"
stand() { nats consumer info KLICKS zaehler --json | jq -c '.delivered | {consumer_seq, stream_seq}'; }
stand
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 50
until [ "$(nats consumer info KLICKS zaehler --json | jq '.num_pending + .num_ack_pending')" = 0 ]; do sleep 1; done
stand
psql -h s3 -U kurz -d kurz -tAc "select 'gezählt: ' || sum(anzahl) from klicks"
ssh s2 "sudo rm /etc/systemd/system/zaehler.service.d/pause.conf && sudo systemctl daemon-reload && sudo systemctl restart zaehler"

Expected:

{"consumer_seq":250011,"stream_seq":258364}
    checks_succeeded...: 100.00% 5001 out of 5001
19:24:04 zaehler abgeschossen
{"consumer_seq":255512,"stream_seq":263365}
gezählt: 5001

The stream has grown by 5001 messages, the consumer has delivered 5501: one batch of 500 came twice, as on Day 10. Still, exactly 5001 are counted. The second delivery hit numbers that were already in klicks_verarbeitet and changed nothing.

Does the table stay small? Under load the worker cleans up every five seconds:

# on s1
k6 run -q -e DAUER=20s klick.js | grep -E 'checks_succeeded'
sleep 2
psql -h s3 -U kurz -d kurz -tAc "select 'noch gemerkt: ' || count(*) from klicks_verarbeitet"

Expected (numbers fluctuate):

    checks_succeeded...: 100.00% 29093 out of 29093
noch gemerkt: 5593

Of around 78,500 numbers since emptying, a good 5000 are left, those of the last few seconds.

Save your progress? Sign up for free

Exercise: Speed drills

  1. How many idempotency keys are stored, and when is the oldest from? Target time: 1 min
  2. Delete all keys older than 24 hours. Target time: 1 min
  3. How many sequence numbers does the counter currently remember, and how long is the stream’s duplicate window in seconds? Target time: 1 min

Solution

# on s1
psql -h s3 -U kurz -d kurz -tAc "select count(*), min(angelegt)::time(0) from idempotenz"
psql -h s3 -U kurz -d kurz -c "DELETE FROM idempotenz WHERE angelegt < now() - interval '24 hours'"
psql -h s3 -U kurz -d kurz -tAc "select count(*) from klicks_verarbeitet"
nats stream info KLICKS --json | jq '.config.duplicate_window / 1e9'

Expected (your numbers will differ; today no key is a day old yet):

21497|19:14:06
DELETE 0
5593
120

How long a key is valid is a promise to the client. 24 hours is common. After that, the same request creates a new link. In operation, a timer does the deleting, not you.

Save your progress? Sign up for free

Checkpoint

The same request twice with the same key:

# on s1
for i in 1 2; do curl -s -i -X POST -H 'Idempotency-Key: kontrolle-1' localhost/api/links -d '{"url":"https://example.org/kontrolle"}' | grep -iE '^HTTP|replayed|^\{'; done

Expected: 201 twice with the same code, the second time additionally idempotent-replayed: true.

HTTP/1.1 201 Created
{"code":"qNNNnwc","url":"https://example.org/kontrolle"}
HTTP/1.1 201 Created
idempotent-replayed: true
{"code":"qNNNnwc","url":"https://example.org/kontrolle"}
# on s1
psql -h s3 -U kurz -d kurz -tAc "select count(*) from links where url = 'https://example.org/kontrolle'"

Expected: 1

# on s1
curl -s -o /dev/null -w '%{http_code}\n' -X POST -H 'Idempotency-Key: kontrolle-1' localhost/api/links -d '{"url":"https://example.org/kontrolle-anders"}'

Expected: 422

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

Expected: 0

Challenge

Two customers create the same address at the same moment, each with their own idempotency key. How many links are created? Make sure that a new address gets only one code, no matter how many requests arrive at the same time. The existing codes must not disappear: they are printed on posters.

Hint: A key only prevents repetitions of the same request. Against different requests for the same thing, only a rule in the database helps. Create the unique index only for rows from today on.

Solution

Twenty concurrent requests with different keys:

# on s1
U=https://example.org/tag11/gleichzeitig-1
seq 20 | xargs -P 20 -I{} curl -s -o /dev/null -w '%{http_code}\n' -X POST -H "Idempotency-Key: client-{}" localhost/api/links -d "{\"url\":\"$U\"}" | sort | uniq -c
psql -h s3 -U kurz -d kurz -tAc "select count(*) from links where url = '$U'"

Expected (distribution fluctuates):

     17 200
      3 201
3

Three codes for one address. A unique index on url would prevent that, but it cannot be created:

# on s1
psql -h s3 -U kurz -d kurz -c "CREATE UNIQUE INDEX links_url_eindeutig ON links (url)"

Expected:

ERROR:  could not create unique index "links_url_eindeutig"
DETAIL:  Key (url)=(https://example.org/neu/10-120) is duplicated.

The old duplicates come from the load tests of the last few days, and any of their codes may be in use somewhere. So the rule applies from now on: a partial index only for rows from a cutoff date, created without a lock (CONCURRENTLY). Then anlegen has to cope with the conflict: ON CONFLICT DO NOTHING without a column catches every unique index, and with 0 rows anlegen checks once more whether the address was just created by another request.

# on s1
STICHTAG=$(date -u +%FT%TZ); echo $STICHTAG
time psql -h s3 -U kurz -d kurz -c "CREATE UNIQUE INDEX CONCURRENTLY links_url_neu ON links (url) WHERE angelegt >= '$STICHTAG'"
cd ~/kurz && cp anlegen.go /tmp/anlegen.alt
perl -0pi -e 's/ON CONFLICT \(code\) DO NOTHING/ON CONFLICT DO NOTHING/; s/\t\tif tag.RowsAffected\(\) == 0 \{\n\t\t\tcontinue \/\/ Code schon vergeben: neuer Versuch\n\t\t\}\n/\t\tif tag.RowsAffected() == 0 {\n\t\t\t\/\/ Code vergeben oder die Adresse kam gerade von einer anderen Anfrage\n\t\t\tif vorhanden, err := sucheURL(ctx, in.URL); err == nil {\n\t\t\t\tw.Header().Set("Content-Type", "application\/json")\n\t\t\t\tjson.NewEncoder(w).Encode(\n\t\t\t\t\tmap[string]string{"code": vorhanden, "url": in.URL})\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n/' anlegen.go
diff /tmp/anlegen.alt anlegen.go
go vet . && go build -o kurz . && echo gebaut

Expected:

2026-11-23T19:26:01Z
CREATE INDEX

real    0m1.131s
user    0m0.149s
sys 0m0.036s
66c66
<           ON CONFLICT (code) DO NOTHING`, code, in.URL)
---
>           ON CONFLICT DO NOTHING`, code, in.URL)
73c73,80
<           continue // Code schon vergeben: neuer Versuch
---
>           // Code vergeben oder die Adresse kam gerade von einer anderen Anfrage
>           if vorhanden, err := sucheURL(ctx, in.URL); err == nil {
>               w.Header().Set("Content-Type", "application/json")
>               json.NewEncoder(w).Encode(
>                   map[string]string{"code": vorhanden, "url": in.URL})
>               return
>           }
>           continue
gebaut

Roll out with the loop from Drill 1, then the same experiment, once with and once without a key:

# on s1
U=https://example.org/tag11/gleichzeitig-2
seq 20 | xargs -P 20 -I{} curl -s -o /dev/null -w '%{http_code}\n' -X POST -H "Idempotency-Key: client2-{}" localhost/api/links -d "{\"url\":\"$U\"}" | sort | uniq -c
psql -h s3 -U kurz -d kurz -tAc "select count(*) from links where url = '$U'"
U=https://example.org/tag11/gleichzeitig-3
seq 20 | xargs -P 20 -I{} curl -s -o /dev/null -w '%{http_code}\n' -X POST localhost/api/links -d "{\"url\":\"$U\"}" | sort | uniq -c
psql -h s3 -U kurz -d kurz -tAc "select count(*) from links where url = '$U'"

Expected:

     19 200
      1 201
1
     19 200
      1 201
1

One request creates, nineteen get its code. The index is the actual guarantee; the check with sucheURL before it only saves work. That holds in general: checking and then acting never protects against a concurrent second party. A unique rule in the database does.

Save your progress? Sign up for free

Clean-up

Nothing to tear down. KURZ_VERZOEGERUNG is no longer set, kurz accepts an Idempotency-Key from now on, new addresses have a unique index, and zaehler counts in version 3. Check that no drop-ins from today are left over:

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

Expected:

cache.conf
cpu.conf
klicks.conf
lesen.conf
pool.conf
/etc/systemd/system/kurz.service.d/:
cache.conf
cpu.conf
klicks.conf
lesen.conf
pool.conf

/etc/systemd/system/zaehler.service.d/:

Interview note

  • “What happens when the client retries after a timeout?” Show the gap: the server may be done, only the response did not arrive. Then the idempotency key: the client generates it per operation, the server stores it with the response in the same transaction as the change.
  • Retries done right: a limited number of attempts, exponential backoff with jitter, only for errors worth retrying (timeout, 503), never for 400 or 422. Backoff protects the server, the key protects the data.
  • Exactly-once: does not exist between two systems as delivery, only as effect. Deliver at least once and recognize at the receiver, by an ID, what is already done. The ID must land in the same commit as the change.

Enterprise note

  • Many payment and cloud APIs work with exactly this header. Typical promises: keys are valid for 24 hours, the same key with a different body is an error, server errors are not stored. As a standard for HTTP, the header is an IETF draft.
  • If the data lives on several databases (shards, microservices), one transaction is no longer enough. Then the key belongs on the same database as the change, or you work with an outbox table (Day 10) and idempotent receivers on each side.
  • If the stream is recreated, the sequence numbers start again at 1. Then klicks_verarbeitet must be emptied too, otherwise new messages count as already counted. More robust is a separate ID per click that kurz assigns and sends along as Nats-Msg-Id.

Contents

More