Skip to content
Blog

← All articles

Token Bucket Math: How Rate Limiters Allow Bursts but Enforce a Long-Term Average

The mathematics of rate limiting with bursts: why a token bucket never lets more than b + r·t requests through in any span of time, how fast the average converges to r, how long a burst lasts, why GCRA is the same limiter in one number, what fixed and sliding windows really allow, how to enforce a strict cap per hour, and a tested Redis implementation.

By 15 min read

Every API rate limit has to answer two questions that pull in opposite directions. Should a client that has been quiet be allowed to send twenty requests at once, the way a browser does when a page loads? Yes, or the service feels slow for no reason. Should a client be able to keep sending twenty requests a second forever? No, or the limit means nothing. The token bucket answers both with two numbers and one inequality, and the math behind it is short enough to prove in a paragraph.

This article works through that math: the guarantee, why it holds, how quickly the average settles, how long bursts last, and what the popular alternatives (fixed and sliding windows) actually let through. Every code example was run before publishing, including a Redis version tested with 20 concurrent clients.

The short answer#

Two numbers, one promise#

A rate limit with bursts is described by two parameters: the rate r (requests per second on average) and the burst b (how many requests may arrive at once). Together they define a promise about every stretch of time. If A(s, t) is the number of requests accepted between times s and t, then for all s ≤ t:

A(s, t) ≤ b + r · (t − s)

In network engineering, this is called an arrival curve, and a stream of traffic that satisfies it is “(b, r)-constrained”, a notation that goes back to Rene Cruz’s work on network delay in 1991. Read it as a straight line on a chart of cumulative requests: it starts at height b and rises with slope r. A client may get close to the line, but never above it, wherever you start measuring.

That one line gives both behaviors. For short spans, the b dominates: a client can send up to b requests instantly. For long spans, the r·t dominates: whatever happened at the start, the client can’t sustain more than r a second.

The token bucket#

The algorithm that enforces the line is almost a physical model. A bucket holds up to b tokens. Tokens drip in at r per second, and any that arrive while the bucket is full overflow and are lost. Each request takes one token, and a request that finds the bucket empty is rejected. There is no background timer: the refill is calculated from the time since the last request.

token-bucket.mjs
// token-bucket.mjs: the bucket holds up to `burst` tokens and refills at `rate` tokens per second.
// Each request takes a token; when none is left, the request is rejected.
export class TokenBucket {
  constructor(rate, burst, now = 0) {
    this.rate = rate;   // r: the long-term average, in requests per second
    this.burst = burst; // b: the bucket size, the largest burst
    this.tokens = burst; // start full
    this.last = now;    // time of the last update, in seconds
  }

  allow(now, cost = 1) {
    // Refill for the time that has passed, but never above the bucket size.
    this.tokens = Math.min(this.burst, this.tokens + (now - this.last) * this.rate);
    this.last = now;
    if (this.tokens < cost) return false;
    this.tokens -= cost;
    return true;
  }
}

if (import.meta.main) {
  let limiter = new TokenBucket(10, 100); // 10 requests a second on average, bursts of up to 100
  let accepted = 0;
  for (let i = 0; i < 1000; i++) if (limiter.allow(i / 1000)) accepted++; // 1,000 requests in one second
  console.log(accepted); // 109: the burst of 100, plus 9 tokens refilled during that second

  limiter = new TokenBucket(10, 100);
  accepted = 0;
  for (let i = 0; i < 60000; i++) if (limiter.allow(i / 1000)) accepted++; // keep going for a minute
  console.log(accepted, (accepted / 60).toFixed(2)); // 699 11.65: b + r*t = 100 + 10*59.999
}

One thousand requests in a single second got 109 through: the full bucket of 100, plus 9 tokens that dripped in during that second. Kept up for a minute, the same client got 699, an average of 11.65 a second, already close to the rate of 10. Here is a smaller bucket (r = 5, b = 20) facing a client that sends 25 requests a second, pauses, and sends again:

A client sends 25 requests a second for 4 seconds, pauses for 4 seconds, then sends again, to a token bucket with rate 5 per second and burst 20. Requests sent rise steeply to 200. Requests accepted rise quickly to 24 in the first second, then at 5 per second, reaching 39 at 4 seconds; they stay flat during the pause while the bucket refills to 20; then another burst and 5 per second, ending at 78. The accepted line never crosses the straight line 20 + 5t. Below, the bucket level drops from 20 to 0 within a second, refills during the pause, and drops again.SentAcceptedb + r·t0255075100010200 s2 s4 s6 s8 s10 s12 sRequests, cumulativeTokens in the bucketsent: 200 by 12 s ↑b + r·taccepted (78)0.0 s: 0 sent, 0 accepted, 20.0 tokens0.2 s: 5 sent, 5 accepted, 15.8 tokens0.4 s: 10 sent, 10 accepted, 11.8 tokens0.6 s: 15 sent, 15 accepted, 7.8 tokens0.8 s: 20 sent, 20 accepted, 3.8 tokens1.0 s: 25 sent, 24 accepted, 0.8 tokens1.2 s: 30 sent, 25 accepted, 0.8 tokens1.4 s: 35 sent, 26 accepted, 0.8 tokens1.6 s: 40 sent, 27 accepted, 0.8 tokens1.8 s: 45 sent, 28 accepted, 0.8 tokens2.0 s: 50 sent, 29 accepted, 0.8 tokens2.2 s: 55 sent, 30 accepted, 0.8 tokens2.4 s: 60 sent, 31 accepted, 0.8 tokens2.6 s: 65 sent, 32 accepted, 0.8 tokens2.8 s: 70 sent, 33 accepted, 0.8 tokens3.0 s: 75 sent, 34 accepted, 0.8 tokens3.2 s: 80 sent, 35 accepted, 0.8 tokens3.4 s: 85 sent, 36 accepted, 0.8 tokens3.6 s: 90 sent, 37 accepted, 0.8 tokens3.8 s: 95 sent, 38 accepted, 0.8 tokens4.0 s: 100 sent, 39 accepted, 0.8 tokens4.2 s: 100 sent, 39 accepted, 1.8 tokens4.4 s: 100 sent, 39 accepted, 2.8 tokens4.6 s: 100 sent, 39 accepted, 3.8 tokens4.8 s: 100 sent, 39 accepted, 4.8 tokens5.0 s: 100 sent, 39 accepted, 5.8 tokens5.2 s: 100 sent, 39 accepted, 6.8 tokens5.4 s: 100 sent, 39 accepted, 7.8 tokens5.6 s: 100 sent, 39 accepted, 8.8 tokens5.8 s: 100 sent, 39 accepted, 9.8 tokens6.0 s: 100 sent, 39 accepted, 10.8 tokens6.2 s: 100 sent, 39 accepted, 11.8 tokens6.4 s: 100 sent, 39 accepted, 12.8 tokens6.6 s: 100 sent, 39 accepted, 13.8 tokens6.8 s: 100 sent, 39 accepted, 14.8 tokens7.0 s: 100 sent, 39 accepted, 15.8 tokens7.2 s: 100 sent, 39 accepted, 16.8 tokens7.4 s: 100 sent, 39 accepted, 17.8 tokens7.6 s: 100 sent, 39 accepted, 18.8 tokens7.8 s: 100 sent, 39 accepted, 19.8 tokens8.0 s: 100 sent, 39 accepted, 20.0 tokens8.2 s: 105 sent, 44 accepted, 15.8 tokens8.4 s: 110 sent, 49 accepted, 11.8 tokens8.6 s: 115 sent, 54 accepted, 7.8 tokens8.8 s: 120 sent, 59 accepted, 3.8 tokens9.0 s: 125 sent, 63 accepted, 0.8 tokens9.2 s: 130 sent, 64 accepted, 0.8 tokens9.4 s: 135 sent, 65 accepted, 0.8 tokens9.6 s: 140 sent, 66 accepted, 0.8 tokens9.8 s: 145 sent, 67 accepted, 0.8 tokens10.0 s: 150 sent, 68 accepted, 0.8 tokens10.2 s: 155 sent, 69 accepted, 0.8 tokens10.4 s: 160 sent, 70 accepted, 0.8 tokens10.6 s: 165 sent, 71 accepted, 0.8 tokens10.8 s: 170 sent, 72 accepted, 0.8 tokens11.0 s: 175 sent, 73 accepted, 0.8 tokens11.2 s: 180 sent, 74 accepted, 0.8 tokens11.4 s: 185 sent, 75 accepted, 0.8 tokens11.6 s: 190 sent, 76 accepted, 0.8 tokens11.8 s: 195 sent, 77 accepted, 0.8 tokens12.0 s: 200 sent, 78 accepted, 0.8 tokens
A token bucket with rate 5/s and burst 20. Accepted requests (blue) jump with each burst, then follow the rate; the pause refills the bucket. They never cross the dashed line b + r·t.

