Rate limiting¶
Warning
If during setup you chose to install Envoy Gateway, then before you proceed with this lab, you will need to deploy Redis, and reconfigure Envoy Gateway with rate limiting pointing to the URL of the Redis instance you deployed.
Detailed instructions are available here.
Similar to retries, rate limiting is not part of the Kubernetes Gateway API specification, and is configured through Envoy Gateway's BackendTrafficPolicy resource.
The rate limit is associated with the HTTPRoute you wish to limit.
Simple example¶
Configure access to httpbin
to be limited to three requests per minute:
Test it¶
Send four requests in succession, the fourth should be rate-limited:
Here is the captured output:
HTTP/2 200
server: gunicorn/19.9.0
date: Tue, 07 May 2024 22:33:12 GMT
content-type: text/html; charset=utf-8
content-length: 9593
access-control-allow-origin: *
access-control-allow-credentials: true
x-ratelimit-limit: 3, 3;w=60
x-ratelimit-remaining: 2
x-ratelimit-reset: 48
HTTP/2 200
server: gunicorn/19.9.0
date: Tue, 07 May 2024 22:33:12 GMT
content-type: text/html; charset=utf-8
content-length: 9593
access-control-allow-origin: *
access-control-allow-credentials: true
x-ratelimit-limit: 3, 3;w=60
x-ratelimit-remaining: 1
x-ratelimit-reset: 48
HTTP/2 200
server: gunicorn/19.9.0
date: Tue, 07 May 2024 22:33:12 GMT
content-type: text/html; charset=utf-8
content-length: 9593
access-control-allow-origin: *
access-control-allow-credentials: true
x-ratelimit-limit: 3, 3;w=60
x-ratelimit-remaining: 0
x-ratelimit-reset: 48
HTTP/2 429
x-envoy-ratelimited: true
x-ratelimit-limit: 3, 3;w=60
x-ratelimit-remaining: 0
x-ratelimit-reset: 48
date: Tue, 07 May 2024 22:33:12 GMT
Above, note the x-ratelimit-*
headers that inform us of the limit, the number of requests remaining, and the amount of time (in seconds) until the corresponding counter is reset.
Verify: Tail the gateway logs¶
kubectl logs --tail 1 -n envoy-gateway-system \
-l gateway.envoyproxy.io/owning-gateway-name=eg \
-l gateway.envoyproxy.io/owning-gateway-namespace=default | jq
Below is a copy of the prettified JSON log line:
Note the Envoy response flag is RL: RateLimited.
Rate limit distinct users¶
It is more common for individual users to each have their own limit.
The below example adds a rate limit selection condition to distinguish between users by http header name of x-user-id
:
Test it¶
Sending multiple requests for the same user in succession will produce a result similar to the above simple example:
Following that up with another set of requests from a different user demonstrates that each user has their own, separate rate limiting counter:
The curious may wish to inspect the translated configuration at the Envoy proxy:
egctl config envoy-proxy route -n envoy-gateway-system \
-l gateway.envoyproxy.io/owning-gateway-name=eg \
-l gateway.envoyproxy.io/owning-gateway-namespace=default \
-o yaml | bat -l yaml
Here is a sanitized copy of the captured output: