API Gateways, Traffic Management & the Edge›06 · Rate limiting and quotas

Lesson 06 of 13 · Hands-on with Envoy Gateway

Rate limiting and quotas

Protect services and share capacity fairly. How rate limiters count (token bucket, fixed and sliding windows), local vs global limits and why local limits multiply with replicas, rate limits vs quotas vs concurrency limits, and a hands-on lab: per-tenant, per-plan global limits keyed on verified token claims, with Redis-backed counters, real 429 responses and rate-limit headers, and what clients should do with them.

Intermediate → Advanced
Key wordsrate limitingquotastoken bucketleaky bucketfixed windowsliding windowlocal rate limitglobal rate limitRedisenvoy-ratelimitBackendTrafficPolicyclientSelectorsDistinctper-tenant limitsper-plan limits429 Too Many RequestsRetry-Afterx-ratelimit-limitx-ratelimit-remainingconcurrency limitscost-based limitsfairness

Why limit at all

  • Protect capacity: one runaway script must not take the API down for everyone.
  • Fairness: in a multi-tenant product, one tenant's spike must not slow the others (the noisy neighbour).
  • Plans: free and paid customers get different limits.
  • Cost and abuse: scraping, credential stuffing and accidental loops cost money.
globex free plan: 5/min acme standard: 20/min Gateway pod 1 Gateway pod 2 Gateway pod 3 Rate-limit service envoy-ratelimit Redis counter per tenant + plan over the limit → 429 + Retry-After, whichever pod the request reached
Every gateway replica asks one shared rate-limit service, which keeps a counter per tenant in Redis, so the limit holds no matter which replica a request reaches.

A water fountain at school: each class gets a number of cups per break. The teacher at the fountain keeps a tally per class (a counter per tenant). If there are three fountains, all three teachers write on one shared board (the global store), otherwise a class could drink three times its share by switching fountains.

How limiters count

Algorithm Idea Behaviour
Token bucket A bucket refills at a fixed rate; each request takes a token Allows short bursts up to the bucket size, then the steady rate. Most common
Fixed window Count per minute (or second); reset at the window edge Simple; a client can send 2× the limit across a window edge
Sliding window Weighted count over the last window Smoother than fixed windows, a little more work
Concurrency Count requests in flight, not per time Protects slow backends; independent of request rate

Rate limits, quotas and concurrency

Rate limit Quota Concurrency limit
Unit Requests per second/minute Requests (or units) per day/month Requests in flight
Purpose Absorb bursts, protect capacity Enforce a plan, billing Protect slow or fragile backends
Typical place Gateway Gateway or API-management product, plus metering Gateway, service, connection pools
On exceed 429, try again soon 429 or 403 until the period resets or the plan changes 503 or queueing

Local or global

Local:   each replica keeps its own counters   → fast, no dependency, limit × replicas in practice
Global:  replicas ask a rate-limit service     → accurate across replicas, adds ~1 ms and a dependency
         that keeps counters in Redis

A common pattern: a generous local limit as a first line (cheap protection against floods) plus a global per-tenant limit for fairness and plans. Decide what happens if the global service is down: most gateways fail open (allow traffic) so a rate-limit outage doesn't become an API outage.

Lab: per-tenant, per-plan limits

Continue from lesson 5: tokens carry tenant and plan, and the gateway turns them into the trusted headers x-tenant-id and x-tenant-plan. Output is real.

1. A shared counter store

apiVersion: v1
kind: Namespace
metadata:
  name: redis-system
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: redis
  namespace: redis-system
spec:
  replicas: 1
  selector:
    matchLabels: { app: redis }
  template:
    metadata:
      labels: { app: redis }
    spec:
      containers:
      - name: redis
        image: "redis:7.4-alpine"
        ports:
        - containerPort: 6379
---
apiVersion: v1
kind: Service
metadata:
  name: redis
  namespace: redis-system
spec:
  selector: { app: redis }
  ports:
  - port: 6379

2. Tell Envoy Gateway to use it

# eg-values.yaml
config:
  envoyGateway:
    rateLimit:
      backend:
        type: Redis
        redis:
          url: redis.redis-system.svc.cluster.local:6379
helm upgrade eg oci://docker.io/envoyproxy/gateway-helm --version v1.10.0 \
  -n envoy-gateway-system -f eg-values.yaml
kubectl rollout restart deploy/envoy-gateway -n envoy-gateway-system

3. The limits