The bucket empties within the first second, after which the client gets exactly one request through every 0.2 s. The four-second pause refills it completely, so the second burst is as large as the first. Of 200 requests, 78 got through, and the accepted line comes within half a request of the dashed line without ever crossing it.

Why it never exceeds b + r·t#

Pick any two moments s < t. At time s, the bucket holds at most b tokens, because it can never hold more. Between s and t, at most r·(t − s) new tokens can drip in; overflow only makes that smaller. Every accepted request removes one token, and the bucket can’t go below zero. So the requests accepted in between can’t exceed the tokens available:

A(s, t) ≤ tokens(s) + r·(t − s) ≤ b + r·(t − s)

That is the whole proof, and it holds for every pair of moments at once, which is what makes the guarantee strong. A limit that says “100 per minute” only applies to specific minutes; this one applies to every stretch of time. The bound is also tight: a client that waits until the bucket is full and then sends as fast as it can gets exactly ⌊b + r·t⌋, as the 699 above shows (100 + 10 × 59.999).

Our test checked it empirically too: random bursty traffic through three different buckets, with every one of about 7 billion spans between two accepted requests checked against the bound. None exceeded it, and the worst span reached it.

How the average converges#

Divide the bound by the length of the span, and you get the highest possible average over that span:

A(t) / t ≤ r + b / t

The burst’s contribution shrinks as 1/t. For the bucket above (r = 10/s, b = 100), the most a client can get is:

SpanAt mostAverageAbove the rate
1 s110110/s1,000%
10 s20020/s100%
1 min70011.667/s16.67%
1 h36,10010.028/s0.28%
1 day864,10010.001/s0.01%

Over a second, the burst allows eleven times the rate; over a minute, 17% more; over an hour, 0.28%. This is the precise sense in which a token bucket “enforces the average”: not by smoothing traffic, but by making the excess a fixed amount, b, that is spread over a longer and longer time.

How long a burst lasts#

Suppose a client with a full bucket starts sending at a constant peak rate p greater than r. Tokens leave at p and arrive at r, so the bucket drains at p − r:

  • The burst lasts b / (p − r) seconds.
  • It delivers p · b / (p − r) requests, slightly more than b, because tokens keep arriving during the burst.
  • After the client goes quiet, the bucket is full again after b / r seconds.

For r = 10/s and b = 100:

Client’s peak rateBurst lastsRequests in the burst
20/s10 s200
100/s1.111 s111.1
1,000/s0.101 s101

A slow client gets a long burst; a fast one gets a short one, but always about b requests. The refill time b/r, ten seconds here, is the useful number for choosing b: it is how long a client must be quiet to earn a full burst back.

GCRA: the same limit in one number#

A token bucket stores two numbers per client: the token count and the time of the last update. The Generic Cell Rate Algorithm, designed for ATM networks in the 1990s, stores one: the theoretical arrival time (TAT), when the client’s next request would be due if it had always sent at exactly the average rate. Each accepted request pushes the TAT forward by the interval T = 1/r. A request is rejected if the client is too far ahead of its schedule, by more than a tolerance τ:

