express-slow-down vs express-brute vs express-rate-limit vs rate-limiter-flexible
Express アプリケーションにおけるレート制限とトラフィック制御の戦略
express-slow-downexpress-bruteexpress-rate-limitrate-limiter-flexible類似パッケージ:

Express アプリケーションにおけるレート制限とトラフィック制御の戦略

これらのライブラリは、Node.js の Express アプリケーションに対して、API エンドポイントへのリクエスト頻度を制限し、サーバーへの過負荷や悪意のある攻撃(ブルートフォースなど)から保護するためのミドルウェアです。express-rate-limit は標準的なレート制限を提供し、express-slow-down はリクエストをブロックせずに遅延させます。rate-limiter-flexible はより柔軟な設定と複数のストレージバックエンドをサポートし、express-brute は古いブルートフォース保護用のパッケージですが、現在はメンテナンスが停止されています。

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

3 年

GitHub Starsランキング

統計詳細

パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
express-slow-down166,29830238.7 kB22時間前MIT
express-brute0568-2110年前BSD
express-rate-limit03,289153 kB822日前MIT
rate-limiter-flexible03,581230 kB93ヶ月前ISC

Express ミドルウェアによるレート制限とトラフィック制御の戦略

Node.js の Express アプリケーションを本番環境で運用する際、API の乱用やサーバーの過負荷を防ぐためのレート制限は不可欠です。express-brute、express-rate-limit、express-slow-down、rate-limiter-flexible は、それぞれ異なるアプローチでこの課題を解決しますが、その保守性、機能、および適用シナリオには大きな違いがあります。ここでは、実務的な観点からこれらを比較します。

🛠️ 保守性とステータス:現役かレガシーか

パッケージのメンテナンス状況は、セキュリティと長期運用において最も重要な要素です。

express-brute は、かつてブルートフォース攻撃対策として人気でしたが、現在はメンテナンスが停止しています。

  • 最終更新から長期間が経過しており、新しい Node.js バージョンとの互換性に問題が生じる可能性があります。
  • 新しいプロジェクトでは使用を避けるべきです。
// express-brute: 非推奨のパッケージ
// 新規プロジェクトでの使用は推奨されません
const Brute = require('express-brute');
const store = new Brute.MemoryStore();
const protect = new Brute(store);

// 古いスタイルのミドルウェア適用
app.post('/login', protect.handle, (req, res) => { /*...*/ });

express-rate-limit は、現在最も広く採用されている標準的なソリューションです。

  • 活発にメンテナンスされており、Express コミュニティでの信頼性が高いです。
  • 定期的なアップデートにより、セキュリティパッチや機能改善が提供されます。
// express-rate-limit: actively maintained
import rateLimit from 'express-rate-limit';

const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 分
  max: 100 // 各 IP につき 100 リクエスト
});

app.use('/api/', limiter);

express-slow-down は、express-rate-limit と同じエコシステムにあり、安定して維持されています。

  • レート制限そのものではなく、速度制限に特化しています。
  • 単独ではなく、レート制限ミドルウェアと組み合わせて使われることが一般的です。
// express-slow-down: 速度制限
import slowDown from 'express-slow-down';

const speedLimiter = slowDown({
  windowMs: 15 * 60 * 1000,
  delayAfter: 100,
  delayMs: (hits) => hits * 100 // リクエスト数に応じて遅延を増加
});

app.use('/api/', speedLimiter);

rate-limiter-flexible は、現代的なアーキテクチャ向けに設計された高機能なライブラリです。

  • 活発に開発が続いており、Express 以外のフレームワーク(Koa、Fastify など)もサポートします。
  • 複雑な要件を持つシステムでの採用が増えています。
// rate-limiter-flexible: 高機能・多用途
import { RateLimiterMemory } from 'rate-limiter-flexible';
import { rateLimiterExpress } from 'rate-limiter-flexible';

const rateLimiter = new RateLimiterMemory({
  points: 10,
  duration: 1
});

