GitRead 中文社区
首页趋势排行榜原创文章严选周刊
更多资源
新手训练营
精选专题热门话题GitHub 文档资源精选实战指南

node-rate-limiter-flexible

Atomic and non-atomic counters and rate limiting tools. Limit resource access at any scale.

  • 语言JavaScript
  • 默认分支master
  • 大小1.5 MB
  • 更新1 天前
  • Issues7
在 GitHub 打开
avataranimir

项目介绍

animir/node-rate-limiter-flexible 是一个托管在 GitHub 上的开源项目,主要使用 JavaScript 编写,采用 ISC License 许可证,目前获得 3.6k 个 Star、199 次 Fork。

仓库全名
animir/node-rate-limiter-flexible

README 摘要

[node-url]: http://nodejs.org/download/ 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…

完整内容见 GitHub 原始 README 或本页 。

常见问题

node-rate-limiter-flexible 用什么语言开发?

主要使用 JavaScript 编写,采用 ISC License 许可证,目前有 3.6k 个 Star。

node-rate-limiter-flexible 可以免费商用吗?

仓库采用 ISC License 许可证,可免费使用与修改,商业使用请遵守许可证条款(例如保留版权声明与许可声明)。

如何获取 node-rate-limiter-flexible 的源码?

可以直接克隆仓库:git clone https://github.com/animir/node-rate-limiter-flexible.git,默认分支为 master;安装与运行步骤见仓库 README。

node-rate-limiter-flexible 最近还在维护吗?

仓库最近一次更新为 1 天前,当前有 7 个未关闭 Issue;Star 数为 3.6k,可作为社区活跃度的参考。

本页面展示项目元数据与原始 README,GitRead 中文社区 编辑团队负责选题收录。

相关仓库

affaan-m/ECC avatar
ECCaffaan-m
1 天前
300.5k
44.2k
94

代理框架性能优化系统。为 Claude Code、Codex、Opencode、Cursor 及其他工具提供技能、本能、记忆、安全性和研究优先的开发支持。

ai-agentsanthropicclaude+5
JavaScript
61.3 MB
2
详情
react/react avatar
reactreact
16 小时前
252.5k
51.4k
869

用于 Web 和原生用户界面的库。

declarativefrontendjavascript+3
JavaScript
1.1 GB
0
详情
trekhleb/javascript-algorithms avatar
javascript-algorithmstrekhleb
7月26日
196.7k
29.6k
145

用 JavaScript 实现的算法与数据结构,并附有讲解和延伸阅读链接

algorithmalgorithmscomputer-science+5
JavaScript
14.6 MB
0
详情
DietrichGebert/ponytail avatar
ponytailDietrichGebert
1 周前
188.1k
10.4k
80

让你的 AI 代理像房间里最懒的资深开发者一样思考。最好的代码是你从未写过的代码。

agent-skillsai-agentsclaude+7
JavaScript
12.8 MB
0
详情
Snailclimb/JavaGuide avatar
JavaGuideSnailclimb
2 周前
159.5k
46.1k
22

Java 面试 & 后端通用面试指南,覆盖计算机基础、数据库、分布式、高并发、系统设计与 AI 应用开发

agentaicontext-engineering+10
JavaScript
179.2 MB
1
详情
airbnb/javascript avatar
javascriptairbnb
4月17日
148.0k
24.2k
99

JavaScript 风格指南

arrow-functionses2015es2016+11
JavaScript
3.7 MB
0
详情
vercel/next.js avatar
next.jsvercel
1 小时前
143.4k
32.4k
1.1k

React 框架

blogbrowsercompiler+11
JavaScript
2.5 GB
0
详情
Chalarangelo/30-seconds-of-code avatar
30-seconds-of-codeChalarangelo
1 天前
129.5k
12.1k
0

助你提升开发技能的编程文章

astroawesome-listcss+10
JavaScript
725.2 MB
0
详情

关于

bruteforcedrizzledynamodbexpresshapikoalimitnestjspostgresqlprismarate-limitingratelimterredissecuritysqlitethrottlevalkey
  • ISC License
  • 3.6k Stars
  • 199 Forks
  • 18 Watching

简要分析

热度分
4016
价值分
2221
活跃状态
活跃
GitHub

语言占比

JavaScript
Shell

