Skip to content
System design · Chapter 14 of 21 Day 12: Rate Limiting and Backpressure

Day 12: Rate Limiting and Backpressure

Goal: A single customer must not clog the system for everyone else. You measure where kurz hits its limit when creating links, limit customers per API key in HAProxy, shed overload early instead of piling it up in queues, and slow down an attacker who guesses codes · Duration: approx. 90 min · Prerequisite: Day 11

Briefing

  • Day 11 showed how quickly 600 operations turn into 1800 requests. A client with misconfigured retries, a script in a loop or an attacker is enough, and everyone else waits. The system cannot know whose request is important as long as it treats them all the same.
  • Rate limiting gives every customer a quota: so many requests per time period, the rest immediately gets 429 Too Many Requests. That protects customers from each other.
  • Backpressure means: the system says “full” early, instead of accepting everything and piling it up in queues. An unbounded queue does not turn overload into errors but into wait time, and for everyone. Rejecting early (load shedding) keeps the response time of accepted requests low.
Term Meaning
Quota allowed requests per time window, here per API key
429 “too many requests”, often with Retry-After: wait this many seconds
Stick table table in HAProxy that keeps counters per key (header, IP, …)
Load shedding rejecting requests that would not be served in time (503)
maxconn at most this many concurrent requests per server, the rest waits in HAProxy
timeout queue how long a request may wait in HAProxy, then 503

By the end of the day HAProxy limits every customer with a key and lets through to the instances only as many requests as they answer promptly.

Drill 1: Where Is the Limit?

So far you have mainly measured redirects. Today it is about creating links, the expensive path. The script sends a new address per iteration, optionally with an API key in the header X-Api-Key, and counts the responses by status:

# on s1
mkdir -p ~/sd/tag12 && cd ~/sd/tag12
cat > anlegen.js <<'EOF'
import http from "k6/http";
import { check } from "k6";

const ZIEL = __ENV.ZIEL || "http://localhost";
const KUNDE = __ENV.KUNDE || "";             // landet im Header X-Api-Key, leer = ohne

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

export default function () {
  const headers = { "Content-Type": "application/json" };
  if (KUNDE) headers["X-Api-Key"] = KUNDE;
  const url = `https://example.org/tag12/${KUNDE || "anonym"}/${__VU}-${__ITER}-${Date.now()}`;
  const r = http.post(`${ZIEL}/api/links`, JSON.stringify({ url }), { headers, timeout: "10s" });
  check(r, { "201": (x) => x.status === 201, "429": (x) => x.status === 429, "503": (x) => x.status === 503 });
}
EOF
for rate in 300 600 1200 2400; do
  echo "== $rate/s"
  k6 run -q -e RATE=$rate anlegen.js 2>&1 | grep -E 'http_req_duration\.|http_req_failed\.|dropped_iterations|http_reqs\.'
done

Expected:

== 300/s
    http_req_duration..............: avg=6.86ms min=2.63ms med=5.89ms max=40.6ms  p(90)=10.48ms p(95)=12.83ms
    http_req_failed................: 0.00%  0 out of 6001
    http_reqs......................: 6001   299.856061/s
== 600/s
    http_req_duration..............: avg=14.43ms min=3.22ms med=8.67ms max=337.02ms p(90)=18.93ms p(95)=28.14ms
    http_req_failed................: 0.00%  0 out of 11900
    http_reqs......................: 11900  594.750262/s
    dropped_iterations.............: 101    5.04788/s
== 1200/s
    http_req_duration..............: avg=415.87ms min=4.63ms med=419.57ms max=991.82ms p(90)=696.92ms p(95)=738.96ms
    http_req_failed................: 0.00%  0 out of 21482
    http_reqs......................: 21482  1048.711489/s
    dropped_iterations.............: 2519   122.972919/s
== 2400/s
    http_req_duration..............: avg=1.43s min=15.94ms med=1.75s max=2.1s  p(90)=1.9s p(95)=1.96s
    http_req_failed................: 0.00%  0 out of 22821
    http_reqs......................: 22821  1066.527199/s
    dropped_iterations.............: 25181  1176.820534/s

