Day 11: Rate limiting and backpressure in the Gateway
Goal: Catch overload at the entrance instead of in the backend: a local limit per Envoy, a global limit per user with its own counter store, and a circuit breaker that rejects early instead of keeping clients waiting – measured with k6 each time, including where the protection brings less than hoped · Duration: approx. 100 min · Prerequisite: Day 10
Briefing
- In the predecessor course, HAProxy counted a limit per source IP. Here Envoy sits at the entrance, and Envoy Gateway knows two kinds of limits: local (each Envoy instance counts on its own) and global (all instances ask a shared rate limit service that counts in Redis or Valkey).
- Backpressure means: whoever cannot cope any more
says so immediately instead of piling up requests. In Envoy that is the
circuit breaker – an upper bound for concurrent and
pending requests per backend. Anything beyond it gets
503immediately. - Everything hangs on a single
BackendTrafficPolicyper route: the retry, timeouts and outlier detection from Day 4 get limits and a circuit breaker added today.
| Term | Meaning |
|---|---|
| Local limit | Token bucket in each Envoy instance, no coordination between instances |
| Global limit | For each request, Envoy asks the envoy-ratelimit
service, which counts in Valkey |
Distinct |
Each distinct value of a header gets its own counter |
| Fail open | If the rate limit service does not respond in time, Envoy lets the request through |
| Circuit breaker | Limits for parallel (maxParallelRequests) and pending
(maxPendingRequests) requests |
At the end of the day, no user may send more than 50 requests per
second, and kurz rejects overload in milliseconds instead
of dragging it out.
Drill 1: Overload without protection
First the baseline via the Gateway: 1000 and 3000 redirects per
second, 40 seconds each. Since Day 10, kurz scales by CPU
via KEDA (2 to 6 Pods).
# on s1
mkdir -p ~/sdk/tag11 && cd ~/sdk/tag11
cp ../tag10/codes.txt ../tag10/klick.js .
for r in 1000 3000; do echo "== $r/s ohne Schutz"
k6 run -q -e ZIEL=http://172.16.0.126 -e RATE=$r -e DAUER=40s klick.js 2>&1 \
| grep -E 'http_req_duration\.|http_req_failed\.|http_reqs\.|dropped' | sed 's/ */ /g'
sleep 20; doneExpected:
== 1000/s ohne Schutz
http_req_duration...: avg=34.01ms min=1.42ms med=18.79ms max=831.55ms p(90)=83.25ms p(95)=114.65ms
http_req_failed.....: 0.00% 0 out of 39709
http_reqs...........: 39709 991.851227/s
dropped_iterations..: 291 7.268597/s
== 3000/s ohne Schutz
http_req_duration...: avg=154.18ms min=1.87ms med=131.16ms max=1.07s p(90)=282.69ms p(95)=344.38ms
http_req_failed.....: 0.00% 0 out of 95881
http_reqs...........: 95881 2392.770435/s
dropped_iterations..: 24124 602.029536/s
(ohne Schutz = without protection.) No errors – but 2400
instead of 3000 per second and a p95 of 344 ms. k6 never even sent the
missing 600 per second, because all 600 virtual users were waiting for
responses. That is exactly what overload looks like when nobody says no:
everything gets slower, for everyone.
For the next measurements you need numbers per status code – a
429 or 503 in 2 ms is something different from
a 302 in 300 ms.
# on s1
cat > status.js <<'EOF'
import http from "k6/http";
import { SharedArray } from "k6/data";
// Weiterleitungen mit Kennzahlen je Statuscode; X-Nutzer optional (NUTZER = Anzahl Nutzer)
const codes = new SharedArray("codes", () => open("./codes.txt").split("\n").filter(Boolean));
const ZIEL = __ENV.ZIEL || "http://localhost:8080";
const NUTZER = Number(__ENV.NUTZER || 0);
export const options = {
scenarios: {
last: {
executor: "constant-arrival-rate",
rate: Number(__ENV.RATE || 1000), timeUnit: "1s",
duration: __ENV.DAUER || "40s",
preAllocatedVUs: 100, maxVUs: 600,
},
},
// Schwellen nur, damit k6 die Werte je Status ausgibt
thresholds: {
"http_reqs{status:302}": ["count>=0"], "http_reqs{status:429}": ["count>=0"],
"http_reqs{status:503}": ["count>=0"],
"http_req_duration{status:302}": ["p(95)>=0"], "http_req_duration{status:429}": ["p(95)>=0"],
"http_req_duration{status:503}": ["p(95)>=0"],
},
};
export default function () {
const code = codes[Math.floor(Math.random() * codes.length)];
const headers = NUTZER ? { "X-Nutzer": `nutzer-${__VU % NUTZER}` } : {};
http.get(`${ZIEL}/${code}`, { redirects: 0, headers });
}
EOF
# Function status: count and p95 per status code from a k6 output
status() { grep -A1 -E '\{status:(302|429|503)\}' "$1" | sed 's/ */ /g' | grep -v '^--' | paste - -; }The script sends redirects and reports metrics per status code; the
optional X-Nutzer header (user) is set when
NUTZER (number of users) is given. The thresholds exist
only so that k6 prints the values per status.
Save your progress? Sign up for free
Drill 2: A local limit
A limit of 600 requests per second for the route kurz.
The obvious way is a second policy:
# on s1
cat > limit-zweite.yaml <<'EOF'
apiVersion: gateway.envoyproxy.io/v1alpha1
kind: BackendTrafficPolicy
metadata:
name: kurz-limit
namespace: kurz
spec:
targetRefs:
- group: gateway.networking.k8s.io
kind: HTTPRoute
name: kurz
rateLimit:
local:
rules:
- limit:
requests: 600
unit: Second
EOF
kubectl apply -f limit-zweite.yaml
kubectl -n kurz get btp kurz-limit -o jsonpath='{range .status.ancestors[0].conditions[*]}{.type}={.status} {.reason}: {.message}{"\n"}{end}'Expected:
backendtrafficpolicy.gateway.envoyproxy.io/kurz-limit created
Accepted=False Conflicted: Unable to target HTTPRoute kurz, another BackendTrafficPolicy has already attached to it
kubectl apply reports success, but the policy has no
effect anywhere – you only see that in the status. Per route, exactly
one BackendTrafficPolicy applies; the older one wins. So
the limit goes into the policy from Day 4:
# on s1
kubectl -n kurz delete btp kurz-limit
# Policy from Day 4 plus local limit
cp ../tag04/retry.yaml schutz.yaml
cat >> schutz.yaml <<'EOF'
rateLimit:
local:
rules:
- limit:
requests: 600
unit: Second
EOF
kubectl apply -f schutz.yaml
# 2000/s: how many get through, how fast are the rejected ones?
k6 run -q -e ZIEL=http://172.16.0.126 -e RATE=2000 status.js > k6-lokal.txt 2>&1; status k6-lokal.txtExpected:
backendtrafficpolicy.gateway.envoyproxy.io/kurz-retry configured
http_req_duration{status:302} ✓ 'p(95)>=0' p(95)=176.5ms
http_req_duration{status:429} ✓ 'p(95)>=0' p(95)=90.44ms
http_req_duration{status:503} ✓ 'p(95)>=0' p(95)=0s
http_reqs{status:302} ✓ 'count>=0' count=49158
http_reqs{status:429} ✓ 'count>=0' count=28725
http_reqs{status:503} ✓ 'count>=0' count=0
49,158 redirects in 40 seconds are 1229 per second –
not 600. The local limit applies per Envoy instance, and since Day 3 two
are running (EnvoyProxy zwei-zonen). If you limit locally,
you have to divide the limit by the number of instances – and it changes
as soon as someone changes the replicas.
And the rejected requests? p95 90 ms for a response that Envoy generates itself. Saying no also costs CPU, and at 2000 per second the lab’s nodes are fully loaded (Day 9).
Save your progress? Sign up for free
Drill 3: A global limit per user
A fair limit is per user, counted across all instances. Here the user
ID comes from a header X-Nutzer – in real operation it
would be the ID from a token or the client IP. (Envoy does not see the
source IP in this lab: ServiceLB translates it, Day 3.)
The global limit needs the envoy-ratelimit service and a
counter store. A single Valkey without persistence is enough; counters
lost on a restart do not matter for one-second windows.
# on s1
cat > ratelimit-valkey.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
name: ratelimit-valkey
namespace: envoy-gateway-system
spec:
replicas: 1
selector:
matchLabels:
app: ratelimit-valkey
template:
metadata:
labels:
app: ratelimit-valkey
spec:
containers:
- name: valkey
image: valkey/valkey:9.2.0
args: ["--save", "", "--appendonly", "no"]
ports:
- containerPort: 6379
resources:
requests:
cpu: 50m
memory: 32Mi
limits:
memory: 128Mi
---
apiVersion: v1
kind: Service
metadata:
name: ratelimit-valkey
namespace: envoy-gateway-system
spec:
selector:
app: ratelimit-valkey
ports:
- port: 6379
EOF
kubectl apply -f ratelimit-valkey.yaml && kubectl -n envoy-gateway-system rollout status deploy ratelimit-valkey
# Tell Envoy Gateway about the store (Helm release from Day 3)
export KUBECONFIG=/etc/rancher/k3s/k3s.yaml
cat > eg-ratelimit.yaml <<'EOF'
config:
envoyGateway:
rateLimit:
backend:
type: Redis
redis:
url: ratelimit-valkey.envoy-gateway-system.svc.cluster.local:6379
EOF
helm upgrade eg oci://docker.io/envoyproxy/gateway-helm --version v1.10.0 -n envoy-gateway-system \
--skip-crds --reuse-values -f eg-ratelimit.yaml --wait | grep STATUS
# Policy from Day 4 plus global limit: 50 per second for each value of X-Nutzer
cp ../tag04/retry.yaml schutz-global.yaml
cat >> schutz-global.yaml <<'EOF'
rateLimit:
global:
rules:
- clientSelectors:
- headers:
- name: X-Nutzer
type: Distinct
limit:
requests: 50
unit: Second
EOF
kubectl apply -f schutz-global.yaml
# the rate limit service is only created with the first global rule
kubectl -n envoy-gateway-system rollout status deploy envoy-ratelimitExpected (excerpt):
deployment "ratelimit-valkey" successfully rolled out
STATUS: deployed
backendtrafficpolicy.gateway.envoyproxy.io/kurz-retry configured
deployment "envoy-ratelimit" successfully rolled out
Ten users together send 1000 requests per second, so 100 per second per user. 50 are allowed – about 500 per second should get through.
# on s1
k6 run -q -e ZIEL=http://172.16.0.126 -e RATE=1000 -e NUTZER=10 status.js > k6-global.txt 2>&1; status k6-global.txtExpected:
http_req_duration{status:302} ✓ 'p(95)>=0' p(95)=158.27ms
http_req_duration{status:429} ✓ 'p(95)>=0' p(95)=69.8ms
...
http_reqs{status:302} ✓ 'count>=0' count=34269
http_reqs{status:429} ✓ 'count>=0' count=5305
857 per second instead of 500. What is Envoy counting? Every Envoy Pod has an admin interface with statistics on port 19000:
# on s1
# Function rlstat: counters of the global limit in both Envoy Pods
rlstat() { for p in $(kubectl -n envoy-gateway-system get pods -l gateway.envoyproxy.io/owning-gateway-name=web -o name); do
kubectl -n envoy-gateway-system port-forward $p 19000:19000 >/dev/null 2>&1 & PF=$!; sleep 2
curl -s localhost:19000/stats | grep -E 'rule/0.ratelimit\.(ok|over_limit|failure_mode_allowed):|ratelimit_cluster.upstream_rq_timeout' | tr '\n' ' '; echo
kill $PF; sleep 1; done; }
rlstatExpected (one line per Pod, abridged):
cluster.httproute/kurz/kurz/rule/0.ratelimit.failure_mode_allowed: 10112 ...ratelimit.ok: 4935 ...ratelimit.over_limit: 2394 cluster.ratelimit_cluster.upstream_rq_timeout: 9566
cluster.httproute/kurz/kurz/rule/0.ratelimit.failure_mode_allowed: 13016 ...ratelimit.ok: 6206 ...ratelimit.over_limit: 2911 cluster.ratelimit_cluster.upstream_rq_timeout: 12440
For 23,128 of 39,574 requests – 58 % – the rate limit service did not
respond in time, and Envoy let the request through without
checking (failure_mode_allowed). That is
intentional: a failed limit should not take down the whole site (“fail
open”). But the deadline is tight: according to the Envoy Gateway
documentation, Envoy waits 20 ms without its own setting, and the
service runs on s1, where k6 is also working.
# on s1
# Deadline to 200 ms
sed -i 's/^ rateLimit:$/ rateLimit:\n timeout: 200ms/' eg-ratelimit.yaml
helm upgrade eg oci://docker.io/envoyproxy/gateway-helm --version v1.10.0 -n envoy-gateway-system \
--skip-crds --reuse-values -f eg-ratelimit.yaml --wait | grep STATUS
kubectl -n envoy-gateway-system rollout restart deploy envoy-gateway && kubectl -n envoy-gateway-system rollout status deploy envoy-gateway
sleep 30
k6 run -q -e ZIEL=http://172.16.0.126 -e RATE=1000 -e NUTZER=10 status.js > k6-global-200.txt 2>&1; status k6-global-200.txt
rlstatExpected (Envoy’s counters keep running since the first run):
http_req_duration{status:302} ✓ 'p(95)>=0' p(95)=210.7ms
http_req_duration{status:429} ✓ 'p(95)>=0' p(95)=116.12ms
...
http_reqs{status:302} ✓ 'count>=0' count=20376
http_reqs{status:429} ✓ 'count>=0' count=19086
cluster.httproute/kurz/kurz/rule/0.ratelimit.failure_mode_allowed: 10364 ...ratelimit.ok: 13973 ...ratelimit.over_limit: 11140 ...
cluster.httproute/kurz/kurz/rule/0.ratelimit.failure_mode_allowed: 13290 ...ratelimit.ok: 17018 ...ratelimit.over_limit: 13251 ...
20,376 in 40 seconds are 509 per second, almost exactly 10 × 50. Only 526 requests were let through unchecked this time (10,364 − 10,112 and 13,290 − 13,016), just over 1 %. The price: every request waits for the rate limit service, and the p95 of the redirects rises from 158 to 211 ms.
One more test belongs here – requests without any
X-Nutzer:
# on s1
k6 run -q -e ZIEL=http://172.16.0.126 -e RATE=1000 -e DAUER=20s status.js 2>&1 | grep -A1 -E 'http_reqs\{status:(302|429)\}' | sed 's/ */ /g' | grep -v '^--' | paste - -Expected:
http_reqs{status:302} ✓ 'count>=0' count=19885
http_reqs{status:429} ✓ 'count>=0' count=0
No header, no counter, no limit. A rule with Distinct
only applies to requests that have the header. Anyone building such a
limit needs a second rule for everyone else – or an ID that every
request has.
Save your progress? Sign up for free
Drill 4: Circuit breaker
Limits protect against individual users. Against overall overload, a
limit at the backend helps: at most 100 concurrent requests and 20
pending per Envoy to kurz. Everything beyond that gets
503 immediately.
# on s1
cp schutz-global.yaml schutz-ende.yaml
cat >> schutz-ende.yaml <<'EOF'
circuitBreaker:
maxParallelRequests: 100
maxPendingRequests: 20
EOF
# 3000/s first without, then with circuit breaker
for v in ohne mit; do
if [ $v = mit ]; then kubectl apply -f schutz-ende.yaml >/dev/null; else kubectl apply -f schutz-global.yaml >/dev/null; fi
sleep 20; echo "== 3000/s, $v Circuit Breaker"
k6 run -q -e ZIEL=http://172.16.0.126 -e RATE=3000 -e DAUER=40s status.js > k6-cb-$v.txt 2>&1
status k6-cb-$v.txt | grep -E '302|503'; grep dropped_iterations k6-cb-$v.txt | sed 's/ */ /g'; sleep 30; doneExpected:
== 3000/s, ohne Circuit Breaker
http_req_duration{status:302} ✓ 'p(95)>=0' p(95)=355.79ms
http_reqs{status:302} ✓ 'count>=0' count=94199
http_reqs{status:503} ✓ 'count>=0' count=0
dropped_iterations..: 25802 642.297359/s
== 3000/s, mit Circuit Breaker
http_req_duration{status:302} ✓ 'p(95)>=0' p(95)=297.8ms
http_req_duration{status:503} ✓ 'p(95)>=0' p(95)=239.8ms
http_reqs{status:302} ✓ 'count>=0' count=83304
http_reqs{status:503} ✓ 'count>=0' count=21387
dropped_iterations..: 15319 382.008443/s
(ohne = without, mit = with.) Sobering: 11
% fewer redirects, the p95 only slightly better, and the rejections
themselves take 240 ms. The circuit breaker protects the backend – but
here kurz is not the bottleneck, the nodes as a whole are
(Day 9). Envoy, k6 and kurz share the same CPU; a fast no
does not arrive fast at the client.
What it looks like when kurz itself is the bottleneck is
shown by the small Pods from Day 9 (two Pods with a fixed limit of
200m). KEDA is paused for this:
# on s1
kubectl -n kurz annotate scaledobject kurz autoscaling.keda.sh/paused-replicas=2 --overwrite
kubectl apply -f ../tag09/kurz-hpa.yaml && kubectl -n kurz rollout status deploy kurz
for v in ohne mit; do
if [ $v = mit ]; then kubectl apply -f schutz-ende.yaml >/dev/null; else kubectl apply -f schutz-global.yaml >/dev/null; fi
sleep 20; echo "== 1000/s, 2 kleine Pods, $v Circuit Breaker"
k6 run -q -e ZIEL=http://172.16.0.126 -e RATE=1000 -e DAUER=40s status.js > k6-klein-$v.txt 2>&1
status k6-klein-$v.txt | grep -E '302|503'; grep dropped_iterations k6-klein-$v.txt | sed 's/ */ /g'; sleep 20; doneExpected:
== 1000/s, 2 kleine Pods, ohne Circuit Breaker
http_req_duration{status:302} ✓ 'p(95)>=0' p(95)=571.69ms
http_reqs{status:302} ✓ 'count>=0' count=38645
http_reqs{status:503} ✓ 'count>=0' count=0
dropped_iterations..: 1355 33.595017/s
== 1000/s, 2 kleine Pods, mit Circuit Breaker
http_req_duration{status:302} ✓ 'p(95)>=0' p(95)=342.82ms
http_req_duration{status:503} ✓ 'p(95)>=0' p(95)=35.54ms
http_reqs{status:302} ✓ 'count>=0' count=34758
http_reqs{status:503} ✓ 'count>=0' count=4771
dropped_iterations..: 472 11.69493/s
Now it works: 12 % of the requests get a clear no in 36 ms (p95), and
the rest become 40 % faster (572 → 343 ms). Without a circuit breaker,
everyone waits long; with it, a few do not wait at all and the others
wait less. A client with retry and backoff (Day 12) can do something
with a fast 503, but not with a response after 600 ms.
# on s1
# back to normal Pods, KEDA in control again; final state: policy with all protection mechanisms
kubectl apply -f ../tag09/kurz.yaml
kubectl -n kurz annotate scaledobject kurz autoscaling.keda.sh/paused-replicas-
kubectl apply -f schutz-ende.yamlSave your progress? Sign up for free
Exercise: Speed drills
- Is the policy of
kurzaccepted, and which protection mechanisms does it contain? Target time: 1 min - How many requests has the global limit let through unchecked since the Envoy Pods started? Target time: 2 min
- You want to allow 1000 requests per second for the whole route and have three Envoy replicas. Which number belongs in a local limit, and what happens if one replica fails? Target time: 2 min
Solution
# on s1
# 1: state and content of the policy
kubectl -n kurz get btp kurz-retry -o jsonpath='{.status.ancestors[0].conditions[0].type}={.status.ancestors[0].conditions[0].status}{"\n"}'
kubectl -n kurz get btp kurz-retry -o json | jq -c '.spec | keys'
# 2: failure_mode_allowed counters of both Envoy Pods
rlstat | grep -o 'failure_mode_allowed: [0-9]*'Expected (the counters depend on your runs and restarts of the Envoy Pods):
Accepted=True
["circuitBreaker","healthCheck","rateLimit","retry","targetRefs","timeout"]
failure_mode_allowed: 5320
failure_mode_allowed: 4680
On 3: 1000 / 3 ≈ 333 per instance. If one fails, the other two only manage 666 per second – the limit silently drops by a third even though nobody changed it. If you need a fixed total limit, use a global limit.
Save your progress? Sign up for free
Challenge
The global limit lets everything through when the rate limit service
fails. Decide for two cases whether “fail open” or “fail closed” is
right, and try out what happens when envoy-ratelimit is
gone: (a) the redirects of kurz, (b) a login interface that
is supposed to protect against password guessing.
Solution
For (a), “fail open” is right: a missing limit is worse than a
working one, but better than a site that is down. For (b) it is the
other way round: without a limit, the interface is open to password
guessing, so rather reject: failClosed: true under
rateLimit in the Envoy Gateway configuration (like
timeout above). Envoy then responds with 500
as long as the service is missing – and that applies to all global
limits of the Gateway. If you need both, move the login to its own
Gateway.
# on s1
# Stop the rate limit service, 20 s of load with users, start the service again
kubectl -n envoy-gateway-system scale deploy envoy-ratelimit --replicas=0
sleep 10
k6 run -q -e ZIEL=http://172.16.0.126 -e RATE=500 -e NUTZER=5 -e DAUER=20s status.js 2>&1 | grep -A1 -E 'http_reqs\{status:(302|429|503)\}' | sed 's/ */ /g' | grep -v '^--' | paste - -
kubectl -n envoy-gateway-system scale deploy envoy-ratelimit --replicas=1Expected:
deployment.apps/envoy-ratelimit scaled
http_reqs{status:302} ✓ 'count>=0' count=10000
http_reqs{status:429} ✓ 'count>=0' count=0
http_reqs{status:503} ✓ 'count>=0' count=0
deployment.apps/envoy-ratelimit scaled
Five users with 100 per second each, limit 50 – and all 10,000
requests got through. Without the service there is no limit, and neither
k6 nor kurz notices anything. It is only visible in Envoy’s
counters (failure_mode_allowed rises by exactly 10,000) – a
reason to monitor exactly this counter.
Save your progress? Sign up for free
Checkpoint
# on s1
# one policy for kurz, accepted
kubectl -n kurz get btp -o custom-columns=NAME:.metadata.name,STATUS:.status.ancestors[0].conditions[0].status
# rate limit service and its store are running
kubectl -n envoy-gateway-system get deploy envoy-ratelimit ratelimit-valkey -o custom-columns=NAME:.metadata.name,READY:.status.readyReplicas
# deadline of the rate limit service
kubectl -n envoy-gateway-system get cm envoy-gateway-config -o jsonpath='{.data.envoy-gateway\.yaml}' | grep timeout
# a user at 100/s gets half of them as 429
k6 run -q -e ZIEL=http://172.16.0.126 -e RATE=100 -e NUTZER=1 -e DAUER=10s status.js 2>&1 | grep -A1 -E 'http_reqs\{status:(302|429)\}' | sed 's/ */ /g' | grep -v '^--' | paste - -Expected:
NAME STATUS
kurz-retry True
NAME READY
envoy-ratelimit 1
ratelimit-valkey 1
timeout: 200ms
http_reqs{status:302} ✓ 'count>=0' count=535
http_reqs{status:429} ✓ 'count>=0' count=466
Interview note
- Local or global? Local limits are cheap and failure-proof, but they apply per instance – two Envoys, double the limit (here 1229 instead of 600 per second). Global limits count correctly, cost one lookup per request (p95 158 → 211 ms) and depend on another service.
- Fail open is the default, and it hides well: 58 %
of the requests went through unchecked until the deadline was raised
from 20 to 200 ms. Without a look at
failure_mode_allowed, nobody would have noticed. - Backpressure pays off when the backend is the bottleneck: with small Pods, the p95 improved by 40 % and the rejections came in 36 ms. If the nodes as a whole are full, a circuit breaker only shifts who suffers.
- A 429 or 503 is an answer, not an outage – provided the client handles it (Retry-After, backoff). That is what tomorrow is about.
Enterprise note
- Limits belong to a contract: per API key or tenant, documented, with
429andRetry-After. Envoy Gateway can also read the ID from a JWT claim instead of trusting a header that anyone can set. - The rate limit service is part of the data path. It needs monitoring
(the counters
over_limit,error,failure_mode_allowed), a deliberate decision for fail open or closed, and capacity on a node that is not itself under load. - Circuit breaker limits are capacity planning: maximum parallelism per instance × number of instances must match what the backend can really handle. Values from examples (1024 is the default) protect nothing.