demo: rate limit by header (advanced rate limiting)
a single cloudflare rate limit rule counts by the value of the
x-user-id header (not ip). each user id has its own bucket:
5 requests per 10 seconds. hammer the endpoint as user-a
and user-b and both will start getting 429 after the 5th
request. hammer as user-c at a slower rate and it stays
under the limit. that's the whole point of advanced rate limiting —
counting on a signal that actually identifies who is making the request,
not the ip address of a corporate proxy.
# pick a user, fire 8 requests
click a button…
# or from your terminal
# hammer as user-a: requests 6-8 will return 429
for i in $(seq 1 8); do
curl -s -o /dev/null -w "user-a req %s → %{http_code}\n" $i \
-H "x-user-id: user-a" "https://rhocfsandbox.com/api/ratelimit-per-user"
done
# meanwhile user-b has its own independent bucket
curl -s -o /dev/null -w "user-b req 1 → %{http_code}\n" \
-H "x-user-id: user-b" "https://rhocfsandbox.com/api/ratelimit-per-user" # what's the rule
| rule name | SITE_ratelimit_per_user |
| expression | http.request.uri.path eq "/api/ratelimit-per-user" |
| characteristics | http.request.headers["x-user-id"] + cf.colo.id |
| counting | 5 requests per 10 seconds |
| mitigation timeout | 10 seconds |
| action | block · custom html response (429) |