At just over 1050 creations per second it is over; the two instances with their half CPU core cannot do more. What is remarkable is what happens above that: not a single error. Every request is accepted and waits, at 2400 per second almost two seconds. dropped_iterations counts what k6 could not even send because all 2000 virtual users were still waiting for responses. To a real user the system does not look broken, just unbearably slow.

Save your progress? Sign up for free

Drill 2: A Loud Customer

Two customers: leise (“quiet”) creates 20 links per second, laut (“loud”) 1500. First leise alone, then both at the same time:

# on s1
k6 run -q -e KUNDE=leise -e RATE=20 anlegen.js 2>&1 | grep -E 'http_req_duration\.|http_req_failed\.'
echo "== mit lautem Kunden"
k6 run -q -e KUNDE=laut -e RATE=1500 anlegen.js > laut.log 2>&1 &
sleep 2
k6 run -q -e KUNDE=leise -e RATE=20 -e DAUER=15s anlegen.js 2>&1 | grep -E 'http_req_duration\.|http_req_failed\.'
wait; grep -E 'http_req_duration\.|http_reqs\.' laut.log

Expected:

    http_req_duration..............: avg=7.83ms min=4.72ms med=7.32ms max=40.34ms p(90)=9.89ms  p(95)=11.48ms
    http_req_failed................: 0.00% 0 out of 401
== mit lautem Kunden
    http_req_duration..............: avg=1.18s min=245.49ms med=1.21s max=2.03s p(90)=1.9s p(95)=1.93s
    http_req_failed................: 0.00% 0 out of 301
    http_req_duration..............: avg=1.18s min=12.61ms med=1.3s max=2.04s p(90)=1.9s p(95)=1.93s
    http_reqs......................: 21861  1016.871551/s

leise has not done anything differently, but now waits 1.9 instead of 0.011 seconds. Both customers get the same bad response time, because they stand in the same queue.

Save your progress? Sign up for free

Drill 3: One Quota per Key

HAProxy can count per customer. A stick table in the frontend keeps a rate for every value of the header X-Api-Key: requests in the last second. From 200 on, HAProxy itself answers with 429 and the hint to try again in one second:

# on s1
sudo cp /etc/haproxy/haproxy.cfg /tmp/haproxy.cfg.alt
sudo perl -0pi -e 's/(frontend web\n    bind :80\n)/$1    # Anfragen pro Sekunde je API-Schlüssel, nach 30 s ohne Anfrage vergessen\n    stick-table type string len 64 size 100k expire 30s store http_req_rate(1s)\n    http-request track-sc0 req.hdr(X-Api-Key) if { req.hdr(X-Api-Key) -m found }\n    acl zu_viel sc_http_req_rate(0) gt 200\n    http-request return status 429 content-type text\/plain string "zu viele" hdr Retry-After 1 if zu_viel\n/' /etc/haproxy/haproxy.cfg
diff /tmp/haproxy.cfg.alt /etc/haproxy/haproxy.cfg
sudo haproxy -c -f /etc/haproxy/haproxy.cfg && sudo systemctl reload haproxy && echo neu geladen

Expected:

17a18,22
>     # Anfragen pro Sekunde je API-Schlüssel, nach 30 s ohne Anfrage vergessen
>     stick-table type string len 64 size 100k expire 30s store http_req_rate(1s)
>     http-request track-sc0 req.hdr(X-Api-Key) if { req.hdr(X-Api-Key) -m found }
>     acl zu_viel sc_http_req_rate(0) gt 200
>     http-request return status 429 content-type text/plain string "zu viele" hdr Retry-After 1 if zu_viel
neu geladen

http-request return with text needs a content-type; without it, haproxy -c rejects the line. And HAProxy knows no continuation lines: a rule stands on one line. Requests without a key are not counted. The same measurement as in Drill 2, plus a look at the table:

# on s1
k6 run -q -e KUNDE=laut -e RATE=1500 anlegen.js > laut.log 2>&1 &
sleep 2
k6 run -q -e KUNDE=leise -e RATE=20 -e DAUER=15s anlegen.js 2>&1 | grep -E 'http_req_duration\.|http_req_failed\.'
echo "show table web" | sudo nc -U /run/haproxy/admin.sock
wait; grep -E '✓|✗|201|429|http_req_duration\.|http_reqs\.' laut.log

Expected:

    http_req_duration..............: avg=9.41ms  min=5.34ms med=8.56ms max=24.99ms p(90)=13.49ms p(95)=14.88ms
    http_req_failed................: 0.00% 0 out of 301
# table: web, type: string, size:102400, used:2
0x76f93ee38e50: key=leise use=0 exp=29750 shard=0 http_req_rate(1000)=15
0x76f942e86250: key=laut use=1 exp=30002 shard=0 http_req_rate(1000)=1499

    ✗ 201
      ↳  0% — ✓ 200 / ✗ 29742
    ✗ 429
      ↳  99% — ✓ 29742 / ✗ 200
    ✗ 503
      ↳  0% — ✓ 0 / ✗ 29942
    http_req_duration..............: avg=1.59ms min=208.67µs med=678.2µs max=72.56ms p(90)=2.46ms  p(95)=4.08ms
    http_reqs......................: 29942  1496.967264/s

leise is fast again: p95 14.9 ms. But laut was allowed to create only 200 links in 20 seconds, not 200 per second. The table shows why: the rate counts every request, including the rejected ones. Anyone knocking at 1500 per second is always above 200 and never gets through again. That is not a quota, that is a block, as long as the customer does not slow down on their own.

For a paying customer that is wrong. They should get their 200 per second, no matter how often they knock in addition. So count only the requests that are let through. For that, the stick table has general-purpose counters (gpc) that you increment yourself, with their own rate:

# on s1
sudo cp /etc/haproxy/haproxy.cfg /tmp/haproxy.cfg.v1
sudo perl -0pi -e 's/store http_req_rate\(1s\)/store gpc_rate(1,1s)/; s/acl zu_viel sc_http_req_rate\(0\) gt 200\n/acl zu_viel sc_gpc_rate(0,0) ge 200\n/; s/(    http-request return status 429 [^\n]*\n)/$1    # nur durchgelassene Anfragen zählen\n    http-request sc-inc-gpc(0,0) if { req.hdr(X-Api-Key) -m found }\n/' /etc/haproxy/haproxy.cfg
diff /tmp/haproxy.cfg.v1 /etc/haproxy/haproxy.cfg
sudo haproxy -c -f /etc/haproxy/haproxy.cfg && sudo systemctl reload haproxy && echo neu geladen
k6 run -q -e KUNDE=laut -e RATE=1500 anlegen.js > laut.log 2>&1 &
sleep 2
k6 run -q -e KUNDE=leise -e RATE=20 -e DAUER=15s anlegen.js 2>&1 | grep -E 'http_req_duration\.|http_req_failed\.'
echo "show table web" | sudo nc -U /run/haproxy/admin.sock
wait; grep -E '↳|http_req_duration\.|http_reqs\.' laut.log

Expected:

19c19
<     stick-table type string len 64 size 100k expire 30s store http_req_rate(1s)
---
>     stick-table type string len 64 size 100k expire 30s store gpc_rate(1,1s)
21c21
<     acl zu_viel sc_http_req_rate(0) gt 200
---
>     acl zu_viel sc_gpc_rate(0,0) ge 200
22a23,24
>     # nur durchgelassene Anfragen zählen
>     http-request sc-inc-gpc(0,0) if { req.hdr(X-Api-Key) -m found }
neu geladen
    http_req_duration..............: avg=9.11ms  min=3.18ms med=8.48ms max=20.54ms p(90)=14.18ms p(95)=15.82ms
    http_req_failed................: 0.00% 0 out of 300