Release

  • Fix Prisma and Drizzle atomicity1 天前
  • New option: blockOnConsumed4 天前
  • Queue: not initialized queue returns correct remaining points1 周前
  • Redis: call multi only when it will be used3 周前
  • Queue: fix redundant limiter creation4 周前

贡献者

animiranimiranimirranimirrDaniel-97Daniel-97roggervalfroggervalfNeumann-NilsNeumann-NilsbackflipbackflipmroderickmroderickCopilotCopilotavifeneshavifeneshdmozgovoidmozgovoimuco-rollemuco-rollesevaunisevauni

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:

  • no race conditions
  • no production dependencies
  • TypeScript declaration bundled
  • Block Strategy against really powerful DoS attacks (like 100k requests per sec) Read about it and benchmarking here
  • Insurance Strategy as emergency solution if database/store is down Read about Insurance Strategy here
  • works in Cluster or PM2 without additional software See RateLimiterCluster benchmark and detailed description here
  • useful get, set, block, delete, penalty and reward methods

Full documentation is on Wiki

Middlewares, plugins and other packages

  • Express middleware
  • Koa middleware
  • Hapi plugin
  • GraphQL graphql-rate-limit-directive
  • NestJS nestjs-rate-limiter
  • Fastify-based NestJS app try nestjs-fastify-rate-limiter

Copy/paste examples on Wiki:

  • Minimal protection against password brute-force
  • Login endpoint protection
  • Apply Block Strategy
  • Setup Insurance Strategy
  • Websocket connection prevent flooding
  • Dynamic block duration
  • Authorized users specific limits
  • Different limits for different parts of application
  • Third-party API, crawler, bot rate limiting

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

  • Options

  • API methods

  • Drizzle Atomic and non-atomic counters.

  • DynamoDb

  • Etcd Atomic and non-atomic counters.

  • Memcached

  • Memory Supports dump() and restore() for graceful restarts and green/blue deployment

  • Mongo (with sharding support)

  • MySQL (support Sequelize and Knex)

  • Postgres (support Sequelize, TypeORM and Knex)

  • Prisma

  • Redis Atomic and non-atomic counters.

  • SQLite

  • Valkey: iovalkey or ValkeyGlide

  • RateLimiterCluster (PM2 cluster docs read here)

  • BurstyRateLimiter Traffic burst support

  • RateLimiterUnion Combine 2 or more limiters to act as single

  • RLWrapperBlackAndWhite Black and White lists

  • RLWrapperTimeouts Timeouts

  • RateLimiterQueue Rate limiter with FIFO queue

  • AWS SDK v3 Client Rate Limiter Prevent punishing rate limit.

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:

  • keyPrefix Make keys unique among different limiters.
  • blockDuration Block for N seconds, if consumed more than points.
  • blockOnConsumed Block if consumed points exceed a certain threshold.
  • inMemoryBlockOnConsumed Avoid extra requests to store.
  • inMemoryBlockDuration
  • insuranceLimiter Make it more stable with less efforts.
  • storeType Have to be set to knex, if you use it.
  • dbName Where to store points.
  • tableName Table/collection.
  • tableCreated Is table already created in MySQL, SQLite or PostgreSQL.
  • clearExpiredByTimeout For MySQL, SQLite and PostgreSQL.

See full list of options.

API

Read detailed description on Wiki.

  • consume(key, points = 1) Consume points by key.
  • get(key) Get RateLimiterRes or null.
  • set(key, points, secDuration) Set points by key.
  • block(key, secDuration) Block key for secDuration seconds.
  • delete(key) Reset consumed points.
  • deleteInMemoryBlockedAll
  • penalty(key, points = 1) Increase number of consumed points in current duration.
  • reward(key, points = 1) Decrease number of consumed points in current duration.
  • getKey(key) Get internal prefixed key.

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.

评论

登录 后发表评论
暂无评论
GitRead 中文社区
深度解读 · 趋势洞察 · 价值精选

关于

关于我们联系我们编辑准则收录标准赞赏人员

发现

技术趋势新手训练营资源精选实战指南精选专题热门话题GitHub 文档

条款

隐私政策服务条款网站地图
26.9万收录项目
5.7万中文话题
155精选专题
发现技术价值,连接开源智慧
© 2026 GitRead · GitHub 中文社区 本站与 GitHub, Inc. 无隶属关系;GitHub 是 GitHub, Inc. 的商标。