gcra.mjs
// gcra.mjs: the same limit, stored as a single number per client: the "theoretical arrival time" (TAT),
// when the client's next request would be due if it had always sent at exactly the average rate.
export class Gcra {
  constructor(rate, burst) {
    this.interval = 1 / rate;                     // T: seconds between requests at the average rate
    this.tolerance = (burst - 1) * this.interval; // tau: how far ahead of schedule a client may get
    this.tat = -Infinity;
  }

  allow(now) {
    const tat = Math.max(this.tat, now); // an idle client can't bank more than a full bucket
    if (tat - now > this.tolerance) return false;
    this.tat = tat + this.interval;
    return true;
  }

  retryAfter(now) {
    // The next request is allowed once now >= TAT - tau.
    return Math.max(0, this.tat - this.tolerance - now);
  }
}

if (import.meta.main) {
  const limiter = new Gcra(10, 100);
  let accepted = 0;
  for (let i = 0; i < 1000; i++) if (limiter.allow(i / 1000)) accepted++;
  console.log(accepted); // 109, the same as the token bucket
  console.log(limiter.retryAfter(1).toFixed(3)); // 0.000: at t = 1 s the next token is due
  console.log(limiter.retryAfter(0.95).toFixed(3)); // 0.050
}

The two algorithms are the same limiter written in different units. The bucket’s token count is just the distance between the schedule and now, measured in intervals:

tokens = b − (TAT − now) / T

A request is allowed when at least one token remains (tokens ≥ 1), which rearranges to TAT − now ≤ (b − 1)·T. That is GCRA’s test with τ = (b − 1)·T. And “the bucket can’t hold more than b” becomes the max(TAT, now): a client that has been idle restarts from now, not from the past. Our test ran both implementations side by side on 200,000 random requests with four different settings, and they made the same decision every time.

GCRA has two practical advantages. It needs no floating-point token count, so it works in integer milliseconds. And it answers “when can I retry?” directly: the next request is allowed at TAT − τ, which is exactly what an HTTP 429 response’s Retry-After header should say.

Leaky bucket: meter or queue#

“Leaky bucket” is used for two different things, which is the source of most confusion about it:

  • The leaky bucket as a meter is a bucket that fills by one with each request and leaks at rate r; a request that would overflow it is rejected. That is the token bucket upside down (counting used capacity instead of remaining capacity), and it accepts exactly the same requests.
  • The leaky bucket as a queue holds up to b waiting requests and releases them at exactly rate r. Nothing passes faster than r, so there are no bursts downstream at all, at the cost of latency: a request may wait up to b/r seconds in the queue.

The difference is policing versus shaping. Policing (the meter, the token bucket, GCRA) rejects excess traffic immediately and lets bursts through. Shaping (the queue) delays excess traffic and smooths it. APIs police, because a client is better served by a fast 429 than by a request that hangs. Outbound traffic, such as calls you make to someone else’s rate-limited API, is usually better shaped.

What window counters really allow#

Many rate limiters count requests per window instead: “100 requests per minute”. They are simple, but they don’t let you choose an arrival curve, and their worst case is worse than it looks. We sent the same pattern to two of them, 100 requests in the last half second of a minute and then as many as each limiter would accept:

windows.mjs
// windows.mjs: two popular counters, "100 requests per minute", and what they let through.
export class FixedWindow {
  constructor(limit, seconds) {
    Object.assign(this, { limit, seconds, window: -1, count: 0 });
  }
  allow(now) {
    const w = Math.floor(now / this.seconds);
    if (w !== this.window) [this.window, this.count] = [w, 0]; // a new minute: start from zero
    if (this.count >= this.limit) return false;
    this.count++;
    return true;
  }
}

export class SlidingWindowCounter {
  constructor(limit, seconds) {
    Object.assign(this, { limit, seconds, window: 0, count: 0, previous: 0 });
  }
  allow(now) {
    const w = Math.floor(now / this.seconds);
    if (w !== this.window) [this.previous, this.window, this.count] = [w === this.window + 1 ? this.count : 0, w, 0];
    // Estimate the last full minute, assuming the previous minute's requests were spread evenly.
    const elapsed = now / this.seconds - w;
    if (this.previous * (1 - elapsed) + this.count >= this.limit) return false;
    this.count++;
    return true;
  }
}

