Suryanand/ Bootcamp
suryanand.com ↗Let's talk
Frame · dsa / ai-algorithms / 12-token-bucket-rate-limiter.jsJavaScript

Token Bucket Rate Limiter for Tokens-Per-Minute Budgets

Use the tabs to read the prompt, implementation, and tests separately. Syntax uses Shiki; tests can be executed on the server with node --test.

Same file as in the repo · ~20s timeout

From file header (JSDoc)

Token Bucket Rate Limiter for Tokens-Per-Minute Budgets

Problem: LLM providers enforce tokens-per-minute (TPM) limits. Build a
token bucket that holds at most `capacity` tokens and refills continuously
at `tokensPerMinute`. The clock is injected (`now()` returns milliseconds)
so behaviour is testable.
- `tryConsume(n)`: if at least n tokens are available, remove them and
  return true; otherwise return false and remove nothing.
- `waitTimeMs(n)`: milliseconds until n tokens will be available (0 if
  available now, Infinity if n > capacity).
- `available()`: current token count after refilling.
The bucket starts full.

Constraints:
- capacity > 0, tokensPerMinute > 0, n >= 0
- the clock never goes backwards

Example:
  capacity 1000, 600 tokens/min (10 per second)
  tryConsume(900) -> true; tryConsume(200) -> false
  waitTimeMs(200) -> 10000; after 10 s, tryConsume(200) -> true

Approach: Store the token count and last refill time; refill lazily on
every call by elapsed * rate, capped at capacity. No timers or background
work. Every operation is O(1) time and O(1) space.
@param {{ capacity: number, tokensPerMinute: number, now?: () => number }} opts
Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.