# table: web, type: string, size:102400, used:2
0x7459a4e1be10: key=leise use=0 exp=29691 shard=0 gpc0_rate(1000)=14
0x7459a3236650: key=laut use=1 exp=29996 shard=0 gpc0_rate(1000)=199

      ↳  13% — ✓ 3999 / ✗ 25519
      ↳  86% — ✓ 25519 / ✗ 3999
      ↳  0% — ✓ 0 / ✗ 29518
    http_req_duration..............: avg=3.92ms  min=228.14µs med=1.03ms max=141.35ms p(90)=8.6ms   p(95)=13.78ms
    http_reqs......................: 29518  1475.259852/s

The three lines belong to the checks 201, 429 and 503. laut has now created 3999 links in 20 seconds, exactly its quota of 200 per second. leise stays at p95 15.8 ms. The rule for the counter comes after the rejection: whatever ends with 429 never reaches it.

Save your progress? Sign up for free

Drill 4: Load Shedding Instead of a Queue

Quotas protect customers from each other. They do not help against overload as a whole: many customers who all stay within their quota can still overwhelm the system. Drill 1 showed what happens then. Now the same experiment without a key at 2400 per second, once as before and once with a limit per instance: at most 16 concurrent requests (that is how many connections the pool of kurz has), and anyone who waits longer than 20 ms in HAProxy immediately gets 503:

# on s1
echo "== ohne Schutz"
k6 run -q -e RATE=2400 anlegen.js 2>&1 | grep -E '^ +[✓✗] |↳|expected_response|http_reqs\.|dropped'
sudo cp /etc/haproxy/haproxy.cfg /tmp/haproxy.cfg.v2
sudo perl -0pi -e 's/(    default-server inter 2s fall 3 rise 2)\n/$1 maxconn 16\n    timeout queue 20ms\n/' /etc/haproxy/haproxy.cfg
diff /tmp/haproxy.cfg.v2 /etc/haproxy/haproxy.cfg
sudo haproxy -c -f /etc/haproxy/haproxy.cfg && sudo systemctl reload haproxy && echo neu geladen
echo "== mit Lastabwurf"
k6 run -q -e RATE=2400 anlegen.js 2>&1 | grep -E '^ +[✓✗] |↳|expected_response|http_reqs\.|dropped'

Expected:

== ohne Schutz
    ✓ 201
    ✗ 429
      ↳  0% — ✓ 0 / ✗ 21845
    ✗ 503
      ↳  0% — ✓ 0 / ✗ 21845
      { expected_response:true }...: avg=1.48s min=22.28ms med=1.69s max=2.34s p(90)=2.1s p(95)=2.14s
    http_reqs......................: 21845  1029.652591/s
    dropped_iterations.............: 26156  1232.84931/s
31c31,32
<     default-server inter 2s fall 3 rise 2
---
>     default-server inter 2s fall 3 rise 2 maxconn 16
>     timeout queue 20ms
neu geladen
== mit Lastabwurf
    ✗ 201
      ↳  47% — ✓ 21708 / ✗ 23757
    ✗ 429
      ↳  0% — ✓ 0 / ✗ 45465
    ✗ 503
      ↳  52% — ✓ 23757 / ✗ 21708
      { expected_response:true }...: avg=54.56ms min=6.25ms med=51.15ms max=196.26ms p(90)=75.97ms p(95)=89.27ms
    http_reqs......................: 45465  2269.088467/s
    dropped_iterations.............: 2536   126.567873/s
created p95 of created rejected
without protection 21,845 2.14 s 0
with load shedding 21,708 89 ms 23,757 immediately with 503

Almost the same number of links, but in one twenty-fourth of the time. The rejected requests could not have been served anyway. Without a limit they would only have held up everyone else. A client that gets a fast 503 can try again later, with backoff from Day 11.

The wait time in the queue is the latency. With timeout queue 100ms, the p95 of the created links was 209 ms: under overload the queue always fills up to the limit.

