rate-limiter-flexible vs bottleneck vs express-rate-limit vs limiter vs p-limit vs ratelimiter
웹 개발에서의 속도 제한 라이브러리
rate-limiter-flexiblebottleneckexpress-rate-limitlimiterp-limitratelimiter유사 패키지:

웹 개발에서의 속도 제한 라이브러리

속도 제한 라이브러리는 웹 애플리케이션에서 API 호출이나 요청의 빈도를 조절하여 서버의 과부하를 방지하고 안정성을 높이는 데 사용됩니다. 이러한 라이브러리는 다양한 방식으로 요청을 관리하고, 특정 시간 내에 허용된 요청 수를 초과하지 않도록 제어합니다. 이를 통해 서비스의 품질을 유지하고, 악의적인 공격으로부터 보호할 수 있습니다.

npm 다운로드 트렌드

3 년

GitHub Stars 순위

통계 세부사항

패키지
다운로드
Stars
크기
Issues
발행일
라이선스
rate-limiter-flexible4,597,3423,599457 kB1014時間前ISC
bottleneck02,010-887年前MIT
express-rate-limit03,315155 kB91日前MIT
limiter01,568103 kB52ヶ月前MIT
p-limit02,93916.1 kB02ヶ月前MIT
ratelimiter0721-117年前MIT

기능 비교: rate-limiter-flexible vs bottleneck vs express-rate-limit vs limiter vs p-limit vs ratelimiter

기본 기능

  • rate-limiter-flexible:

    Rate-limiter-flexible는 다양한 저장소를 지원하고, 복잡한 속도 제한 로직을 구현할 수 있는 유연성을 제공합니다.

  • bottleneck:

    Bottleneck는 비동기 작업의 동시 실행 수를 조절하고, 요청의 지연을 설정할 수 있는 기능을 제공합니다. 이를 통해 API 호출의 빈도를 조절할 수 있습니다.

  • express-rate-limit:

    Express-rate-limit는 특정 시간 내에 허용된 요청 수를 초과하지 않도록 간단하게 설정할 수 있는 기능을 제공합니다. Express.js와의 통합이 용이합니다.

  • limiter:

    Limiter는 기본적인 속도 제한 기능을 제공하며, 간단한 사용 사례에 적합합니다. 설정이 간단하여 빠르게 적용할 수 있습니다.

  • p-limit:

    P-limit는 Promise의 동시 실행 수를 제한하여 비동기 작업을 효율적으로 관리할 수 있는 기능을 제공합니다.

  • ratelimiter:

    Ratelimiter는 간단한 속도 제한 기능을 제공하며, 기본적인 사용 사례에 적합합니다.

유연성

  • rate-limiter-flexible:

    Rate-limiter-flexible는 다양한 저장소와 함께 사용할 수 있어 유연성이 뛰어납니다. 복잡한 요구 사항을 충족할 수 있습니다.

  • bottleneck:

    Bottleneck는 다양한 설정을 통해 복잡한 비동기 작업을 유연하게 관리할 수 있습니다. 요청의 우선순위를 설정할 수 있는 기능도 제공합니다.

  • express-rate-limit:

    Express-rate-limit는 기본적인 속도 제한 기능을 제공하지만, 유연성은 제한적입니다. 주로 간단한 사용 사례에 적합합니다.

  • limiter:

    Limiter는 간단한 사용 사례에 적합하며, 유연성은 제한적입니다. 복잡한 설정이 필요할 경우 다른 라이브러리를 고려해야 합니다.

  • p-limit:

    P-limit는 Promise의 동시 실행 수를 유연하게 조절할 수 있으며, 비동기 작업의 효율성을 높일 수 있습니다.

  • ratelimiter:

    Ratelimiter는 기본적인 속도 제한 기능을 제공하며, 유연성은 제한적입니다.

설정 용이성

  • rate-limiter-flexible:

    Rate-limiter-flexible는 다양한 설정 옵션을 제공하지만, 초기 설정이 다소 복잡할 수 있습니다.

  • bottleneck:

    Bottleneck는 다양한 설정 옵션을 제공하지만, 초기 설정이 복잡할 수 있습니다. 그러나 한 번 설정하면 유용하게 사용할 수 있습니다.

  • express-rate-limit:

    Express-rate-limit는 설정이 매우 간단하여, 빠르게 적용할 수 있습니다. Express.js와의 통합이 용이합니다.

  • limiter:

    Limiter는 사용하기 쉽고, 설정이 간단하여 빠르게 적용할 수 있습니다.

  • p-limit:

    P-limit는 간단한 API를 제공하여 설정이 용이합니다. 비동기 작업을 쉽게 관리할 수 있습니다.

  • ratelimiter:

    Ratelimiter는 기본적인 속도 제한 기능을 제공하며, 설정이 간단합니다.

성능

  • rate-limiter-flexible:

    Rate-limiter-flexible는 다양한 저장소를 지원하여 성능을 최적화할 수 있습니다. 복잡한 요구 사항을 충족할 수 있습니다.

  • bottleneck:

    Bottleneck는 비동기 작업의 동시 실행 수를 조절하여 성능을 최적화할 수 있습니다. 요청의 지연을 설정하여 서버의 부하를 줄일 수 있습니다.

  • express-rate-limit:

    Express-rate-limit는 요청 수를 제한하여 서버의 부하를 줄이고, 성능을 향상시킬 수 있습니다.

  • limiter:

    Limiter는 간단한 속도 제한 기능을 제공하여 성능을 유지할 수 있습니다.

  • p-limit:

    P-limit는 Promise의 동시 실행 수를 제한하여 비동기 작업의 성능을 최적화할 수 있습니다.

  • ratelimiter:

    Ratelimiter는 기본적인 속도 제한 기능을 제공하여 성능을 유지할 수 있습니다.

사용 사례

  • rate-limiter-flexible:

    Rate-limiter-flexible는 복잡한 속도 제한 로직이 필요한 경우에 적합합니다.

  • bottleneck:

    Bottleneck는 API 호출을 최적화하고, 복잡한 비동기 작업을 관리해야 할 때 유용합니다.

  • express-rate-limit:

    Express-rate-limit는 Express.js 애플리케이션에서 간단한 속도 제한을 구현할 때 적합합니다.

  • limiter:

    Limiter는 간단한 속도 제한이 필요한 경우에 적합합니다.

  • p-limit:

    P-limit는 비동기 작업의 동시 실행 수를 제한해야 할 때 유용합니다.

  • ratelimiter:

    Ratelimiter는 기본적인 속도 제한 기능이 필요한 경우에 적합합니다.

선택 방법: rate-limiter-flexible vs bottleneck vs express-rate-limit vs limiter vs p-limit vs ratelimiter

  • rate-limiter-flexible:

    Rate-limiter-flexible는 다양한 저장소를 지원하며, 복잡한 속도 제한 로직을 구현할 수 있습니다. 유연한 설정이 필요할 때 적합합니다.

  • bottleneck:

    Bottleneck는 복잡한 비동기 작업을 관리하고, 동시 실행 수를 조절해야 할 때 유용합니다. 특히, API 호출을 최적화하고자 할 때 적합합니다.

  • express-rate-limit:

    Express-rate-limit는 Express.js 애플리케이션에 통합하여 간단하게 속도 제한을 설정할 수 있습니다. 기본적인 속도 제한 기능이 필요할 때 선택하세요.

  • limiter:

    Limiter는 간단한 속도 제한 기능을 제공하며, 사용하기 쉽고 가벼운 라이브러리를 원할 때 적합합니다.

  • p-limit:

    P-limit는 Promise의 동시 실행 수를 제한하는 데 유용합니다. 비동기 작업을 병렬로 처리하면서도 제어가 필요할 때 선택하세요.

  • ratelimiter:

    Ratelimiter는 간단한 속도 제한 기능을 제공하며, 기본적인 사용 사례에 적합합니다.

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.