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;}Report a problem with this exampleOpens a pre-filled issue on GitHub.