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.

// 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.

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)

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.

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

NeedPick
Simple, good enough for most APIsFixed window, with a daily quota on top
Smooth limits without bursts at window edgesSliding window counter
Allow short bursts, steady averageToken bucket
Protect a fragile downstream systemLeaky 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.

Related