Tag 9: Upstreams und Load Balancing
Ziel: Last auf zwei Instanzen von notes-api verteilen, kranke Instanzen automatisch herausnehmen und eine neue Version per Canary an zehn Prozent der Anfragen geben. · Dauer: ca. 60 min · Voraussetzung: Tag 8
Briefing
- Ein Upstream ist ein virtueller Hostname mit
mehreren Targets (
host:portmit Gewicht). Ein Service zeigt mithost: notes-upauf ihn statt auf einen Container. - Der Standard-Algorithmus ist
round-robin, gewichtet nachweight. - Aktive Health Checks fragen jedes Target regelmäßig ab; passive werten echte Antworten aus. Ein krankes Target bekommt keine Anfragen mehr.
- Ein Canary ist nur eine Frage der Gewichte: 90 zu 10.
┌─► notes-api:8080 (0.2.0, weight 90)
Service notes ─► notes-up┤
host: notes-up └─► notes-api-2:8080 (0.3.0, weight 10)
Health Check: GET /healthz alle 2 s
Drill 1: Eine zweite Instanz
Die zweite Instanz bekommt eine neue Version, damit du an
/version siehst, wer antwortet:
source ~/kong-lab/setup/env.sh
mkdir -p ~/kong-lab/tag09 && cd ~/kong-lab/code/notes/notes-api
docker build -q --build-arg VERSION=0.3.0 -t notes-api:0.3.0 .
cd ~/kong-lab/code/backend
grep -A2 'notes-api-2:' compose.yaml
docker compose --profile lb up -d --wait
docker compose ps --format "table {{.Service}}\t{{.Image}}\t{{.Status}}"Erwartet (gekürzt):
sha256:2b4915ed17c7…
notes-api-2: # zweite Instanz, neue Version, für Load Balancing (Tag 9)
image: notes-api:0.3.0
environment: *api-env
Container backend-notes-api-2-1 Healthy
SERVICE IMAGE STATUS
db postgres:18.6-alpine Up About an hour (healthy)
echo ghcr.io/mccutchen/go-httpbin:2.26.0 Up About an hour
notes-api notes-api:0.2.0 Up About an hour (healthy)
notes-api-2 notes-api:0.3.0 Up 2 seconds (healthy)
Das Profil lb startet notes-api-2
zusätzlich. Beide nutzen dieselbe Datenbank.
Fortschritt speichern? Kostenlos registrieren
Drill 2: Ein Upstream für beide
cd ~/kong-lab/tag09
cp ~/kong-lab/code/tag09/*.yaml .
grep -v '^#' upstream.yaml
deck file merge ~/kong-lab/kong/kong.yaml upstream.yaml -o ~/kong-lab/kong/kong.yaml
SEL='$.services[?(@.name=="notes" || @.name=="notes-version")]'
deck file patch -s ~/kong-lab/kong/kong.yaml --selector "$SEL" \
--value 'host:"notes-up"' -o ~/kong-lab/kong/kong.yaml
deck gateway diff ~/kong-lab/kong/kong.yaml 2>/dev/null \
| grep -E '^(creating|updating)|"host"'
ksync 2>/dev/null | tail -3Erwartet (gekürzt):
_format_version: "3.0"
upstreams:
- name: notes-up
algorithm: round-robin
targets:
- target: notes-api:8080
weight: 100
- target: notes-api-2:8080
weight: 100
updating service notes {
- "host": "notes-api",
+ "host": "notes-up",
updating service notes-version {
- "host": "notes-api",
+ "host": "notes-up",
creating upstream notes-up
creating target notes-api:8080 for upstream ef91f37a-…
creating target notes-api-2:8080 for upstream ef91f37a-…
Created: 3
Updated: 2
Deleted: 0
Die Services ändern nur ihren Host. Kong merkt, dass
notes-up ein Upstream ist, und löst ihn nicht per DNS auf,
sondern über die Targets.
Zähl, wer antwortet. /api/v1/version eignet sich, weil
die Route kein Rate Limit hat:
zaehle() { for i in $(seq 1 ${1:-20}); do curl -s $PROXY/api/v1/version; done \
| sort | uniq -c; }
zaehle 20
curl -s $ADMIN/upstreams/notes-up/health | jq -r '.data[] | [.target, .health] | @tsv'Erwartet:
10 0.2.0
10 0.3.0
notes-api-2:8080 HEALTHCHECKS_OFF
notes-api:8080 HEALTHCHECKS_OFF
Genau abwechselnd. HEALTHCHECKS_OFF heißt: Kong prüft
noch nicht, ob die Targets leben.
Fortschritt speichern? Kostenlos registrieren
Drill 3: Health Checks
health.yaml ist eine Patch-Datei für decK: Kong soll
alle zwei Sekunden /healthz fragen und ein Target nach zwei
Fehlern herausnehmen.
grep -v '^#' health.yaml | sed -n '3,16p'
deck file patch -s ~/kong-lab/kong/kong.yaml health.yaml -o ~/kong-lab/kong/kong.yaml
ksync 2>/dev/null | tail -1
curl -s $ADMIN/upstreams/notes-up/health | jq -r '.data[] | [.target, .health] | @tsv'Erwartet:
- selectors:
- $.upstreams[?(@.name=="notes-up")]
values:
healthchecks:
active:
http_path: /healthz
healthy:
interval: 2
successes: 1
unhealthy:
interval: 2
http_failures: 2
tcp_failures: 2
timeouts: 2
Deleted: 0
notes-api-2:8080 HEALTHY
notes-api:8080 HEALTHY
Jetzt fällt eine Instanz aus:
docker compose -f ~/kong-lab/code/backend/compose.yaml stop notes-api-2
sleep 7
curl -s $ADMIN/upstreams/notes-up/health | jq -r '.data[] | [.target, .health] | @tsv'
zaehle 10Erwartet:
Container backend-notes-api-2-1 Stopped
notes-api-2:8080 UNHEALTHY
notes-api:8080 HEALTHY
10 0.2.0
Kein einziger Fehler beim Client: Kong schickt alles an die gesunde Instanz. Und zurück:
docker compose -f ~/kong-lab/code/backend/compose.yaml --profile lb start notes-api-2
sleep 7
curl -s $ADMIN/upstreams/notes-up/health | jq -r '.data[] | [.target, .health] | @tsv'Erwartet:
Container backend-notes-api-2-1 Started
notes-api-2:8080 HEALTHY
notes-api:8080 HEALTHY
/healthz von notes-api prüft auch die Datenbank. Fällt
Postgres aus, melden sich beide Instanzen krank, und Kong antwortet mit
503 (Tag 15).
Fortschritt speichern? Kostenlos registrieren
Drill 4: Canary
Version 0.3.0 soll erst zehn Prozent der Anfragen bekommen:
U='$.upstreams[?(@.name=="notes-up")].targets'
deck file patch -s ~/kong-lab/kong/kong.yaml \
--selector "$U[?(@.target==\"notes-api:8080\")]" \
--value 'weight:90' -o ~/kong-lab/kong/kong.yaml
deck file patch -s ~/kong-lab/kong/kong.yaml \
--selector "$U[?(@.target==\"notes-api-2:8080\")]" \
--value 'weight:10' -o ~/kong-lab/kong/kong.yaml
ksync 2>/dev/null | tail -2
zaehle 100Erwartet:
Updated: 2
Deleted: 0
90 0.2.0
10 0.3.0
Läuft 0.3.0 gut, gehen die Gewichte schrittweise auf 50/50 und 0/100.
Geht etwas schief, ist der Rückweg derselbe Patch mit
weight:0.
Für heute zurück auf gleiche Gewichte, dann festhalten:
for t in notes-api notes-api-2; do
deck file patch -s ~/kong-lab/kong/kong.yaml \
--selector "$U[?(@.target==\"$t:8080\")]" \
--value 'weight:100' -o ~/kong-lab/kong/kong.yaml
done
ksync 2>/dev/null | tail -2
cd ~/kong-lab/kong && git add kong.yaml
git commit -qm "Tag 9: Upstream mit Health Checks"Erwartet:
Updated: 2
Deleted: 0
Fortschritt speichern? Kostenlos registrieren
Drill 5: Die Algorithmen
curl -s $ADMIN/upstreams/notes-up | jq -c '{algorithm, hash_on, slots}'
curl -s $ADMIN/schemas/upstreams | jq -r '.fields[] | select(.algorithm)
| .algorithm.one_of | join(", ")'Erwartet:
{"algorithm":"round-robin","hash_on":"none","slots":10000}
consistent-hashing, least-connections, round-robin, latency
| Algorithmus | Verteilt nach | Typischer Einsatz |
|---|---|---|
round-robin |
Reihum, gewichtet | Standard, gleich starke Instanzen |
least-connections |
wenigsten offenen Verbindungen | lange Anfragen |
latency |
schnellster Antwortzeit | unterschiedlich starke Instanzen |
consistent-hashing |
Hash über Consumer, IP, Header, Cookie | Caches, Sitzungen |
Fortschritt speichern? Kostenlos registrieren
Kontrollpunkt
curl -s $ADMIN/services/notes | jq -r .hostErwartet: Der Service zeigt auf den Upstream.
notes-up
curl -s $ADMIN/upstreams/notes-up/health | jq -r '.data[] | [.target, .health,
.weight] | @tsv'Erwartet: zwei gesunde Targets mit gleichem Gewicht.
notes-api-2:8080 HEALTHY 100
notes-api:8080 HEALTHY 100
for i in $(seq 1 10); do curl -s $PROXY/api/v1/version; done | sort | uniq -cErwartet: halb und halb.
5 0.2.0
5 0.3.0
Challenge
Was sieht ein Client, wenn beide Instanzen ausfallen? Und wie lange dauert es, bis Kong wieder ausliefert, nachdem eine zurück ist?
Hinweis: Beide stoppen, dann eine starten und im Sekundentakt fragen.
Lösung
cd ~/kong-lab/code/backend
docker compose stop notes-api notes-api-2
sleep 7
curl -s -w ' %{http_code}\n' $PROXY/api/v1/version
docker compose start notes-api
until [ "$(curl -s -o /dev/null -w '%{http_code}' $PROXY/api/v1/version)" = 200 ]; do
echo -n '.'; sleep 1
done; echo ' wieder da'
docker compose --profile lb start notes-api-2Erwartet (gekürzt, die Zahl der Punkte schwankt):
Container backend-notes-api-2-1 Stopped
Container backend-notes-api-1 Stopped
{
"message":"failure to get a peer from the ring-balancer",
"request_id":"…"
} 503
Container backend-notes-api-1 Started
... wieder da
Container backend-notes-api-2-1 Started
Ohne gesundes Target antwortet Kong selbst mit 503. Nach dem Start
braucht es einen erfolgreichen Check (successes: 1, alle 2
s) plus die Startzeit der Instanz.
Fortschritt speichern? Kostenlos registrieren
Enterprise-Notiz
- Passive Health Checks
(
healthchecks.passive) werten echte Antworten aus und kosten keine zusätzlichen Anfragen; kombiniert mit aktiven Checks erkennen sie Ausfälle schneller. - Health Checks pro Knoten: Jeder Kong-Knoten prüft selbst. Bei zehn Knoten und Intervall 2 s bekommt jedes Backend fünf Prüfanfragen pro Sekunde.
- Service Discovery: Statt fester Targets kann ein Upstream per DNS-SRV oder über den Ingress Controller (Tag 14) mit den Pods eines Kubernetes-Service befüllt werden.
- Canary mit Regeln (nach Header, Consumer, Prozent
pro Benutzer) bietet das Enterprise-Plugin
canary; OSS bleibt bei Gewichten.