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.
| Time | Tokens before | Requests | Result |
|---|---|---|---|
| 0 ms | 5 | 6 | 5 allowed, 1 denied |
| 1,200 ms | 2.4 | 3 | 2 allowed, 1 denied |
| 5,000 ms | 5 (8 capped) | 5 | 5 allowed |
02Every replica grants the full limit
Every replica grants the full limit
Predict the three lines this program prints.
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.
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.
05Settings that fit
Settings that fit
| Setting | n·B and n·r | Result |
|---|---|---|
| 3 replicas, burst 200, 20/s | 600, 60 | overflows at once |
| 3 replicas, burst 100, 20/s | 300, 60 | fits |
| 4 replicas, burst 50, 20/s | 200, 80 | touches at 20s; exceeds after |
| 4 replicas, burst 75, 18/s | 300, 72 | fits |
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.
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.
// 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
Sources
- Go: golang.org/x/time/rate
- Rust: governor
- RFC 2697: a single rate three color marker (token buckets)
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.
Sign in to keep your read marks on every device. Sign in
Was this helpful?