Load/Bearing
Fundamentals · 09 of 22

Rate limiting

Decide how much each client may ask for, and say no early and cheaply when they ask for more.

4 min readUsed in: 8 · Bot Swarm

A rate limiter caps how many requests a client can make in a period of time. It protects you from abuse (scrapers, credential stuffing, a buggy client stuck in a retry loop), keeps one tenant from starving the others, and controls costs when each request calls something expensive. It's also load shedding: turning away excess work cheaply at the door instead of letting it overload the database.

A rejected request gets HTTP 429 Too Many Requests, ideally with a Retry-After header so well-behaved clients know when to come back.

Where it runs and what it counts

The algorithms

AlgorithmHow it worksMemory per keyTrade-off
Fixed windowCount requests per clock window (e.g. per minute). Reset at the boundary.1 counterSimple, but allows 2× the limit across a boundary: 100 at 0:59 and 100 at 1:00.
Sliding window logStore a timestamp per request. Count those in the last N seconds.1 entry per requestExact, but memory grows with traffic.
Sliding window counterWeight the previous window's count by how much of it still overlaps.2 countersClose to exact, very cheap. A common production choice.
Token bucketA bucket holds up to B tokens and refills at R per second. Each request spends one.tokens + timestampAllows bursts up to B while holding the average to R.
Leaky bucketRequests join a queue that drains at a fixed rate R.a queuePerfectly smooth output, but bursts wait or get dropped.

Sliding window counter

limit = 100/min, we are 15 s into the current minute previous minute: 80 requests, current minute so far: 30 estimate = 30 + 80 × (45 / 60) = 90 → allow (90 < 100)

Token bucket

A token bucket answers "how big a burst is acceptable?" separately from "what's the long-run rate?". You don't need a timer to add tokens. Store the token count and the time of the last update, and top it up lazily on each request:

def allow(bucket, now): bucket.tokens = min(B, bucket.tokens + (now - bucket.last) * R) bucket.last = now if bucket.tokens >= 1: bucket.tokens -= 1 return True return False

With B = 20 and R = 5 per second, a client can fire 20 requests at once, then gets 5 per second after that. In a multi-threaded server, wrap the read-modify-write in a lock per bucket, or use an atomic compare-and-swap.

Token vs leaky bucket: a token bucket lets bursts through immediately if tokens are saved up. A leaky bucket used as a queue smooths every burst into a steady stream, which suits protecting a downstream system that can only take a fixed rate.

Per-user limits without unbounded memory

One bucket per user, kept forever, grows without limit as new users and IPs appear. Two fixes:

Distributed rate limiting

With N app servers behind a load balancer, a counter in each server's memory lets a client get N times the limit. The options:

Decide what happens when Redis is down. Fail open (allow everything) keeps the product working but drops protection. Fail closed (reject everything) is safer for expensive or security-sensitive endpoints such as login. Many systems fail open with a local in-memory limiter as a backstop.

Telling clients

HTTP/1.1 429 Too Many Requests Retry-After: 12 RateLimit-Limit: 100 RateLimit-Remaining: 0 RateLimit-Reset: 12

Client libraries should back off with jitter when they see 429. Otherwise every rejected client retries at the same moment and the spike repeats.

In the game: in Bot Swarm, 70% of the traffic is bots and a third of real users share office IPs. Limiting by IP blocks those users; limiting by API key doesn't. A fixed window lets the bots double up at every reset, which shows as an error spike every 10 seconds. A sliding window or token bucket removes it.

Interview checklist

Practise it

Level 8: Bot Swarm

Put this into practice against live traffic. Your progress in the game is saved in your browser.

Play level 8
Workshop drill

Do it by hand

Interactive drills for the parts the simulator can't show. Scored, with your best result saved in your browser.

Token bucket

Further reading