app.use('/api/', rateLimiterExpress.middleware({ rateLimiter }));

⚙️ 設定と柔軟性:シンプルさ vs 制御力

要件に応じて、設定の簡易さと制御の細かさのどちらを優先するかで選択が分かれます。

express-rate-limit は、設定が非常に直感的です。

  • windowMs(時間枠)と max(最大リクエスト数)の 2 つを指定するだけで動作します。
  • 標準的なユースケースでは、これ以上の設定は不要なことが多いです。
// express-rate-limit: シンプルな設定
const limiter = rateLimit({
  windowMs: 60 * 1000,
  max: 10,
  message: 'リクエストが多すぎます'
});

express-slow-down も同様にシンプルですが、遅延の計算ロジックをカスタマイズできます。

  • delayMs に関数を渡すことで、負荷に応じた動的な遅延を設定可能です。
  • ユーザーに「完全に拒否」される前に警告を与える効果があります。
// express-slow-down: 動的な遅延設定
const speedLimiter = slowDown({
  delayAfter: 50,
  delayMs: (hits) => Math.min(hits * 500, 60000) // 最大 60 秒まで遅延
});

rate-limiter-flexible は、ポイントベースのシステムを採用しており、きめ細かい制御が可能です。

  • 異なるアクションに異なるコスト(ポイント)を割り当てることができます(例:ログインは 5 ポイント、閲覧は 1 ポイント)。
  • 設定はやや複雑ですが、その分表現力が豊かです。
// rate-limiter-flexible: ポイントベースの制御
const loginLimiter = new RateLimiterMemory({
  points: 5, // 5 ポイント
  duration: 60 // 60 秒以内
});

// リクエスト時に消費ポイントを設定可能
app.post('/login', async (req, res) => {
  try {
    await loginLimiter.consume(req.ip, { points: 5 });
    res.send('Login success');
  } catch (rejRes) {
    res.status(429).send('Too Many Requests');
  }
});

express-brute は、当時の基準では柔軟でしたが、現在の基準では設定項目が限定的です。

  • 失敗回数に基づくリトライロジックは備わっていますが、現代的なカスタマイズ性には欠けます。
  • コード例は前述の通り、レガシーな構造を持っています。
// express-brute: 固定されたロジック
// 現代的なカスタマイズが難しい
const protect = new Brute(store, {
  failCallback: (req, res, next, nextValidRequestDate) => {
    res.status(429).send('Too many requests');
  }
});

🗄️ ストレージバックエンド:メモリ vs 分散環境

シングルサーバーか、クラスター・分散環境かで適切なストレージ戦略が異なります。

express-rate-limit はデフォルトでインメモリストレージを使用します。

  • 設定なしで動作しますが、Node.js プロセスが再起動するとカウンターがリセットされます。
  • 複数のサーバーをロードバランサーで運用している場合、IP ごとの集計が正しく機能しない可能性があります。
// express-rate-limit: デフォルトはメモリ
// クラスター環境では Redis 等のストアを設定する必要がある
const limiter = rateLimit({
  store: new RedisStore({ client: redisClient }) // 追加設定が必要
});

express-slow-down も同様に、デフォルトはインメモリです。

  • 分散環境で使用する場合は、express-rate-limit と同じく外部ストアのミドルウェアを併用する必要があります。
  • 単体での分散対応機能は限られています。
// express-slow-down: メモリベースが基本
// 分散環境での同期は別途工夫が必要
const speedLimiter = slowDown({
  // 外部ストアを直接指定するオプションは限定的
  skip: (req) => !req.ip // 簡易的な制御のみ
});

rate-limiter-flexible は、多様なストレージバックエンドをネイティブにサポートしています。

  • Redis、Memcached、MongoDB、PostgreSQL など、主要なデータベースに対応したアダプターが用意されています。
  • クラスター環境でも一貫したレート制限を適用しやすい設計です。
