Rate Limiting Algorithms
Protect services from abuse and overload with token bucket, leaky bucket, fixed window and sliding window limiters, applied per user, key or IP.
Intermediate · about 3 hours · difficulty 3/5
Learn first: Reverse Proxies and API Gateways
A rate limiter caps how many requests a client can make in a time window. It protects you from abuse (OTP spam, scraping, credential stuffing), keeps one noisy customer from hurting others, and controls cost on paid downstream APIs.
Algorithms
- Token bucket: a bucket holds up to B tokens, refilled at R per second. Each request takes a token. Allows short bursts up to B while enforcing an average rate. The most common choice (used by AWS and Stripe style limiters).
- Leaky bucket: requests enter a queue that drains at a fixed rate. Smooths traffic into a steady flow; bursts wait or are dropped.
- Fixed window counter: count requests per calendar minute. Simple, but a client can send 2x the limit across a window boundary.
- Sliding window log: store each request timestamp and count those in the last N seconds. Exact, memory hungry.
- Sliding window counter: blend the current and previous window counts by overlap. Close to exact with tiny memory.
What to limit on
User ID, API key, IP address, phone number (for OTP endpoints), or a combination. Different endpoints deserve different limits: login and OTP very strict, product browsing generous.
Responding
Return 429 Too Many Requests with a Retry-After header and, ideally, X-RateLimit-Limit / Remaining headers so good clients can back off.
Where it lives
At the API gateway or edge for coarse limits, in services for business limits (5 OTPs per phone per hour). The full distributed version (shared counters in Redis, race conditions, multi-region) is covered as a case study later.
Pitfalls
- Limiting only by IP, which punishes everyone behind one college or office NAT.
- Fixed windows that let double bursts through at the boundary.
- No limits on expensive endpoints like search or report export.
You are ready to move on when you can simulate token bucket and sliding window counter by hand for a sequence of requests and explain which one you would use for an OTP endpoint.
Key concepts
- Token bucket
- Leaky bucket
- Fixed window counter
- Sliding window log and counter
- Choosing limit keys
- 429 and Retry-After
Mini project
Implement token bucket, fixed window and sliding window counter limiters as middleware in a small API. Fire a scripted burst pattern at each and plot allowed vs rejected requests over time.
Check yourself
With a fixed window of 100 requests per minute, how can a client send 200 requests within about 2 seconds, and which algorithm prevents it?
Free resources
- Scaling your API with rate limiters (Stripe)
- Token bucket (Wikipedia)
- Rate limiting pattern (Microsoft)