p-limit vs express-rate-limit vs limiter vs bottleneck vs rate-limiter-flexible vs ratelimiter
Node.js 限流庫
p-limitexpress-rate-limitlimiterbottleneckrate-limiter-flexibleratelimiter類似套件:

Node.js 限流庫

限流庫是用於控制應用程式中請求或操作的頻率,以防止過載或濫用。這些庫提供了不同的策略和功能來限制請求的數量,確保系統的穩定性和性能。透過使用這些庫,開發者可以有效地管理資源,避免因為過多的請求而導致的性能問題或服務中斷。

npm下載趨勢

3 年

GitHub Stars 排名

統計詳情

套件
下載數
Stars
大小
Issues
發布時間
許可
p-limit461,131,1332,94316.1 kB02 個月前MIT
express-rate-limit99,847,9223,318158 kB911 小時前MIT
limiter23,887,4361,571103 kB52 個月前MIT
bottleneck15,603,3862,009-897 年前MIT
rate-limiter-flexible4,759,0733,605234 kB124 天前ISC
ratelimiter46,514720-117 年前MIT

功能比較: p-limit vs express-rate-limit vs limiter vs bottleneck vs rate-limiter-flexible vs ratelimiter

限流策略

  • p-limit:

    p-limit 專注於限制同時執行的 Promise 數量,適合需要控制並發請求的情境。

  • express-rate-limit:

    express-rate-limit 主要基於 IP 地址進行限流,支持簡單的速率限制設置,適合用於保護 API。

  • limiter:

    Limiter 提供基本的請求計數和限制功能,適合不需要複雜配置的場景。

  • bottleneck:

    Bottleneck 提供多種限流策略,包括基於時間的限制、最大佇列長度和優先級控制,允許開發者根據需求靈活配置。

  • rate-limiter-flexible:

    rate-limiter-flexible 支持多種限流策略,包括基於用戶的限制和動態重置,適合複雜的應用需求。

  • ratelimiter:

    ratelimiter 提供簡單的請求限制功能,適合快速集成和基本使用。

使用場景

  • p-limit:

    適合需要控制並發請求的場景,如批量處理請求或 API 調用。

  • express-rate-limit:

    非常適合用於保護 Express 應用的 API,防止濫用和過載。

  • limiter:

    適合小型應用或簡單的限流需求,快速實現基本的請求限制。

  • bottleneck:

    適合需要高效處理大量請求的應用,如網絡爬蟲或 API 請求。

  • rate-limiter-flexible:

    適合需要高級限流功能的應用,如多用戶系統或需要動態調整的場景。

  • ratelimiter:

    適合簡單的應用場景,快速實現限流功能。

擴展性

  • p-limit:

    p-limit 的擴展性主要體現在控制 Promise 的並發數量,適合需要簡單擴展的場景。

  • express-rate-limit:

    雖然功能簡單,但可以與其他中間件結合使用,擴展其功能。

  • limiter:

    Limiter 的擴展性有限,主要適合基本的請求限制需求。

  • bottleneck:

    Bottleneck 的設計非常靈活,支持自定義限流邏輯和擴展,適合複雜的應用需求。

  • rate-limiter-flexible:

    提供豐富的 API 和配置選項,支持多種存儲後端,擴展性強。

  • ratelimiter:

    ratelimiter 的擴展性較低,主要針對簡單的使用場景。

學習曲線

  • p-limit:

    p-limit 的使用簡單,學習曲線平緩,適合快速集成。

  • express-rate-limit:

    學習曲線平緩,易於上手,特別是對於已經熟悉 Express 的開發者。

  • limiter:

    Limiter 的學習曲線非常低,適合快速上手。

  • bottleneck:

    Bottleneck 具有一定的學習曲線,因為其功能豐富,需要理解不同的配置選項。

  • rate-limiter-flexible:

    由於功能豐富,學習曲線相對較陡,但提供了詳細的文檔。

  • ratelimiter:

    ratelimiter 的學習曲線非常低,易於理解和使用。

如何選擇: p-limit vs express-rate-limit vs limiter vs bottleneck vs rate-limiter-flexible vs ratelimiter

  • p-limit:

    選擇 p-limit 如果你需要限制並發的 Promise 數量,這對於控制同時執行的異步操作數量非常有用,特別是在處理大量請求時。

  • express-rate-limit:

    選擇 express-rate-limit 如果你正在使用 Express 框架並需要簡單的基於 IP 的請求限制,這個庫非常適合用於保護 API 免受濫用。

  • limiter:

    選擇 Limiter 如果你需要一個簡單的限流工具,專注於基本的請求限制功能,並且不需要複雜的配置或功能。

  • bottleneck:

    選擇 Bottleneck 如果你需要一個靈活且可擴展的限流解決方案,支持多種限流策略(如基於時間的限制和最大佇列長度),並且需要在多個異步操作之間進行精細控制。

  • rate-limiter-flexible:

    選擇 rate-limiter-flexible 如果你需要一個功能強大的限流庫,支持多種存儲後端(如 Redis 和 MongoDB),並且需要更高級的功能,如基於用戶的限流和自動重置。

  • ratelimiter:

    選擇 ratelimiter 如果你需要一個輕量級的限流解決方案,專注於簡單的使用案例,並且希望快速集成到你的應用中。

p-limit 的 README

p-limit

Run multiple promise-returning & async functions with limited concurrency

Works in Node.js and browsers.

Install

npm install p-limit

Usage

import pLimit from 'p-limit';

const limit = pLimit(1);

const input = [
	limit(() => fetchSomething('foo')),
	limit(() => fetchSomething('bar')),
	limit(() => doSomething())
];

// Only one promise is run at once
const result = await Promise.all(input);
console.log(result);

API

pLimit(concurrency) default export

Returns a limit function.

concurrency

Type: number | object
Minimum: 1

Concurrency limit.

You can pass a number or an options object with a concurrency property.

rejectOnClear

Type: boolean
Default: false

Reject pending promises with an AbortError when clearQueue() is called. This is recommended if you await the returned promises, for example with Promise.all, so pending tasks do not remain unresolved after clearQueue().

import pLimit from 'p-limit';

const limit = pLimit({concurrency: 1});

limit(fn, ...args)

Returns the promise returned by calling fn(...args).

fn

Type: Function

Promise-returning/async function.

args

Any arguments to pass through to fn.

Support for passing arguments on to the fn is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a lot of functions.

Warning: Avoid calling the same limit function inside a function that is already limited by it. This can create a deadlock where inner tasks never run. Use a separate limiter for inner tasks.

limit.map(iterable, mapperFunction)

Process an iterable of inputs with limited concurrency.

The mapper function receives the item value and its index.

Returns a promise equivalent to Promise.all(Array.from(iterable, (item, index) => limit(mapperFunction, item, index))).

If the iterable throws during iteration, the returned promise rejects with that error. Mapper functions that were already scheduled still run, and their results are discarded.

This is a convenience function for processing inputs that arrive in batches. For more complex use cases, see p-map.

limit.activeCount

The number of promises that are currently running.

limit.pendingCount

The number of promises that are waiting to run (i.e. their internal fn was not called yet).

limit.clearQueue()

Discard pending promises that are waiting to run.

This might be useful if you want to tear down the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app.

Note: This does not cancel promises that are already running.

When rejectOnClear is enabled, pending promises are rejected with an AbortError. This is recommended if you await the returned promises, for example with Promise.all, so pending tasks do not remain unresolved after clearQueue().

limit.concurrency

Get or set the concurrency limit.

limitFunction(fn, options) named export

Returns a function with limited concurrency.

The returned function manages its own concurrent executions, allowing you to call it multiple times without exceeding the specified concurrency limit.

Ideal for scenarios where you need to control the number of simultaneous executions of a single function, rather than managing concurrency across multiple functions.

import {limitFunction} from 'p-limit';

const limitedFunction = limitFunction(async () => {
	return doSomething();
}, {concurrency: 1});

const input = Array.from({length: 10}, limitedFunction);

// Only one promise is run at once.
await Promise.all(input);

fn

Type: Function

Promise-returning/async function.

options

Type: object

concurrency

Type: number
Minimum: 1

Concurrency limit.

rejectOnClear

Type: boolean
Default: false

Reject pending promises with an AbortError when clearQueue() is called. This is recommended if you await the returned promises, for example with Promise.all, so pending tasks do not remain unresolved after clearQueue().

limitedFunction.clearQueue()

Discard pending calls that have not started yet.

When rejectOnClear is enabled, pending promises are rejected with an AbortError. Otherwise, their promises remain unresolved.

This does not cancel calls that are already running.

Recipes

See recipes.md for common use cases and patterns.

FAQ

How is this different from the p-queue package?

This package is only about limiting the number of concurrent executions, while p-queue is a fully featured queue implementation with lots of different options, introspection, and ability to pause the queue.

Related

  • p-throttle - Throttle promise-returning & async functions
  • p-debounce - Debounce promise-returning & async functions
  • p-map - Run promise-returning & async functions concurrently with different inputs
  • p-all - Run promise-returning & async functions concurrently with optional limited concurrency
  • More…