Limit the execution rate of a function

Overview

valvelet

Version npm Build Status Coverage Status

This is a small utility to limit the execution rate of a function. It is useful for scenarios such as REST APIs consumption where the amount of requests per unit of time should not exceed a given threshold.

This module is very similar to node-function-rate-limit. The difference is that valvelet works seamlessly with promise-returning functions.

Install

npm install --save valvelet

API

The module exports a single function that takes four arguments.

valvelet(fn, limit, interval[, size])

Returns a function which should be called instead of fn.

Arguments

  • fn - The function to rate limit calls to.
  • limit - The maximum number of allowed calls per interval.
  • interval - The timespan where limit is calculated.
  • size - 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. When the internal queue is at capacity the returned promise is rejected.

Example

const valvelet = require('valvelet');

const get = valvelet(
  function request(i) {
    return Promise.resolve(`${i} - ${new Date().toISOString()}`);
  },
  2,
  1000
);

function log(data) {
  console.log(data);
}

for (let i = 0; i < 10; i++) {
  get(i).then(log);
}

/*
0 - 2016-06-02T20:07:33.843Z
1 - 2016-06-02T20:07:33.844Z
2 - 2016-06-02T20:07:34.846Z
3 - 2016-06-02T20:07:34.846Z
4 - 2016-06-02T20:07:35.846Z
5 - 2016-06-02T20:07:35.846Z
6 - 2016-06-02T20:07:36.848Z
7 - 2016-06-02T20:07:36.848Z
8 - 2016-06-02T20:07:37.851Z
9 - 2016-06-02T20:07:37.851Z
*/

Disclaimers

This module is not a complete solution if you are trying to throttle your requests to a remote API, but have multiple Node.js processes on the same or multiple hosts, since the state is not shared between the services. That case can be addressed by allowing each process to send up to only a fraction of the total limit. Ex: If you have 4 processes, let each process send up to $limit/4.

License

MIT

You might also like...

Wrap a function with bun-livereload to automatically reload any imports inside the function the next time it is called

bun-livereload Wrap a function with bun-livereload to automatically reload any imports inside the function the next time it is called. import liveRelo

Dec 19, 2022

Job scheduler and rate limiter, supports Clustering

bottleneck Bottleneck is a lightweight and zero-dependency Task Scheduler and Rate Limiter for Node.js and the browser. Bottleneck is an easy solution

Jan 3, 2023

Chrome extension to simulate cryptoblades fights, giving you the win rate % against all enemies with just one click

Chrome extension to simulate cryptoblades fights, giving you the win rate % against all enemies with just one click

CryptoBlades fight simulator This is a Chrome extension that will help you to know the exact win rate percentage you have on each cryptoblades fight.

Aug 7, 2022

MERN stack application which serves as an online map journal where users can mark and rate the places they've been to.

MERN stack application which serves as an online map journal where users can mark and rate the places they've been to.

PlaceRate PlaceRate is a MERN stack application which serves as an online map journal where users can mark and rate the places they've been to. You ca

May 17, 2022

MERN stack travel app using mapbox API, Travel and drop pin , share reviews and rate the location

MERN stack travel app using mapbox API, Travel and drop pin , share reviews and rate the location

MERN-Travel-Map Travel Map Pin A single page application built with MERN Stack from scratch (MongoDB + Mongoose, Express, React & NodeJs) Table of Con

Dec 29, 2022

Mi Band/Amazfit heart rate monitor with OSC integration for VRChat

Mi Band/Amazfit heart rate monitor with OSC integration for VRChat

Mi Band/Amazfit OSC heart rate monitor for VRChat By Vard Based on Jaapp-'s miband-5-heart-rate-monitor and gzalo's miband-6-heart-rate-monitor Thanks

Jan 1, 2023

NEW⚡ PancakeSwap Prediction Bot using AI live recommendations. ~70% Win rate 🔮

NEW⚡ PancakeSwap Prediction Bot using AI live recommendations. ~70% Win rate 🔮

🔮 PancakeSwap Prediction SmartBot PancakeSwap Prediction Bot using live TradingView AI recomendations. ~70% Win rate. ⭐ Please consider giving a star

Jun 14, 2022

NEW⚡ PancakeSwap Prediction Bot using AI live recomendations. ~70% Win rate 🔮

NEW⚡ PancakeSwap Prediction Bot using AI live recomendations. ~70% Win rate 🔮

🔮 PancakeSwap Prediction SmartBot PancakeSwap Prediction Bot using live TradingView AI recomendations. ~70% Win rate. ⭐ Please consider giving a star

Dec 15, 2022

Simple rate-limiter NPM Module used for blocking IPs that exceeds certain number of requests per second in a specific time frame.

API Rate Limiter Zero-Dependencies Simple rate-limiter NPM Module used for blocking IPs that exceeds certain number of requests per second in a specif

Oct 7, 2022

Gulp.js command execution for humans

Gulp.js command execution for humans