// The most requests a limiter accepted in any 60-second span.
const busiest = (times) => {
  let most = 0;
  for (let i = 0, j = 0; i < times.length; i++) {
    while (times[i] - times[j] >= 60) j++;
    most = Math.max(most, i - j + 1);
  }
  return most;
};

if (import.meta.main) {
  // A burst just before the minute changes, then as many requests as the limiter will take.
  const send = (limiter) => {
    const accepted = [];
    for (let i = 0; i < 100; i++) if (limiter.allow(59.5 + i * 0.005)) accepted.push(59.5 + i * 0.005);
    for (let t = 60; t < 120; t += 0.01) if (limiter.allow(t)) accepted.push(t);
    return busiest(accepted);
  };
  console.log(send(new FixedWindow(100, 60))); // 200 in under a second
  console.log(send(new SlidingWindowCounter(100, 60))); // 200 in under a minute
}

The fixed window resets its counter at the start of every minute, so 100 requests at 0:59.5 and 100 more at 1:00.0 all pass: 200 in under a second. The sliding window counter, which estimates the last 60 seconds from the current and the previous minute, does better at the boundary, but its estimate assumes the previous minute’s requests were spread evenly. When they all came at the end, it forgets them too early, and the same client got 200 requests into a single 60-second span.

AlgorithmMost requests in any 60 s, for “100 per minute”State per clientBurst
Fixed window200 (measured)A counter and the window’s numberUp to 2 × limit, at boundaries
Sliding window counter200 (measured, worst case)Two countersDepends on the traffic’s shape
Sliding window log100, exactlyA timestamp for every request in the windowUp to the limit, at once
Token bucket, GCRAb + 60·r, chosen by youTwo numbers, or oneb, a parameter

The sliding window counter is a good approximation for ordinary traffic, which tends to be spread out, and the sliding log is exact, but stores a timestamp for every request. The deeper difference is that window limiters have a burst whether you want one or not, and its size is fixed by the window. A token bucket makes the burst a separate number, and its guarantee covers every span of time rather than one window length.

Enforcing a strict cap#

A contract often says something like “no more than 1,000 requests per hour”. A token bucket with r = 1,000/hour and b = 1,000 doesn’t enforce that: by the bound, it allows up to 2,000 in the first hour. To guarantee at most N in any window of length W, the line must stay below N at W:

b + r·W ≤ N

So the burst has to come out of the hourly budget. With b = 100, the rate can be at most 900 an hour. If you also want to stop short, sharp bursts, add a second, faster limit, and require a request to pass both. The important detail is to charge a request only when every limit allows it, so a rejection by one limit doesn’t use up another:

layered.mjs
// layered.mjs: a request must pass every limit, and only then is it charged to all of them.
import { Gcra } from "./gcra.mjs";

export class Layered {
  constructor(...limits) {
    this.limits = limits;
  }
  allow(now) {
    const due = this.limits.map((l) => Math.max(l.tat, now));
    if (this.limits.some((l, i) => due[i] - now > l.tolerance)) return false; // charge nothing on a rejection
    this.limits.forEach((l, i) => (l.tat = due[i] + l.interval));
    return true;
  }
}

if (import.meta.main) {
  // Bursts of up to 50 at 10 a second, and never more than 1,000 in any hour: 100 + 900 per hour <= 1,000.
  const limiter = new Layered(new Gcra(10, 50), new Gcra(900 / 3600, 100));
  const accepted = [];
  for (let i = 0; i < 720000; i++) if (limiter.allow(i / 100)) accepted.push(i / 100); // 100 a second for 2 hours

  let busiestHour = 0;
  for (let i = 0, j = 0; i < accepted.length; i++) {
    while (accepted[i] - accepted[j] >= 3600) j++;
    busiestHour = Math.max(busiestHour, i - j + 1);
  }
  console.log(accepted.length, busiestHour); // 1899 999: never more than b + r*t, with t just under an hour
}

Two hours of a client asking 100 times a second produced 1,899 accepted requests, and no hour-long span had more than 999. The combined limit is the lower of the two lines at every point: min(50 + 10t, 100 + 0.25t). This is the shape of most real API plans: a per-second limit with a small burst for responsiveness, under a daily or monthly quota for cost.