apiVersion: gateway.envoyproxy.io/v1alpha1
kind: BackendTrafficPolicy
metadata:
  name: orders-limits
  namespace: shop
spec:
  targetRefs:
  - { group: gateway.networking.k8s.io, kind: HTTPRoute, name: orders }
  rateLimit:
    global:
      rules:
      - clientSelectors:                 # free plan: 5 requests per minute, per tenant
        - headers:
          - { name: x-tenant-plan, value: free }
          - { name: x-tenant-id, type: Distinct }
        limit: { requests: 5, unit: Minute }
      - clientSelectors:                 # standard plan: 20 requests per minute, per tenant
        - headers:
          - { name: x-tenant-plan, value: standard }
          - { name: x-tenant-id, type: Distinct }
        limit: { requests: 20, unit: Minute }

type: Distinct gives each tenant its own counter. Envoy Gateway starts an envoy-ratelimit deployment the first time a global limit is used:

$ kubectl wait --for=condition=Available deploy/envoy-ratelimit -n envoy-gateway-system
deployment.apps/envoy-ratelimit condition met
$ kubectl get backendtrafficpolicy orders-limits -n shop -o jsonpath='...conditions...'
Accepted=True Accepted Policy has been accepted.

4. Test with three tenants

G=$(python3 make-jwt.py token globex free)
I=$(python3 make-jwt.py token initech free)
A=$(python3 make-jwt.py token acme standard)
for i in $(seq 8); do curl -s -o /dev/null -w '%{http_code} ' -H 'Host: api.example.test' \
  -H "Authorization: Bearer $G" localhost:8080/orders; done
globex  (free)      x8:  200 200 200 200 200 429 429 429
initech (free)      x3:  200 200 200                       ← its own counter: globex's usage doesn't affect it
acme    (standard)  x8:  200 200 200 200 200 200 200 200   ← higher plan limit

$ curl -si -H 'Host: api.example.test' -H "Authorization: Bearer $G" localhost:8080/orders \
    | grep -i -E '^HTTP|x-ratelimit|retry-after'
HTTP/1.1 429 Too Many Requests
x-ratelimit-limit: 5, 5;w=60
x-ratelimit-remaining: 0
x-ratelimit-reset: 38
retry-after: 38

The headers tell the client the limit (5 per 60-second window), what's left, and when to come back.

What clients should do with a 429

  • Respect Retry-After; add random jitter so thousands of clients don't return at the same second.
  • Use exponential backoff for repeated 429s; never retry in a tight loop.
  • Read x-ratelimit-remaining and slow down before hitting zero.
  • Publish your limits in the API docs, per plan.

Designing limits for a product

  1. Measure normal usage per tenant (p50, p95, p99 of requests per minute).
  2. Set plan limits above normal peaks for that plan, below what one cell or service can absorb from a single tenant.
  3. Limit expensive endpoints separately (search, exports, bulk writes), or use cost-based limits.
  4. Add concurrency limits for slow operations.
  5. Alert when a tenant is limited often: it may need a bigger plan, or it may be an attack.
  6. Treat limits as tenant data (from the plan), not hard-coded numbers; the multi-tenant SaaS course covers the customer tenant lifecycle.

Try it

  1. Add a rule with no plan header that limits any request without a tenant to 2 per minute (anonymous traffic).
  2. Scale the gateway to 3 replicas (EnvoyProxy → replicas: 3) and show that globex still gets exactly 5 per minute: that's the point of global limits.
  3. Delete the Redis pod while sending requests. Do requests fail or pass? Find the setting that controls this behaviour.
  4. Add a stricter limit only for POST /orders with a path and methods selector.

Going deeper

  • Monthly quotas need durable usage counts tied to billing; gateways usually enforce short-window rate limits, while metering and quota checks run in the API-management product or the services.
  • Adaptive limits and load shedding drop low-priority traffic when the backend is unhealthy, regardless of per-tenant limits.
  • The IETF is standardising RateLimit and RateLimit-Policy response headers; many gateways still send x-ratelimit-*.

Recap

  • Rate limits absorb bursts; quotas enforce plans over long periods; concurrency limits protect slow backends.
  • Token bucket is the usual algorithm; fixed windows allow bursts at window edges.
  • Local limits multiply with replicas; global limits share counters (Redis) at the cost of a dependency.
  • Key per-tenant limits on verified identity, return 429 with Retry-After, and teach clients to back off.

This site is a public version of my personal engineering knowledge hub. It intentionally excludes confidential company information and internal operational details.