Resources / Guides
API rate limiting algorithms: fixed window, sliding window and token bucket
How the common API rate limiting algorithms work, where each one breaks, and which to pick for bursts, fairness and simplicity.
"60 requests per minute" sounds precise, but there are several ways to count it — and they disagree exactly when it matters: at the edges of a window, and during bursts.
Fixed window
Count requests in calendar buckets — 12:00:00–12:00:59, 12:01:00–12:01:59 — and reject once the count passes the limit.
- Pros: one counter per client per window; trivial to build with an atomic increment and an expiry.
- Cons: a client can send 60 requests at 12:00:59 and 60 more at 12:01:00 — double the limit in two seconds.
// Fixed window with an atomic counter that expires with the window.
const window = Math.floor(Date.now() / 60_000);
const count = await kv.incr('rl:' + clientId + ':' + window, 1, { ttl: 60 });
if (count > 60) return { status: 429, headers: { 'retry-after': '60' } };
Sliding window log
Store the timestamp of every request and count those in the last 60 seconds.
- Pros: exact. No edge bursts.
- Cons: memory grows with traffic — 60 timestamps per client per minute, more for bigger limits.
Sliding window counter
Keep the fixed-window counts for the current and previous window, and weight the previous one by how much of it still overlaps the last 60 seconds:
estimate = current + previous × (seconds left in the previous window ÷ 60)
- Pros: nearly as smooth as the log, with only two counters.
- Cons: an approximation — fine for APIs, not for billing.
Token bucket
Each client has a bucket of N tokens that refills at a steady rate (say one per second). Each request takes a token; an empty bucket means 429.
- Pros: allows short bursts up to N while holding the long-run rate steady — the behaviour most clients expect.
- Cons: two values per client (tokens and last refill time) that must be updated atomically.
Leaky bucket
Requests queue and drain at a fixed rate. It smooths traffic into a downstream system that can't handle bursts at all, at the price of added latency. Gateways use it more than application APIs do.
Which one to use
| Need | Pick |
|---|---|
| Simple, good enough for most APIs | Fixed window, with a daily quota on top |
| Smooth limits without bursts at window edges | Sliding window counter |
| Allow short bursts, steady average | Token bucket |
| Protect a fragile downstream system | Leaky bucket / queue |
Whatever you choose, enforce it before expensive work happens and answer with 429 plus Retry-After — see API rate limit best practices.
In Wisp
You don't have to build any of this for your endpoints: project and endpoint limits (per minute and per day, for everyone or per client) are enforced by the platform before your code runs. If you need custom logic — say, a limit per customer plan — the atomic kv.incr with a ttl shown above works in any Wisp endpoint.
Build it with Wisp — describe an API, get it live.