rate-limiter-flexible vs async vs bottleneck vs p-limit vs promise-limit
Node.jsの非同期処理ライブラリ
rate-limiter-flexibleasyncbottleneckp-limitpromise-limit類似パッケージ:

Node.jsの非同期処理ライブラリ

非同期処理ライブラリは、Node.jsにおける非同期操作の管理を簡素化し、効率的なタスク実行を可能にします。これらのライブラリは、コールバックやプロミスを使用して非同期処理を行う際の複雑さを軽減し、タスクの実行順序や制限を設定するための便利な機能を提供します。これにより、開発者はより簡潔で可読性の高いコードを書くことができ、アプリケーションのパフォーマンスを向上させることができます。

npmのダウンロードトレンド

3 年

GitHub Starsランキング

統計詳細

パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
rate-limiter-flexible2,043,6033,530221 kB157日前ISC
async028,173808 kB242年前MIT
bottleneck01,989-907年前MIT
p-limit02,84514.9 kB13ヶ月前MIT
promise-limit0143-108年前ISC

機能比較: rate-limiter-flexible vs async vs bottleneck vs p-limit vs promise-limit

タスク管理

  • rate-limiter-flexible:

    rate-limiter-flexibleは、APIリクエストやユーザーアクションのレート制限を柔軟に設定できる機能を提供します。

  • async:

    asyncは、コールバックベースの非同期処理を簡素化するための多くのユーティリティ関数を提供します。これにより、タスクの直列実行や並列実行を簡単に制御できます。

  • bottleneck:

    bottleneckは、タスクの実行速度を制御するための強力なツールで、特定の時間内に実行できるタスクの数を制限することができます。

  • p-limit:

    p-limitは、同時に実行するタスクの数を制限するシンプルな方法を提供します。これにより、システムリソースの過負荷を防ぎます。

  • promise-limit:

    promise-limitは、プロミスを返す関数の実行を制御し、同時実行数を制限するための便利なライブラリです。

使用シナリオ

  • rate-limiter-flexible:

    ユーザーごとのリクエスト制限や、特定の時間内に許可されるリクエスト数を設定したい場合に適しています。

  • async:

    非同期処理のフローを管理する必要がある場合や、複雑なコールバック地獄を避けたい場合に適しています。

  • bottleneck:

    APIの呼び出しやデータベースへのクエリの頻度を制限する必要がある場合に特に有用です。

  • p-limit:

    軽量なタスク制限が必要な場合や、シンプルなプロミスベースの処理を行う場合に最適です。

  • promise-limit:

    プロミスを使用した非同期処理で、同時に実行するタスクの数を制限したい場合に役立ちます。

設計原則

  • rate-limiter-flexible:

    rate-limiter-flexibleは、柔軟なレート制限を実現するために、さまざまなストレージバックエンドをサポートしています。

  • async:

    asyncは、コールバックのネストを避けるために、フロー制御を簡素化することを目的としています。

  • bottleneck:

    bottleneckは、タスクの実行を制御するための柔軟な設計を持ち、特定の条件に基づいてタスクをスロットリングします。

  • p-limit:

    p-limitは、シンプルで直感的なAPIを提供し、非同期処理の制御を容易にします。

  • promise-limit:

    promise-limitは、プロミスの特性を活かしつつ、同時実行数を制限することに特化しています。

拡張性

  • rate-limiter-flexible:

    rate-limiter-flexibleは、さまざまなストレージオプションをサポートしており、ニーズに応じて拡張可能です。

  • async:

    asyncは、さまざまなユーティリティ関数を提供しており、独自のタスク管理ロジックを追加することができます。

  • bottleneck:

    bottleneckは、カスタムのスロットリングロジックを実装するための拡張性を持っています。

  • p-limit:

    p-limitは、シンプルなAPIを持ち、他のライブラリと組み合わせて使用することが容易です。

  • promise-limit:

    promise-limitは、プロミスの特性を活かしつつ、他の非同期処理ライブラリと組み合わせて使用できます。

学習曲線

  • rate-limiter-flexible:

    rate-limiter-flexibleは、柔軟な設定が可能ですが、初めて使用する際には少し学習が必要です。

  • async:

    asyncは、多くのユーティリティ関数を提供しているため、初めて使用する際には少し学習が必要ですが、使いこなすと非常に強力です。

  • bottleneck:

    bottleneckは、タスクの制御が直感的であり、比較的簡単に学ぶことができます。

  • p-limit:

    p-limitは、シンプルなAPIを持っているため、学習曲線が緩やかで、すぐに使い始めることができます。

  • promise-limit:

    promise-limitは、プロミスに基づいているため、プロミスの基本を理解していればすぐに使えます。

選び方: rate-limiter-flexible vs async vs bottleneck vs p-limit vs promise-limit

  • rate-limiter-flexible:

    リクエストのレート制限を柔軟に設定したい場合に選択します。特に、APIの使用制限やユーザーごとのリクエスト制限を行う際に役立ちます。

  • async:

    非同期処理のフローを簡単に管理したい場合や、コールバックスタイルでの開発を好む場合に選択します。多くのユーティリティ関数が用意されており、タスクの並列実行や直列実行を簡単に制御できます。

  • bottleneck:

    タスクの実行速度や頻度を制御したい場合に選択します。特にAPIリクエストやデータベースクエリの制限を設ける必要がある場合に効果的です。

  • p-limit:

    同時に実行するタスクの数を制限したい場合に選択します。シンプルで軽量な実装が特徴で、プロミスを使用した非同期処理に適しています。

  • promise-limit:

    プロミスを使用して非同期処理を行う際に、同時実行数を制限したい場合に選択します。特に、プロミスを返す関数の実行を制御するのに便利です。