// rate-limiter-flexible: 多様なストア対応
import { RateLimiterRedis } from 'rate-limiter-flexible';

const rateLimiter = new RateLimiterRedis({
  storeClient: redisClient,
  points: 10,
  duration: 1
});
// これだけで分散環境対応が可能

express-brute は、ストレージをプラグイン形式で選べましたが、対応しているストアが古いです。

  • 現代的な Redis クライアントやクラウドデータベースとの連携には、追加の労力やラッパーが必要になります。
  • 新規導入するメリットはほぼありません。
// express-brute: 古いストアアダプター
// 現代的な Redis クライアントとの親和性は低い
const RedisStore = require('express-brute-redis');
const store = new RedisStore(redisClient);

🚦 応答制御:ブロック vs 遅延

ユーザーにどのようにフィードバックを与えるかも、パッケージ選定の重要なポイントです。

express-rate-limit と express-brute は、制限を超えるとリクエストを拒否(HTTP 429)します。

  • サーバーを保護するには効果的ですが、 legitimate なユーザーの体験を損なう可能性があります。
  • 明確なエラーメッセージを返すことで、クライアント側に制御を委ねます。
// express-rate-limit: 拒否レスポンス
// HTTP 429 Too Many Requests を返す
const limiter = rateLimit({
  handler: (req, res) => {
    res.status(429).json({ error: '制限を超えました' });
  }
});

express-slow-down は、リクエストを拒否せずに処理速度を落とします。

  • サーバーの負荷を下げつつ、ユーザーには「遅い」という形でフィードバックを返します。
  • 完全なアクセス拒否になる前のバッファとして機能します。
// express-slow-down: 遅延レスポンス
// リクエストは通るが、レスポンスが遅くなる
const speedLimiter = slowDown({
  delayAfter: 10,
  delayMs: 500 // 500ms 遅延させる
});

rate-limiter-flexible は、どちらの挙動も実装可能です。

  • consume メソッドの例外処理で 429 を返すことも、待機させてから処理することもできます。
  • アプリケーションのロジックに合わせたきめ細かい制御が可能です。
// rate-limiter-flexible: 柔軟な応答
app.use(async (req, res, next) => {
  try {
    await limiter.consume(req.ip);
    next();
  } catch (error) {
    // 状況に応じて遅延させるか拒否するかを選べる
    const msToWait = error.msBeforeNext;
    res.set('Retry-After', Math.ceil(msToWait / 1000));
    res.status(429).send('Too Many Requests');
  }
});

📊 比較サマリー

特徴express-rate-limitexpress-slow-downrate-limiter-flexibleexpress-brute
保守状況✅ 活発✅ 活発✅ 活発❌ 停止
主な目的リクエスト制限速度制限柔軟な制限ブルートフォース対策
ストレージメモリ (Redis 等も可)メモリ多様 (Redis, DB 等)限定的
設定の容易さ⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
分散対応設定が必要設定が必要ネイティブ対応困難
推奨度高 (標準)中 (併用)高 (複雑系)低 (非推奨)

💡 結論と推奨事項

express-rate-limit は、ほとんどの標準的な Express アプリケーションにおける第一選択肢です。設定が簡単で信頼性が高く、コミュニティサポートも厚いため、迷わずこれを選ぶべきケースが大半です。

express-slow-down は、express-rate-limit と一緒に使うことで、より優しいトラフィック制御を実現します。いきなりエラーを返すのではなく、徐々に遅くすることで、 legitimate なユーザーの誤操作などを許容しやすくなります。

rate-limiter-flexible は、マイクロサービス構成や、Redis などの外部ストアを必須とする大規模システムに適しています。また、Express 以外のフレームワークとの統一を図りたい場合にも有力な候補です。

express-brute は、歴史的な意義こそあれ、現在の開発環境では使用すべきではありません。セキュリティと保守性の観点から、上記の 3 つのいずれかへの移行を強く推奨します。

