Token Bucket Async Rate Limiter
Implement an async token bucket rate limiter that refills tokens at a fixed rate and awaits when empty to enforce sustained throughput.
Code
export function tokenBucket({capacity=10,refillRate=1}={}){let tokens=capacity,last=Date.now();const queue=[];function refill(){const now=Date.now();tokens=Math.min(capacity,tokens+(now-last)/1000*refillRate);last=now;}function drain(){while(queue.length>0&&tokens>=1){tokens-=1;queue.shift().resolve();}}async function acquire(){refill();if(tokens>=1){tokens-=1;return;}return new Promise(r=>{queue.push({resolve:r});drain();});}acquire.tokens=()=>{refill();return tokens;};return acquire;}How it works
Token Bucket Async Rate Limiter comes down to the functions tokenBucket, refill, drain and acquire.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
What comes back is a new object, not a reference to anything passed in.
Putting it to use
The primary signature is export function tokenBucket({capacity=10,refillRate=1}={})
Import tokenBucket from the file and call it — the rest of the code is implementation detail.
Interactive Tools for This Topic
HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.LLM Token & Cost EstimatorEstimate BPE-approximate LLM token counts across English, CJK text, and source code and compare request and batch costs across pricing tiers.
FAQ
- Does `tokenBucket` modify its input?
- No — a new value is constructed for the result and the arguments are never written to.
- Do I need to install anything before running this?
- No — every API used here ships with the language runtime, so there is nothing to install. The file defines `tokenBucket`, `refill`, `drain` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.