Save your progress? Sign up for free

Drill 5: Someone Guesses Codes

A different pattern: someone tries random codes to find other people’s links. Every made-up code misses the cache and lands in the database, and twice at that: the replica does not know it, so finde also asks the primary to be safe (Day 8). Such an attacker has no key. The script guesses codes and sends them to the address of s1 instead of localhost:

# on s1
cd ~/sd/tag12 && cp ~/sd/tag10/klick.js ~/sd/tag10/codes.txt .
cat > raten.js <<'EOF'
import http from "k6/http";
import { check } from "k6";

const ZIEL = __ENV.ZIEL || "http://172.16.0.126"; // andere Absender-IP als localhost
const ALPHABET = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";

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

// erfundene Codes: fast nie ein Treffer
export default function () {
  let code = "";
  for (let i = 0; i < 7; i++) code += ALPHABET[Math.floor(Math.random() * ALPHABET.length)];
  const r = http.get(`${ZIEL}/${code}`, { redirects: 0 });
  check(r, { "404": (x) => x.status === 404, "429": (x) => x.status === 429 });
}
EOF
export PGPASSWORD=lab-kurz-123
tx() { psql -h $1 -U kurz -d kurz -tAc "select xact_commit from pg_stat_database where datname = 'kurz'"; }
echo "== nur Klicks"
k6 run -q -e RATE=200 -e DAUER=15s klick.js 2>&1 | grep -E 'http_req_duration\.|http_req_failed\.'
echo "== Klicks und Rater"
a3=$(tx s3); a2=$(tx s2)
k6 run -q raten.js > raten.log 2>&1 &
sleep 2
k6 run -q -e RATE=200 -e DAUER=15s klick.js 2>&1 | grep -E 'http_req_duration\.|http_req_failed\.'
wait
echo "Tx/s s3: $(( ($(tx s3) - a3) / 20 )), s2: $(( ($(tx s2) - a2) / 20 ))"
grep -E '^ +[✓✗] |↳|http_reqs\.|dropped' raten.log

Expected:

== nur Klicks
    http_req_duration..............: avg=2.68ms min=1.08ms med=2.4ms  max=35.41ms p(90)=3.68ms p(95)=4.52ms
    http_req_failed................: 0.00%  0 out of 3001
== Klicks und Rater
    http_req_duration..............: avg=24.03ms min=1.27ms med=23.06ms max=93.27ms p(90)=40.39ms p(95)=50.36ms
    http_req_failed................: 13.40% 402 out of 3000
Tx/s s3: 1229, s2: 1220
    ✗ 404
      ↳  85% — ✓ 25165 / ✗ 4100
    ✗ 429
      ↳  0% — ✓ 0 / ✗ 29265
    http_reqs............: 29265   1461.019247/s
    dropped_iterations...: 735     36.693974/s

The guesser generates over 1200 queries per second on both databases, and the real clicks suffer: p95 50 instead of 4.5 ms, and 13% get 503. That is the load shedding from Drill 4, which now hits the real clicks too, because it cannot tell who is causing the load.

Why not simply http://s1 as the target? s1 appears twice in /etc/hosts, as 127.0.1.1 and as 172.16.0.126. k6 spreads the requests across both addresses, and half of them would come from 127.0.0.1, like the real clicks. With the fixed IP, the guesser has its own source address.

Without a key, only the source IP remains. There already is a frontend stick table, so the second one goes into a separate, empty backend. Here it is intended that rejected requests count too: whoever keeps hammering stays blocked. Limit: 3000 requests in 10 seconds.

