Luke Oliff.

TIL: Rate-Limiting API Requests With Bottleneck

·TIL·1 min read·Luke Oliff

APIs have limits. Hit them and you get 429 responses. Bottleneck queues your requests and respects the limits.

const Bottleneck = require('bottleneck')

const limiter = new Bottleneck({
  maxConcurrent: 2,
  minTime: 333
})

const result = await limiter.schedule(() => api.makeRequest())

maxConcurrent limits parallel requests. minTime spaces them out. The limiter wraps any function that returns a Promise.

I wrote this pattern into every Vonage API demo I built. The voice API had rate limits per second. The SMS API had different limits. Bottleneck made each integration respect the right constraints without thinking about it.

Can Bottleneck retry failed requests?

Yes. Pass a retryCount option. Failed requests are automatically re queued up to the limit.

Does it work in the browser?

Yes. The browser version uses the same API. Install bottleneck from npm.