← Math
Math

Rate limiting math

Why did a limit that fits one receiver overflow it?

Check a token bucket’s burst and refill against the receiver, including every replica that enforces it.

Outcome

Model one bucket exactly, add up the limit over every replica, find when it overflows the receiver, and choose a burst that fits a backlog and a catch-up window.

Terminology (6)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Token bucket
A limiter holding up to B tokens that refill at r per second; a request spends tokens equal to its cost or is denied.
Burst
The bucket capacity B: how much a client can send at once after being idle.
Refill rate
The tokens added per second, r, which is the sustained rate the limit allows.
Arrival line
n(B + rt): the most work n full buckets can admit in any interval of length t.
Absorption line
Q + St: what an empty queue with room Q and a busy server at S per second can take in over time t.
Backlog
Work already waiting in the queue, which uses up part of its room.

Why this matters

A rate limit is usually set by looking at one client and one server. Production has several replicas enforcing it, clients that save up their burst, and a downstream that already has work queued. The arithmetic for all three is two straight lines, and it tells you which setting to change before the receiver finds out for you.

This lesson assumes rates, units and floor division.

What a token bucket permits

A token bucket holds up to B tokens and gains r per second. A request spends its cost in tokens or is denied. The stored tokens permit a burst; the refill rate limits the continuing supply. Idle time cannot accumulate tokens beyond the cap.

Separate per-process buckets each grant that allowance. To size them for one receiver, combine their bursts and refill rates, then compare admitted work with available room and service over the relevant time window.

01One token bucket

One token bucket

Each merchant may receive a burst of 200 webhook deliveries and then 20 per second. The merchant’s receiver queues 300 and handles 75 per second, so the limit was approved. Then the endpoint came back from an outage, three dispatcher replicas each spent a full bucket, and 300 deliveries were refused.

To check the refill and cap in isolation, use a smaller bucket first; the same state rule governs each dispatcher. Here B = 5 and r = 2, with every request costing one token.

A bucket of 5 tokens refilling 2 per second
TimeTokens beforeRequestsResult
0 ms565 allowed, 1 denied
1,200 ms2.432 allowed, 1 denied
5,000 ms5 (8 capped)55 allowed
Why does the bucket hold 5 tokens at 5,000 ms and not 8?

02Every replica grants the full limit

Every replica grants the full limit

Predict the three lines this program prints.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const [burst, refill] = [200, 20]; // per merchant, in every replica
const [queue, service] = [300, 75]; // the merchant's receiver
const replicas = 3;

console.log(
  burst <= queue && refill <= service ? "one bucket fits" : "one bucket overflows"
);
console.log(replicas * burst, replicas * refill); // admitted at once, then per second
console.log(Math.floor(queue / replicas)); // largest burst per replica

Each dispatcher replica keeps its buckets in memory, so the merchant’s limit is really three limits. After the outage all three spend a full bucket together: 600 deliveries against a queue of 300. The largest burst each replica can grant is ⌊300 / 3⌋ = 100.

Node.js and browsers have no built-in limiter. A few lines like the lab’s, with tokens kept as integer thousandths, stay exact.

03When the lines cross

When the lines cross

Over any stretch of t seconds, n buckets can admit at most n(B + rt). Here Q limits all outstanding work, including in-service work, and S is a continuous work-conserving service guarantee. We use a fluid envelope, not the exact completion times of discrete deliveries: admitted work is at most n(B+rt), and room plus service is Q+St. Keeping the arrival envelope below that line is a conservative no-overflow condition under these assumptions. An envelope violation identifies a possible overload, not a measured rejection count for every traffic trace.

Suppose the burst is cut to 50 and the autoscaler adds a fourth replica. The burst line starts at 200, under 300. But four replicas refill 80 per second against 75 served, so the queue gains 5 every second and the lines cross at (300 − 200) / (80 − 75) = 20 seconds.

A capacity note checks that 4 × 50 = 200 fits a queue of 300. What does it miss?

04Backlog and a catch-up window

Backlog and a catch-up window

Work already queued takes room first. With 20 deliveries waiting, a 10-second catch-up and the four replicas above, the gap between the lines grows by 5 a second, so the tightest point is the end of the window: n·B ≤ 300 − 20 − 5 × 10 = 230, and B ≤ ⌊230 / 4⌋ = 57.

When the refill fits, for example three replicas at 60 per second, the gap shrinks over time and the tightest point is t = 0: B ≤ ⌊(300 − 20) / 3⌋ = 93.

Four replicas, 20 per second each, a 60-second catch-up and an empty queue. What burst fits?

05Settings that fit

Settings that fit

Per-replica settings against a queue of 300 and 75 served per second
Settingn·B and n·rResult
3 replicas, burst 200, 20/s600, 60overflows at once
3 replicas, burst 100, 20/s300, 60fits
4 replicas, burst 50, 20/s200, 80touches at 20s; exceeds after
4 replicas, burst 75, 18/s300, 72fits

06Fit the limit to the receiver

Fit the limit to the receiver

First inspect a small bucket’s exact refill/cap behavior, then apply that rule to all dispatcher replicas. The last request adds the receiver’s existing backlog and a finite recovery window: checking only the initial burst can miss refill that consumes the remaining room before recovery ends.

A replicated limit

One bucket, every replica together, then the burst for a catch-up.

  1. easy · M-RATE-V4-1 One bucket
  2. medium · M-RATE-V4-2 Every replica together
  3. hard · M-RATE-V4-3 Burst for a catch-up
In the frontend A token bucket for a search box in Next.js and Svelte Optional

A search box that fires on every keystroke can use a small bucket: a few quick searches, then a steady rate, and a message instead of a request when the bucket is empty. Each open tab has its own bucket, so the server still needs its own limit.

Estimate.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// A client-side token bucket: a full burst of searches, then 2 per second.
export function createBucket(burst: number, perSecond: number) {
  let tokens = burst;
  let last = performance.now();

  return function take(): boolean {
    const now = performance.now();
    tokens = Math.min(burst, tokens + ((now - last) / 1000) * perSecond);
    last = now;

    if (tokens < 1) return false;

    tokens -= 1;

    return true;
  };
}

const take = createBucket(5, 2);

export async function search(query: string): Promise<Response | null> {
  if (!take()) return null; // the caller shows "Slow down" instead of sending

  return fetch(`/api/search?q=${encodeURIComponent(query)}`);
}

Check this idea later
One bucket fits the receiver. When can the deployment still overflow it?
When is t = 0 the tightest point for the burst?
Sources

Values above were computed in Node 22 and run in Go 1.27, Rust 1.99 and Apple clang 17. The dispatcher and receiver are a worked model.

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.