# on s1
sudo cp /etc/haproxy/haproxy.cfg /tmp/haproxy.cfg.v3
sudo perl -0pi -e 's/(    http-request sc-inc-gpc\(0,0\) if \{ req.hdr\(X-Api-Key\) -m found \}\n)/$1    # ohne Schlüssel: Anfragen pro 10 s je Absender-IP, abgelehnte zählen mit\n    http-request track-sc1 src table proben unless { req.hdr(X-Api-Key) -m found }\n    http-request deny deny_status 429 if { sc_http_req_rate(1,proben) gt 3000 }\n/; s/(frontend stats\n)/backend proben\n    stick-table type ip size 100k expire 60s store http_req_rate(10s)\n\n$1/' /etc/haproxy/haproxy.cfg
diff /tmp/haproxy.cfg.v3 /etc/haproxy/haproxy.cfg
sudo haproxy -c -f /etc/haproxy/haproxy.cfg && sudo systemctl reload haproxy && echo neu geladen
a3=$(tx s3); a2=$(tx s2)
k6 run -q raten.js > raten.log 2>&1 &
sleep 2
k6 run -q -e RATE=200 -e DAUER=15s klick.js 2>&1 | grep -E 'http_req_duration\.|http_req_failed\.'
echo "show table proben" | sudo nc -U /run/haproxy/admin.sock
wait
echo "Tx/s s3: $(( ($(tx s3) - a3) / 20 )), s2: $(( ($(tx s2) - a2) / 20 ))"
grep -E '^ +[✓✗] |↳|http_reqs\.|dropped' raten.log

Expected:

24a25,27
>     # ohne Schlüssel: Anfragen pro 10 s je Absender-IP, abgelehnte zählen mit
>     http-request track-sc1 src table proben unless { req.hdr(X-Api-Key) -m found }
>     http-request deny deny_status 429 if { sc_http_req_rate(1,proben) gt 3000 }
34a38,40
>
> backend proben
>     stick-table type ip size 100k expire 60s store http_req_rate(10s)
neu geladen
    http_req_duration..............: avg=7.62ms min=1.16ms med=3.35ms max=171.94ms p(90)=10.83ms p(95)=27.5ms
    http_req_failed................: 0.00%  0 out of 3000
# table: proben, type: ip, size:102400, used:2
0x7ae4a669d5b0: key=127.0.0.1 use=0 exp=59721 shard=0 http_req_rate(10000)=1946
0x7ae4a62a73f0: key=172.16.0.126 use=0 exp=59999 shard=0 http_req_rate(10000)=14735

Tx/s s3: 140, s2: 137
    ✗ 404
      ↳  9% — ✓ 2728 / ✗ 26331
    ✗ 429
      ↳  89% — ✓ 26059 / ✗ 3000
    http_reqs............: 29059   1452.803957/s
    dropped_iterations...: 942     47.095266/s

After the first 3000 attempts the guesser is blocked and stays blocked as long as it keeps guessing. The databases drop from 1229 to 140 queries per second, and the real clicks run without errors again. Their p95 of 27.5 ms is still above idle: even when turned away, the guesser still costs CPU on s1, where HAProxy and k6 run.

An IP is a coarse attribute. Behind a company IP sit many people, and an attacker with many addresses goes unnoticed. That is why the limit here is generous, and the real protection is keys for everyone who wants more.

Save your progress? Sign up for free

Exercise: Speed drills

  1. Which keys does the limiter currently know, and how much have they used? Target time: 30 s
  2. How many responses with 4xx and 5xx has HAProxy given since the last reload, and how long was the queue at most? Target time: 1 min
  3. A customer has used up their quota and calls you. Give it back to them immediately. Target time: 1 min

Solution

# on s1
echo "show table web" | sudo nc -U /run/haproxy/admin.sock
echo "show stat" | sudo nc -U /run/haproxy/admin.sock | cut -d, -f1,2,4,43,44 | grep -E "^(# pxname|web|kurz)"
echo "clear table web key kontrolle" | sudo nc -U /run/haproxy/admin.sock

Expected (your numbers will differ):

# table: web, type: string, size:102400, used:1
0x7e7199c36650: key=kontrolle use=0 exp=29921 shard=0 gpc0_rate(1000)=143