Gulp.js command execution for humans. As opposed to similar plugins or to child_process.exec(), this uses Execa which provides: Better Windows support

Dec 14, 2022

Abstracts execution of tasks in parallel using Node.js cluster.

cluster-map Abstracts execution of tasks in parallel using Node.js cluster. It is a high level abstraction around a common pattern used to delegate a

Jul 3, 2022

A web client port-scanner written in GO, that supports the WASM/WASI interface for Browser WebAssembly runtime execution.

A web client port-scanner written in GO, that supports the WASM/WASI interface for Browser WebAssembly runtime execution.

WebAssembly Port Scanner Written in Go with target WASM/WASI. The WASM main function scans all the open ports in the specified range (see main.go), vi

Dec 27, 2022

Remote Code Execution V1 For iOS 15 sent through airdrop after the device was connected to a trusted host

Remote Code Execution V1 For iOS 15 sent through airdrop after the device was connected to a trusted host

iOS 15.0.1 RCE V1 Author: Jonathan Scott @jonathandata1 Date: October 9th, 2021 Release Version 1.0 Description When an iOS device has been connected

Dec 26, 2022

ROP userland execution for PS5 (4.03)

ROP userland execution for PS5 (4.03)

# Exploring the Playstation 5 Security - Userland Introduction The PlayStation 5 was released on November 12th 2020. While it's similar to the PS4 in

Dec 2, 2022

"Lerna & Distributed Task Execution" Example

Lerna Distributed Task Execution (DTE) Example/Benchmark On how to make your CI 23 times faster with a small config change New versions of Lerna can u

Nov 27, 2022

jQuery Plugin For Delayed Event Execution

bindWithDelay jQuery plugin Author: Brian Grinstead MIT license: http://www.opensource.org/licenses/mit-license.php http://github.com/bgrins/bindWith

Dec 31, 2022

Open, extensible, small and simple behaviour-graph execution engine

Behave-Graph Behave-Graph is a standalone library that implements the concept of "behavior graphs" as a portable TypeScript library with no external r

Dec 29, 2022

A React utility belt for function components and higher-order components.

A Note from the Author (acdlite, Oct 25 2018): Hi! I created Recompose about three years ago. About a year after that, I joined the React team. Today,

Jan 4, 2023
Owner
Luigi Pinca
Luigi Pinca
A rate-limiter using Durable Objects on CF Workers that actually doesn't rate limit anything.

Rate Limiter - built for Cloudflare Workers, using Durable Objects Features Supports fixed or sliding window algorithms Scoped rate-limiting Caching C

Ian 11 Dec 15, 2022
⚡️The Fullstack React Framework — built on Next.js

The Fullstack React Framework "Zero-API" Data Layer — Built on Next.js — Inspired by Ruby on Rails Read the Documentation “Zero-API” data layer lets y

⚡️Blitz 12.5k Jan 4, 2023
⚖️ Limit an async function's concurrency with ease!

limit-concur Limit an async function's concurrency with ease! Install $ npm i limit-concur Usage import got from 'got' import limitConcur from 'limit-

Tomer Aberbach 19 Apr 8, 2022
A simple in-memory time-based cache for both objects and function execution.

What is this? A simple in-memory time-based cache for both objects and function execution. How do I install it? You can install it by using the follow

cadienvan 7 Dec 15, 2022
A simple in-memory key-value cache for function execution, allowing both sync and async operations using the same methods

A simple in-memory key-value cache for function execution, allowing both sync and async operations using the same methods. It provides an invalidation mechanism based both on exact string and regex.

cadienvan 10 Dec 15, 2022
Read Medium content without limit!

Medium Unlocker Read Medium content without limit! Aka replacer for Medium Unlimited. Get more information Please visit Wiki page Features Unlock grap

und3fined 303 Dec 24, 2022
Ajax library with XHR2, promises and request limit

qwest 4.5.0 ⚠ I finally decided to archive this repository. ⚠ At first, I developed Qwest because at the time other libraries were lacking of a proper

Aurélien Delogu 718 Sep 14, 2022
Unlocks all brainly answers and bypasses one answer per day limit. Gives infinite free answers & unlocks all textbooks 🔐 ∞

Brainly-LockPick ?? Unlocks all brainly answers and bypasses one answer per day limit. Gives infinite free answers & unlocks textbooks ?? ∞ Note: refr

null 7 Dec 9, 2022
A quickstart AWS Lambda function code generator. Downloads a template function code file, test harness file, sample SAM deffiniation and appropriate file structure.

Welcome to function-stencil ?? A quickstart AWS Lambda function code generator. Downloads a template function code file, test harness file, sample SAM

Ben Smith 21 Jun 20, 2022
Tries to execute sync/async function, returns a specified default value if the function throws

good-try Tries to execute sync/async function, returns a specified default value if the function throws. Why Why not nice-try with it's 70+ million do

Antonio Stoilkov 14 Dec 8, 2022