最終的には、**「シンプルさが必要なら express-rate-limit、複雑な制御が必要なら rate-limiter-flexible」**という基準で選択すると、将来的な技術的負債を避けられます。

選び方: express-slow-down vs express-brute vs express-rate-limit vs rate-limiter-flexible

  • express-slow-down:

    リクエストを完全にブロックするのではなく、過剰なアクセスに対して応答時間を意図的に遅くしたい場合に使用します。ユーザーエクスペリエンスを損なわずにサーバー負荷を下げたい場合や、レート制限発動前の警告として機能させたい場合に有効です。通常は express-rate-limit と併用されます。

  • express-brute:

    このパッケージは長期間メンテナンスされておらず、新しいプロジェクトでの使用は推奨されません。既存のレガシーシステムを維持する場合を除き、代わりに rate-limiter-flexible や express-rate-limit の評価を検討すべきです。セキュリティの観点からも、更新されないライブラリは脆弱性のリスクを伴います。

  • express-rate-limit:

    シンプルな Express アプリケーションで、標準的なレート制限機能をすぐに導入したい場合に最適です。設定が簡単で、メモリストレージデフォルトで動作するため、小規模なサービスやプロトタイプ開発に適しています。複雑な分散環境でない限り、まずこのパッケージを選ぶのが一般的です。

  • rate-limiter-flexible:

    Redis や Memcached などの外部ストレージを使用する必要がある場合や、きめ細かい制御が必要な大規模システムに適しています。Express 以外のフレームワークとも互換性があり、ポイントベースの柔軟な制限設定が可能です。クラスター環境やマイクロサービス構成での利用を想定しているなら、このパッケージが最も堅牢です。

express-slow-down のREADME

Express Slow Down

tests npm version npm downloads

Basic rate-limiting middleware for Express that slows down responses rather than blocking them outright. Use to slow repeated requests to public APIs and/or endpoints such as password reset.

Plays nice with (and built on top of) Express Rate Limit

Stores

The default memory store does not share state with any other processes or servers. It's sufficient for basic abuse prevention, but an external store will provide more consistency.

express-slow-down uses express-rate-limit's stores

Note: when using express-slow-down and express-rate-limit with an external store, you'll need to create two instances of the store and provide different prefixes so that they don't double-count requests.

Installation

From the npm registry:

# Using npm
> npm install express-slow-down
# Using yarn or pnpm
> yarn/pnpm add express-slow-down

From Github Releases:

# Using npm
> npm install https://github.com/express-rate-limit/express-slow-down/releases/download/v{version}/express-slow-down.tgz
# Using yarn or pnpm
> yarn/pnpm add https://github.com/express-rate-limit/express-slow-down/releases/download/v{version}/express-slow-down.tgz

Replace {version} with the version of the package that you want to your, e.g.: 2.0.0.

Usage

Importing

This library is provided in ESM as well as CJS forms, and works with both Javascript and Typescript projects.

This package requires you to use Node 16 or above.

Import it in a CommonJS project (type: commonjs or no type field in package.json) as follows:

const { slowDown } = require('express-slow-down')

Import it in a ESM project (type: module in package.json) as follows:

import { slowDown } from 'express-slow-down'

Examples

To use it in an API-only server where the speed-limiter should be applied to all requests:

import { slowDown } from 'express-slow-down'

const limiter = slowDown({
	windowMs: 15 * 60 * 1000, // 15 minutes
	delayAfter: 5, // Allow 5 requests per 15 minutes.
	delayMs: (hits) => hits * 100, // Add 100 ms of delay to every request after the 5th one.

	/**
	 * So:
	 *
	 * - requests 1-5 are not delayed.
	 * - request 6 is delayed by 600ms
	 * - request 7 is delayed by 700ms
	 * - request 8 is delayed by 800ms
	 *
	 * and so on. After 15 minutes, the delay is reset to 0.
	 */
})

// Apply the delay middleware to all requests.
app.use(limiter)

To use it in a 'regular' web server (e.g. anything that uses express.static()), where the rate-limiter should only apply to certain requests:

import { slowDown } from 'express-slow-down'

const apiLimiter = slowDown({
	windowMs: 15 * 60 * 1000, // 15 minutes
	delayAfter: 1, // Allow only one request to go at full-speed.
	delayMs: (hits) => hits * hits * 1000, // 2nd request has a 4 second delay, 3rd is 9 seconds, 4th is 16, etc.
})

// Apply the delay middleware to API calls only.
app.use('/api', apiLimiter)

To use a custom store:

import { slowDown } from 'express-slow-down'
import { MemcachedStore } from 'rate-limit-memcached'

const speedLimiter = slowDown({
	windowMs: 15 * 60 * 1000, // 15 minutes
	delayAfter: 1, // Allow only one request to go at full-speed.
	delayMs: (hits) => hits * hits * 1000, // Add exponential delay after 1 request.
	store: new MemcachedStore({
		/* ... */
	}), // Use the external store
})

// Apply the rate limiting middleware to all requests.
app.use(speedLimiter)

Note: most stores will require additional configuration, such as custom prefixes, when using multiple instances. The default built-in memory store is an exception to this rule.

Configuration

windowMs

number

Time frame for which requests are checked/remembered.

Note that some stores have to be passed the value manually, while others infer it from the options passed to this middleware.

Defaults to 60000 ms (= 1 minute).

delayAfter

number | function

The max number of requests allowed during windowMs before the middleware starts delaying responses. Can be the limit itself as a number or a (sync/async) function that accepts the Express req and res objects and then returns a number.

Defaults to 1.

An example of using a function:

const isPremium = async (user) => {
	// ...
}

const limiter = slowDown({
	// ...
	delayAfter: async (req, res) => {
		if (await isPremium(req.user)) return 10
		else return 1
	},
})

delayMs

number | function

The delay to apply to each request once the limit is reached. Can be the delay itself (in milliseconds) as a number or a (sync/async) function that accepts a number (number of requests in the current window), the Express req and res objects and then returns a number.

By default, it increases the delay by 1 second for every request over the limit:

const limiter = slowDown({
	// ...
	delayMs: (used) => (used - delayAfter) * 1000,
})

maxDelayMs

number | function

The absolute maximum value for delayMs. After many consecutive attempts, the delay will always be this value. This option should be used especially when your application is running behind a load balancer or reverse proxy that has a request timeout. Can be the number itself (in milliseconds) or a (sync/async) function that accepts the Express req and res objects and then returns a number.

Defaults to 2147483647 (2^31 - 1 ms, which is ~24 days).

Note: Providing a value higher than 2,147,483,647 will throw an error due to Node.js setTimeout limits.

For example, for the following configuration:

const limiter = slowDown({
	// ...
	delayAfter: 1,
	delayMs: (hits) => hits * 1000,
	maxDelayMs: 4000,
})

The first request will have no delay. The second will have a 2 second delay, the 3rd will have a 3 second delay, but the fourth, fifth, sixth, seventh and so on requests will all have a 4 second delay.

Options from express-rate-limit

Because express-rate-limit is used internally, additional options that it supports may be passed in. Some of them are listed below; see express-rate-limit's documentation for the complete list.

Note: The limit (max) option is not supported (use delayAfter instead), nor is the handler option.

Request API

A req.slowDown property is added to all requests with the limit, used, and remaining number of requests and, if the store provides it, a resetTime Date object. It also has the delay property, which is the amount of delay imposed on current request (milliseconds). These may be used in your application code to take additional actions or inform the user of their status.

Note that used includes the current request, so it should always be > 0.

The property name can be configured with the configuration option requestPropertyName.

Issues and Contributing

If you encounter a bug or want to see something added/changed, please go ahead and open an issue! If you need help with something, feel free to start a discussion!

If you wish to contribute to the library, thanks! First, please read the contributing guide. Then you can pick up any issue and fix/implement it!

License

MIT © Nathan Friedly, Vedant K