# pxname,svname,qmax,hrsp_4xx,hrsp_5xx
web,FRONTEND,,2542,57
kurz,s1,0,0,0
kurz,s2,0,0,0
kurz,BACKEND,31,0,57

The 429s count at the frontend; the instances never saw them. The 503s from load shedding count at the backend, and qmax shows the longest queue, here 31 requests. clear table prints nothing.

Save your progress? Sign up for free

Checkpoint

Six hundred requests with the same key at once, from a single curl:

# on s1
curl -s --parallel --parallel-max 100 -X POST -H 'X-Api-Key: kontrolle' -d '{"url":"https://example.org/tag12/kontrolle"}' \
  -w '%{http_code} %header{retry-after}\n' $(for i in $(seq 600); do printf 'localhost/api/links -o /dev/null '; done) | sort | uniq -c

Expected: 400 times 429 with Retry-After: 1; the remaining 200 get through the quota.

    102 200
    400 429 1
     98 503

Of the 200 requests within the quota, HAProxy turned away 98 in the queue, because 100 at once are more than two instances with 16 slots each accept. The quota counted them anyway. The rest get 200, because the address was already created the first time.

# on s1
curl -s -o /dev/null -w '%{http_code}\n' -X POST localhost/api/links -d "{\"url\":\"https://example.org/tag12/ohne-$(date +%s)\"}"

Expected: 201; without a key only the generous per-IP limit applies.

Challenge

A customer fetches 1000 links at once every ten seconds, an average of 100 per second, far below their quota of 200. Still, they get 429 800 times with every burst. Allow bursts up to 1000 without the customer getting more than 200 per second in the long run.

Hint: The rate does not have to be measured per second.

Solution

First the problem, three bursts with nine seconds of pause:

# on s1
for i in 1 2 3; do k6 run -q -e KUNDE=stoss -e RATE=1000 -e DAUER=1s anlegen.js 2>&1 | grep -A1 -E '^ +[✓✗] (201|429)'; sleep 9; done

Expected:

    ✗ 201
      ↳  20% — ✓ 200 / ✗ 799
    ✗ 429
      ↳  79% — ✓ 799 / ✗ 200
    ✗ 201
      ↳  18% — ✓ 186 / ✗ 797
    ✗ 429
      ↳  79% — ✓ 783 / ✗ 200
    ✗ 201
      ↳  20% — ✓ 200 / ✗ 800
    ✗ 429
      ↳  80% — ✓ 800 / ✗ 200

The same upper limit, measured differently: 1000 requests in 5 seconds instead of 200 in one. On average it stays at 200 per second, but within five seconds the customer may distribute them as they like:

# on s1
sudo cp /etc/haproxy/haproxy.cfg /tmp/haproxy.cfg.v4
sudo perl -pi -e 's/store gpc_rate\(1,1s\)/store gpc_rate(1,5s)/; s/sc_gpc_rate\(0,0\) ge 200$/sc_gpc_rate(0,0) ge 1000/' /etc/haproxy/haproxy.cfg
diff /tmp/haproxy.cfg.v4 /etc/haproxy/haproxy.cfg
sudo haproxy -c -f /etc/haproxy/haproxy.cfg && sudo systemctl reload haproxy && echo neu geladen
for i in 1 2 3; do k6 run -q -e KUNDE=stoss -e RATE=1000 -e DAUER=1s anlegen.js 2>&1 | grep -A1 -E '^ +[✓✗] (201|429)'; sleep 9; done
k6 run -q -e KUNDE=laut -e RATE=1500 anlegen.js 2>&1 | grep -A1 -E '^ +[✓✗] (201|429)'

Expected:

