stopcock
Limit the execution rate of a function using the token bucket algorithm. Useful for scenarios such as REST APIs consumption where the amount of requests per unit of time should not exceed a given threshold.
Install
npm install --save stopcock
API
The module exports a single function that takes two arguments.
stopcock(fn[, options])
Returns a function which should be called instead of fn
.
Arguments
fn
- The function to rate limit calls to.options
- A plain JavaScript object that contains the configuration options.
Options
limit
- The maximum number of allowed calls perinterval
. Defaults to 2.interval
- The timespan wherelimit
is calculated. Defaults to 1000.bucketSize
- The capacity of the bucket. Defaults to 40.queueSize
- The maximum size of the internal queue. Defaults to 2^32 - 1 which is the maximum array size in JavaScript.
Return value
A function that returns a promise which resolves to the value returned by the
original fn
function. The returned function has a size
accessor property
which returns the internal queue size. When the queue is at capacity the promise
is rejected.
Example
const stopcock = ; { return Promise;} { console;} const get = ; for let i = 0; i < 10; i++ ; /*0 - 2017-03-30T16:46:39.938Z1 - 2017-03-30T16:46:39.940Z2 - 2017-03-30T16:46:39.940Z3 - 2017-03-30T16:46:39.940Z4 - 2017-03-30T16:46:39.940Z5 - 2017-03-30T16:46:40.443Z6 - 2017-03-30T16:46:40.943Z7 - 2017-03-30T16:46:41.441Z8 - 2017-03-30T16:46:41.942Z9 - 2017-03-30T16:46:42.439Z*/