JavaScriptMedium
Implement a rate limiter
A rate limiter caps how many operations happen in a time window; the token bucket algorithm is the common choice because it allows short bursts while enforcing an average rate: tokens refill at a steady rate, each operation consumes one, and operations without a token are rejected or queued.
Common algorithms
- Token bucket: capacity
C, refillRtokens per second. Allows bursts up toC, averagesR/s. Used by many APIs and cloud providers. - Leaky bucket: requests drain at a fixed rate; smooths traffic, no bursts.
- Fixed window: count requests per calendar window (e.g. per minute). Simple, but allows double bursts at window edges.
- Sliding window log/counter: tracks timestamps (or weighted counts) in a rolling window for accuracy without the edge problem.
Client-side vs server-side
- Client side: avoid hitting a third-party API's limits, throttle expensive user actions, or space out analytics. Queue operations until a token is available instead of failing.
- Server side: protect your API per user, IP or API key. Return 429 Too Many Requests with
Retry-Afterand rate-limit headers. With several servers, store counters in a shared store (Redis) or use the platform's built-in limiting (API gateways, edge middleware).
Implementation notes
- Refill lazily: compute tokens from the elapsed time when a request arrives instead of running a timer.
- Use a monotonic clock (
performance.now()) so system clock changes do not break it. - Expose remaining tokens and the wait time so callers can tell users when to retry.
Code example
js
1class TokenBucket {2 constructor({ capacity, refillPerSecond }) {3 this.capacity = capacity;4 this.refillPerMs = refillPerSecond / 1000;5 this.tokens = capacity;6 this.last = performance.now();7 }8 #refill() {9 const now = performance.now();10 this.tokens = Math.min(this.capacity, this.tokens + (now - this.last) * this.refillPerMs);11 this.last = now;12 }13 tryRemove(cost = 1) {14 this.#refill();15 if (this.tokens >= cost) {16 this.tokens -= cost;17 return { allowed: true, remaining: Math.floor(this.tokens) };18 }19 return { allowed: false, retryAfterMs: Math.ceil((cost - this.tokens) / this.refillPerMs) };20 }21 // Wait for a token instead of failing (client-side use)22 async removeAsync(cost = 1) {23 for (;;) {24 const r = this.tryRemove(cost);25 if (r.allowed) return r;26 await new Promise((res) => setTimeout(res, r.retryAfterMs));27 }28 }29}3031// Burst of 5 allowed, then ~10 per second32const limiter = new TokenBucket({ capacity: 5, refillPerSecond: 10 });33const results = Array.from({ length: 8 }, () => limiter.tryRemove().allowed);34console.log(results); // [true, true, true, true, true, false, false, false]3536const blocked = limiter.tryRemove();37console.log(`429 Too Many Requests, Retry-After ~${blocked.retryAfterMs}ms`);3839// Queue instead of rejecting: 3 extra calls get spaced out at ~100ms each40const started = performance.now();41for (let i = 0; i < 3; i++) await limiter.removeAsync();42console.log(`3 queued calls finished after ~${Math.round((performance.now() - started) / 100) * 100}ms`); // ~300ms
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.