19c19
<     stick-table type string len 64 size 100k expire 30s store gpc_rate(1,1s)
---
>     stick-table type string len 64 size 100k expire 30s store gpc_rate(1,5s)
21c21
<     acl zu_viel sc_gpc_rate(0,0) ge 200
---
>     acl zu_viel sc_gpc_rate(0,0) ge 1000
neu geladen
    ✗ 201
      ↳  98% — ✓ 978 / ✗ 13
    ✗ 429
      ↳  0% — ✓ 0 / ✗ 991
    ✗ 201
      ↳  97% — ✓ 960 / ✗ 26
    ✗ 429
      ↳  0% — ✓ 0 / ✗ 986
    ✓ 201
    ✗ 429
      ↳  0% — ✓ 0 / ✗ 997
    ✗ 201
      ↳  12% — ✓ 3794 / ✗ 26055
    ✗ 429
      ↳  86% — ✓ 25851 / ✗ 3998

No more 429 for the bursts. The few missing links are 503s from load shedding: 1000 requests in one second are more than the instances accept at once. And the steady customer at 1500 per second gets 3794 links in 20 seconds, an average of 190 per second.

The customer still cannot distribute completely freely. HAProxy estimates the rate as a sliding window: the previous period counts proportionally. If the bursts come only every six seconds, the last one is still partly in the counter. When trying it out, only 271 of 1000 got through on the second burst. So the window must be longer than the interval at which a customer may send bursts.

Save your progress? Sign up for free

Clean-up

The per-IP limit has to go again: all load tests of the next few days come from s1 without a key and would otherwise be blocked after 3000 requests. The quotas per key and the load shedding stay. The comment above the stick table gets the new window.

# on s1
sudo cp /etc/haproxy/haproxy.cfg /tmp/haproxy.cfg.v5
sudo perl -0pi -e 's/    # ohne Schlüssel: Anfragen pro 10 s je Absender-IP[^\n]*\n    http-request track-sc1 src table proben[^\n]*\n    http-request deny deny_status 429 if \{ sc_http_req_rate\(1,proben\) gt 3000 \}\n//; s/\nbackend proben\n    stick-table type ip size 100k expire 60s store http_req_rate\(10s\)\n//' /etc/haproxy/haproxy.cfg
sudo sed -i "s/# Anfragen pro Sekunde je API-Schlüssel/# Anfragen pro 5 s je API-Schlüssel/" /etc/haproxy/haproxy.cfg
sudo haproxy -c -f /etc/haproxy/haproxy.cfg && sudo systemctl reload haproxy && echo neu geladen
cd ~/sd/tag12
k6 run -q klick.js 2>&1 | grep -E 'http_req_duration\.|http_req_failed\.|checks_succeeded'

Expected:

neu geladen
    checks_succeeded...: 99.99% 44932 out of 44935
    http_req_duration..............: avg=6.55ms min=772.04µs med=4.21ms max=81.63ms p(90)=13.77ms p(95)=20.14ms
    http_req_failed................: 0.00%  3 out of 44935

1500 redirects per second run as on Day 10, p95 20 ms. Load shedding turned away three of 44,935, during short spikes in the queue. That is the price for the fast response under real overload.

Interview note

  • Where to limit? As far forward as possible: at the load balancer or API gateway, before a request ties up resources. In the app only what is known only there (e.g., expensive operations per account).
  • Algorithms: fixed window (simple, spikes at the boundaries), sliding window (HAProxy estimates it from two periods), token bucket (allows bursts up to the bucket size, then a steady rate). Say which behavior the customer should see, and choose accordingly.
  • Counting distributed: several load balancers need a shared counter (HAProxy peers, Valkey) or each gets a share of the quota. Exact global limits cost a network round trip per request.
  • Backpressure: bound queues, by length or wait time, and reject overload early. A fast 503 with Retry-After is better than a response after two seconds.

Enterprise note

  • API gateways such as Kong or Envoy offer rate limiting with a shared counter in Redis or Valkey and quotas per subscription tier. The principle is the one from Drill 3: count what gets through, reject what lies above.
  • In front of the load balancer, a CDN or a web application firewall filters coarse attacks by IP, country and behavior. That takes load off, but does not replace quotas per customer.
  • The response headers RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset show the client its quota before it hits the limit. Many public APIs send them.

Contents

More