Skip to content

Lesson 5 of 13 · 18m

Rate Limiting and Backpressure

Fixed-window, sliding-log, and token-bucket limiters at the edge and in the app — plus bounded concurrency and load shedding for when offered work exceeds capacity.

A rate limiter is a counter and a decision: INCR rl:ip:203.0.113.9 in Redis, EXPIRE 60 on first hit, and over the limit you return 429 with Retry-After. Doing it atomically needs a Lua script or pipeline — INCR then EXPIRE as separate commands races a crash between them and leaves a key with no TTL, counting forever.

The algorithms, honestly

Fixed-window counter. Count per window (rl:{user}:{minute}). Simple, tiny memory; the flaw is the boundary — a limit of 100/min still permits 100 requests at :59 plus 100 at :01, two hundred in two seconds, compliant.

Sliding-window log. A sorted set per client: ZADD the timestamp, ZREMRANGEBYSCORE to drop entries older than the window, ZCARD to count. Accurate at boundaries; pays memory for every request kept.

Token bucket. A bucket holds N tokens, refills at r/sec, each request spends one — allows a burst, then throttles to the fill rate. This is what production APIs actually mean by "rate limit," and it's why you can burst against GitHub's API and then settle to the sustained cap. They ship the state back to you: x-ratelimit-limit, x-ratelimit-remaining, x-ratelimit-reset.

GCRA (generic cell rate algorithm — what redis-cell and most library limiters implement) is token bucket with O(1) state: one timestamp per key instead of a bucket structure. When you can't justify a sorted set, it's the usual answer.

Leaky bucket — the mirror: requests queue and drain at a fixed rate. Nginx's limit_req is one:

limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
server {
    location /api/ { limit_req zone=api burst=20 nodelay; }
}

burst=20 queues 20 excess requests and drains them at 10r/s; nodelay serves the burst immediately, then enforces the rate.

Enforce at the edge first

The app is the wrong place to absorb abuse — by the time your framework runs code, the request already cost a worker. limit_req/limit_conn, Cloudflare rate-limiting rules, or WAF rules on the ALB reject cheap junk before it reaches a backend. Per-user and per-tenant limits belong in the app (the edge can't see your account_id); per-IP limits belong at the edge.

Honest 429s

429 + Retry-After: 17 + x-ratelimit-* headers lets a good client back off instead of hammering. A 429 without the retry hint is a dare to retry immediately — your own clients become the load.

Backpressure is the bigger idea

Rate limiting rejects requests by policy. Backpressure protects the system when offered work exceeds capacity — and the honest version is shedding. Bounded queues and concurrency caps: a service that can do 500 concurrent items takes 500 and 503s the rest fast, instead of accepting 5,000 and melting them all. Netflix's concurrency-limits library measures a moving RTT floor and sheds work when latency says the system is saturating — the limit adapts instead of being guessed.

Fairness matters more than limits: one tenant burning 90% of capacity starves everyone else, so per-tenant caps in the app — not just per-IP at the edge. Sizing is Little's law: concurrency = arrival rate × latency. A 500-item concurrency bound at 200ms per item is a 2,500 req/s ceiling — a number you can check against offered load instead of a guess.

Retries are the amplifier: a downstream dependency slows, every upstream retry adds load, and uncapped instant retries multiply request volume three to five times — a partial outage becomes total. Cap retries, back off exponentially, and add jitter; AWS's "Exponential Backoff and Jitter" piece exists because synchronized retries create thundering herds.

On July 2, 2019, Cloudflare pushed a WAF rule that ran expensive regexes on every request; CPU exhausted globally within minutes and a large slice of the internet returned 502s. That is the shape backpressure exists for: offered work exceeded capacity with nothing between "fine" and "down."

Practice

Edge limits by IP, app limits by user. Token bucket with headers clients can read. Bounded concurrency inside; shed 503 early rather than melting late. Cap every retry and jitter it.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.