What you're building
A token-bucket rate limiter — the most common algorithm for API throttling used by Stripe, Twilio, Cloudflare, and virtually every production API gateway.
How it works
Imagine a bucket that holds tokens:
- The bucket starts full (capacity
N). - Each accepted request consumes one token.
- Tokens refill at a steady rate (e.g. 2 tokens per second).
- If the bucket is empty, the request is rejected.
Unlike a fixed window, this naturally handles bursts up to the bucket size while enforcing a sustained average.
Requirements
Build a TokenBucket class that accepts (capacity, refillPerSecond):
consume(key)— attempt to take one token for the given key. Returntrue(allowed) orfalse(throttled).- Each key gets its own independent bucket.
- Refill is virtual — compute how many tokens have accrued since the last request using elapsed time; do not use
setInterval. - Bucket never exceeds
capacity.
Stretch goals
consumeN(key, n)— consume N tokens in a single call (batch requests).peek(key)— return the current approximate token count without consuming.
What this proves
You understand token-bucket theory, floating-point time math, per-key state management, and can implement throttling without side-effecting timers — the same approach used in Nginx's limit_req module.
⚡ 40 XP
solution.jsRuns in your browser
Loading editor…
Tests4 to pass
fresh bucket allows up to capacity
bucket blocks when empty
independent keys do not share tokens
returns false not undefined when empty
Run your code to check these.