Bottleneck Rate Limiter With Burst and Reservoir

Smooth bursty traffic with Bottleneck using a token reservoir, rolling rate limit, and prioritized scheduled jobs that respect a fixed quota.

JavascriptResilience

Code

javascriptsnippet
20 lines
import Bottleneck from 'bottleneck';

const limiter = new Bottleneck({
  reservoir: 20,
  reservoirRefreshAmount: 20,
  reservoirRefreshInterval: 60_000,
  maxConcurrent: 5,
  minTime: 200,
});

limiter.on('error', (err) => console.error('limiter error:', err.message));

async function callApi(path, priority = 5) {
  return limiter.schedule({ priority }, () =>
    fetch(`https://api.example.com${path}`).then((r) => r.json()),
  );
}

const high = await callApi('/billing/summary', 1);
const normal = await callApi('/catalog/list', 5);

How it works

Bottleneck Rate Limiter With Burst and Reservoir keeps everything in the function callApi.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

Watch out for

  • Requires bottleneck as a package; the snippet will not run without it.
  • fetch exist only in browsers — a Node runtime has no shims for them out of the box.

Putting it to use

The main signature reads async function callApi(path, priority = 5)

The demo output is labeled (limiter error:), so every printed line maps back to its originating operation.

Core lines

return limiter.schedule({ priority }, () =>
fetch(`https://api.example.com${path}`).then((r) => r.json()),
);
const high = await callApi('/billing/summary', 1);
const normal = await callApi('/catalog/list', 5);

Interactive Tools for This Topic

FAQ

Which packages must be installed first?
Yes. The imports resolve to `bottleneck`, which the package manager must provide.