package
Limit the execution rate of a function using the token bucket algorithm
npm install stopcockGitHub-flavored package documentation.
Across all versions.
Download trend unavailable.
Runtime metadata.
Tagged topics.
Estimated unpacked size across 1 packages.
6.9 kB
Includes dependencies.
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.
npm install --save stopcockThe module exports a single function that takes two arguments.
stopcock(fn[, options])Returns a function which should be called instead of fn.
fn - The function to rate limit calls to.options - A plain JavaScript object that contains the configuration options.limit - The maximum number of allowed calls per interval. Defaults to 2.interval - The timespan where limit 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.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.
const stopcock = require('stopcock');
function request(i) {
return Promise.resolve(`${i} - ${new Date().toISOString()}`);
}
function log(data) {
console.log(data);
}
const get = stopcock(request, { bucketSize: 5 });
for (let i = 0; i < 10; i++) {
get(i).then(log);
}