rate-limiter-flexible のREADME

npm version npm node version deno version

Logo

node-rate-limiter-flexible

rate-limiter-flexible counts and limits the number of events and protects from DoS and brute force attacks at any scale.

It works with Valkey, Redis, Prisma, DynamoDB, process Memory, Cluster or PM2, Memcached, MongoDB, MySQL, SQLite, and PostgreSQL.

Memory limiter also works in the browser.

AI tools See llms.txt and CONTEXT.md for LLM-friendly documentation.

Atomic increments. All operations in memory or distributed environment use atomic increments against race conditions.

Fast. Average request takes 0.7ms in Cluster and 2.5ms in Distributed application. See benchmarks.

Flexible. Combine limiters, block key for some duration, delay actions, manage failover with insurance options, configure smart key blocking in memory and many others.

Ready for growth. It provides a unified API for all limiters. Whenever your application grows, it is ready. Prepare your limiters in minutes.

Friendly. No matter which node package you prefer: valkey-glide or iovalkey, redis or ioredis, sequelize/typeorm or knex, memcached, native driver or mongoose. It works with all of them.

In-memory blocks. Avoid extra requests to store with inMemoryBlockOnConsumed.

Deno compatible See this example

The Flexible Fixed Window algorithm starts counting from the moment a request is received, diversifying rate limit reset times across clients. Read more here

Installation

npm i --save rate-limiter-flexible

yarn add rate-limiter-flexible

Import

import { RateLimiterMemory } from "rate-limiter-flexible";

// or import directly
import RateLimiterMemory from "rate-limiter-flexible/lib/RateLimiterMemory.js";

Basic Example

Points can be consumed by IP address, user ID, authorisation token, API route or any other string.

const opts = {
  points: 6, // 6 points
  duration: 1, // Per second
};

const rateLimiter = new RateLimiterMemory(opts);

rateLimiter.consume(remoteAddress, 2) // consume 2 points
    .then((rateLimiterRes) => {
      // 2 points consumed
    })
    .catch((rateLimiterRes) => {
      // Not enough points to consume
    });

RateLimiterRes object

The Promise's resolve and reject callbacks both return an instance of the RateLimiterRes class if there is no error. Object attributes:

RateLimiterRes = {
    msBeforeNext: 250, // Number of milliseconds before next action can be done
    remainingPoints: 0, // Number of remaining points in current duration 
    consumedPoints: 5, // Number of consumed points in current duration 
    isFirstInDuration: false, // action is first in current duration 
}

You may want to set HTTP headers for the response:

const headers = {
  "Retry-After": rateLimiterRes.msBeforeNext / 1000,
  "X-RateLimit-Limit": opts.points,
  "X-RateLimit-Remaining": rateLimiterRes.remainingPoints,
  "X-RateLimit-Reset": Math.ceil((Date.now() + rateLimiterRes.msBeforeNext) / 1000)
}

Advantages:

Full documentation is on Wiki

Middlewares, plugins and other packages

Copy/paste examples on Wiki:

Migration from other packages

  • express-brute Bonus: race conditions fixed, prod deps removed
  • limiter Bonus: multi-server support, respects queue order, native promises

Docs and Examples

Changelog

See releases for detailed changelog.

Basic Options

  • points

    Required

    Maximum number of points that can be consumed over duration

  • duration

    Required

    Number of seconds before consumed points are reset.

    Points are never reset if duration is set to 0.

  • storeClient

    Required for store limiters

    Must be pool or connection created with store client packages, e.g. @valkey/valkey-glide, ioredis, iovalkey, redis, memcached, mongodb, pg, mysql2, mysql, etc.

Other options on Wiki:

See full list of options.

API

Read detailed description on Wiki.

Contributions

Appreciated, feel free!

Make sure you've launched npm run eslint before creating PR, all errors have to be fixed.

You can try to run npm run eslint-fix to fix some issues.

Any new limiter with storage must be extended from RateLimiterStoreAbstract. It has to implement 4 methods:

  • _getRateLimiterRes parses raw data from store to RateLimiterRes object.

  • _upsert may be atomic or non-atomic upsert (increment). It inserts or updates the value by key and returns raw data. If it doesn't make an atomic upsert (increment), the class should be suffixed with NonAtomic, e.g. RateLimiterRedisNonAtomic.

    It must support forceExpire mode to overwrite key expiration time.

  • _get returns raw data by key or null if there is no key.

  • _delete deletes all key-related data and returns true on deleted, false if key is not found.

All other methods depend on the store. See RateLimiterRedis or RateLimiterPostgres for examples.

For wrapper classes that don't need full RateLimiterAbstract functionality, extend RateLimiterCompatibleAbstract instead. It requires implementing consume, penalty, reward, get, set, block, delete methods and blockDuration/execEvenly getters/setters. If the wrapper doesn't use blockDuration or execEvenly, empty no-op implementations can be provided. See RLWrapperBlackAndWhite for an example.

Note: all changes should be covered by tests.