One limit across many servers#

A limiter in one process only sees that process’s traffic. With several API servers, the state has to be shared, and the read-check-write has to be atomic, or two servers can both see the last token and both spend it. GCRA’s single number makes this a short Redis script, which Redis runs atomically:

gcra.lua
-- gcra.lua: GCRA as a Redis script, so every app server shares one limit per key.
-- KEYS[1] = the client's key, ARGV[1] = interval T in ms, ARGV[2] = tolerance tau in ms.
-- Returns {1, 0} if allowed, or {0, ms to wait} if not.
local t = redis.call("TIME") -- Redis's clock, so the app servers' clocks don't matter
local now = t[1] * 1000 + math.floor(t[2] / 1000)
local interval, tolerance = tonumber(ARGV[1]), tonumber(ARGV[2])

local tat = math.max(tonumber(redis.call("GET", KEYS[1])) or now, now)
if tat - now > tolerance then
  return {0, tat - tolerance - now}
end
tat = tat + interval
redis.call("SET", KEYS[1], tat, "PX", tat - now) -- once TAT has passed, a missing key means the same thing
return {1, 0}
redis-limit.mjs
// redis-limit.mjs: call the script from Node.js (ioredis) and answer like an HTTP API would.
import { readFileSync } from "node:fs";
import Redis from "ioredis";

const redis = new Redis(process.env.REDIS_URL ?? "redis://localhost:6379");
redis.defineCommand("gcra", { numberOfKeys: 1, lua: readFileSync(new URL("./gcra.lua", import.meta.url), "utf8") });

export async function limit(clientId, rate, burst) {
  const interval = Math.round(1000 / rate);
  const [ok, waitMs] = await redis.gcra(`rate:${clientId}`, interval, (burst - 1) * interval);
  return ok === 1 ? { status: 200 } : { status: 429, headers: { "Retry-After": Math.ceil(waitMs / 1000) } };
}

if (import.meta.main) {
  const results = [];
  for (let i = 0; i < 25; i++) results.push((await limit("demo", 10, 20)).status);
  console.log(results.filter((s) => s === 200).length, results.at(-1)); // 20 429: the burst, then "slow down"
  await redis.quit();
}

A few choices in the script matter:

  • The clock comes from Redis (TIME), not from the app servers, so servers with slightly different clocks still share one consistent schedule.
  • The key expires when the bucket would be full again. After that, a missing key and an old TAT mean the same thing, so idle clients cost no memory.
  • Integer milliseconds: GCRA needs no fractional tokens.

We tested the script with 20 connections hammering one key for three seconds at r = 50/s and b = 25. Out of more than 320,000 attempts, 175 were accepted, against a bound of b + r·t = 175.0, and no rejected client was ever told to wait more than one interval.

FAQ#

Should a new bucket start full or empty?

Full is the usual choice: a new client, or one returning after a pause, gets its burst immediately, which is what the burst is for. Starting empty is more conservative, for example to stop a flood of new accounts from each getting a burst, but it makes the first requests after a deploy or a cache flush slower for everyone.

How do I limit requests that cost different amounts?

Give each request a cost and take that many tokens; allow(now, cost) above does exactly that. The bound becomes a bound on total cost: at most b + r·t units in any span. In GCRA, a request of cost c is allowed if TAT − now ≤ τ − (c − 1)·T, and moves the TAT forward by c·T. A request that costs more than b can never pass, so make the bucket at least as big as the most expensive request.

Should the limit be per user, per IP address, or per API key?

Per whatever identifies who pays for the traffic, usually the API key or account. IP addresses are shared by everyone behind a corporate proxy or a mobile carrier’s NAT, and one attacker can have many. Many APIs use both: a generous per-IP limit before authentication, and the real limits per key after it.

What should a rejected request return?

HTTP 429 Too Many Requests, with a Retry-After header computed from the TAT, as in the Redis example. Clients that honor it retry exactly when a token is available instead of hammering the limiter.