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.

JavascriptResilience

Code

javascriptsnippet
1 line
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

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.