distributed-limiter 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Rohit Pandey
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,195 @@
1
+ # distributed-limiter
2
+
3
+
4
+
5
+ A high-performance distributed rate limiter based on the Token Bucket algorithm, designed for Node.js applications using Redis as the backing store.
6
+
7
+
8
+
9
+ ## Features
10
+
11
+
12
+
13
+ - Token Bucket rate limiting
14
+
15
+ - Redis-backed distributed state
16
+
17
+ - Atomic operations using Lua scripts
18
+
19
+ - TypeScript support
20
+
21
+ - Lightweight and framework-agnostic
22
+
23
+ - Suitable for APIs, services, and microservices
24
+
25
+
26
+
27
+ ## Installation
28
+
29
+
30
+
31
+ ```bash
32
+
33
+ npm install distributed-limiter
34
+
35
+ ```
36
+
37
+
38
+
39
+ ## Quick Start
40
+
41
+
42
+
43
+ ```ts
44
+
45
+ import { TokenBucketLimiter } from "distributed-limiter";
46
+
47
+
48
+
49
+ const limiter = new TokenBucketLimiter({
50
+
51
+ redis,
52
+ capacity,
53
+ refillRate
54
+
55
+ });
56
+
57
+
58
+
59
+ const result = await limiter.isAllowed({
60
+
61
+ key: "user:123",
62
+
63
+ tokenRequest: 1,
64
+
65
+ });
66
+
67
+
68
+
69
+ if (result.allowed) {
70
+
71
+ console.log("Request allowed");
72
+
73
+ } else {
74
+
75
+ console.log("Rate limit exceeded");
76
+
77
+ }
78
+
79
+ ```
80
+
81
+
82
+
83
+ ## API
84
+
85
+
86
+
87
+ ### `new TokenBucketLimiter(options)`
88
+
89
+
90
+
91
+ Creates a new limiter instance.
92
+
93
+
94
+
95
+ ```ts
96
+
97
+ const limiter = new TokenBucketLimiter({
98
+
99
+ redis,
100
+ limiterCapacity,
101
+ refillRate
102
+
103
+ });
104
+
105
+ ```
106
+
107
+
108
+
109
+ ### `limiter.isAllowed(request)`
110
+
111
+
112
+
113
+ Checks whether a request can consume the requested number of tokens.
114
+
115
+
116
+
117
+ ```ts
118
+
119
+ const result = await limiter.isAllowed({
120
+
121
+ key: string,
122
+
123
+ tokenRequest: number,
124
+
125
+ });
126
+
127
+ ```
128
+
129
+
130
+
131
+ #### Request Parameters
132
+
133
+ `key` - Unique identifier (user, IP, API key, etc.)
134
+
135
+ `capacity` - Maximum bucket size
136
+
137
+ `refillRate` - Tokens added per second
138
+
139
+ `tokenRequest` - Tokens required for the request
140
+
141
+ **Note:** `capacity` and `refillRate` can be configured once during limiter initialization and reused automatically for all requests. In applications, only `key` and `tokenRequest` need to be supplied per request.
142
+
143
+ #### Response
144
+
145
+
146
+
147
+ ```ts
148
+
149
+ {
150
+
151
+ allowed: boolean;
152
+
153
+ }
154
+
155
+ ```
156
+
157
+
158
+
159
+ ## Architecture
160
+
161
+ ![Diagram](assets/Rate%20Limiter%20Architecture.png)
162
+
163
+ ```text
164
+
165
+ Client Request
166
+
167
+
168
+
169
+
170
+
171
+ BucketLimiter
172
+
173
+
174
+
175
+
176
+
177
+ Redis Lua Script
178
+
179
+
180
+
181
+
182
+
183
+ Token Bucket State
184
+
185
+ ```
186
+
187
+
188
+
189
+ The limiter stores bucket state in Redis and performs all token calculations atomically through Lua scripts to ensure correctness across multiple application instances.
190
+
191
+
192
+
193
+ ## License
194
+
195
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ Limiter: () => Limiter
34
+ });
35
+ module.exports = __toCommonJS(index_exports);
36
+
37
+ // src/core/TokenBucket.ts
38
+ var import_fs = __toESM(require("fs"), 1);
39
+ var import_path = __toESM(require("path"), 1);
40
+ var import_meta = {};
41
+ var tokenBucketLua = import_fs.default.readFileSync(import_path.default.join(import_meta.dirname, "../db/scripts/tokenBucket.lua"), "utf-8");
42
+ async function TokenBucket(redis, { key, capacity, refillRate, tokenRequest }) {
43
+ const currentTime = Date.now();
44
+ const sha = await redis.script("LOAD", tokenBucketLua);
45
+ try {
46
+ const result = await redis.evalsha(
47
+ sha,
48
+ 1,
49
+ key,
50
+ capacity,
51
+ refillRate,
52
+ tokenRequest,
53
+ currentTime
54
+ );
55
+ return result === 1;
56
+ } catch (error) {
57
+ if (error instanceof Error && error.message.includes("NOSCRIPT")) {
58
+ const result = await redis.eval(
59
+ tokenBucketLua,
60
+ 1,
61
+ key,
62
+ capacity,
63
+ refillRate,
64
+ tokenRequest,
65
+ currentTime
66
+ );
67
+ return result === 1;
68
+ }
69
+ throw Error;
70
+ }
71
+ }
72
+
73
+ // src/core/LimiterEngine.ts
74
+ var Limiter = class {
75
+ constructor(redis, capacity, refillRate) {
76
+ this.redis = redis;
77
+ this.capacity = capacity;
78
+ this.refillRate = refillRate;
79
+ }
80
+ redis;
81
+ capacity;
82
+ refillRate;
83
+ async isAllowed({ key, tokenRequest }) {
84
+ const args = {
85
+ key,
86
+ capacity: this.capacity,
87
+ refillRate: this.refillRate,
88
+ tokenRequest
89
+ };
90
+ const redisResponse = await TokenBucket(this.redis, args);
91
+ ;
92
+ return redisResponse;
93
+ }
94
+ };
95
+ // Annotate the CommonJS export names for ESM import in node:
96
+ 0 && (module.exports = {
97
+ Limiter
98
+ });
@@ -0,0 +1,22 @@
1
+ import { Redis } from 'ioredis';
2
+
3
+ type BucketOptions = {
4
+ key: string;
5
+ capacity: number;
6
+ refillRate: number;
7
+ tokenRequest: number;
8
+ };
9
+ type RateLimiterOptions = {
10
+ key: string;
11
+ tokenRequest: number;
12
+ };
13
+
14
+ declare class Limiter {
15
+ private redis;
16
+ private capacity;
17
+ private refillRate;
18
+ constructor(redis: Redis, capacity: number, refillRate: number);
19
+ isAllowed({ key, tokenRequest }: RateLimiterOptions): Promise<Boolean>;
20
+ }
21
+
22
+ export { type BucketOptions, Limiter, type RateLimiterOptions };
package/dist/index.js ADDED
@@ -0,0 +1,113 @@
1
+ // src/db/scripts/tokenBucket.ts
2
+ var bucketLua = `local key = KEYS[1];
3
+
4
+ local capacity = tonumber(ARGV[1]) or 0;
5
+ local refillRate = tonumber(ARGV[2]);
6
+ local tokenRequest = tonumber(ARGV[3]);
7
+ local currentTime = tonumber(ARGV[4]);
8
+
9
+ --get bucket from redis
10
+ local bucket = redis.call(
11
+ "HMGET",
12
+ key,
13
+ "tokens",
14
+ "lastRefill"
15
+ )
16
+ --declare token and lastRefill from bucket
17
+ local tokens = tonumber(bucket[1]);
18
+ local lastRefill = tonumber(bucket[2]);
19
+
20
+ --if no token refillRate, initialize token with capacity and lastRefill with currentTime.
21
+ if tokens == nil then
22
+ tokens = capacity
23
+ lastRefill = currentTime
24
+ end
25
+
26
+ --calculate refill and elapsed time
27
+ local elapsedTime = (currentTime - lastRefill) / 1000
28
+ local refill = elapsedTime * refillRate
29
+
30
+ --prepare tokens and avoid bucket overflow
31
+ tokens = math.min(capacity, tokens + refill)
32
+
33
+ --if requestedTokens exceeds available tokens, return 0
34
+ if tokens < tokenRequest then
35
+ return 0
36
+ end
37
+ --consume tokens
38
+ tokens = tokens - tokenRequest
39
+ --HMSET the new bucket in redis
40
+ redis.call(
41
+ "HMSET",
42
+ key,
43
+ "tokens",
44
+ tokens,
45
+ "lastRefill",
46
+ currentTime
47
+ )
48
+ --set redis expire
49
+ redis.call(
50
+ "EXPIRE",
51
+ key,
52
+ 3600
53
+ )
54
+ return 1`;
55
+
56
+ // src/core/TokenBucket.ts
57
+ var tokenBucketLua = bucketLua;
58
+ async function TokenBucket(redis, { key, capacity, refillRate, tokenRequest }) {
59
+ const currentTime = Date.now();
60
+ const sha = await redis.script("LOAD", tokenBucketLua);
61
+ try {
62
+ const result = await redis.evalsha(
63
+ sha,
64
+ 1,
65
+ key,
66
+ capacity,
67
+ refillRate,
68
+ tokenRequest,
69
+ currentTime
70
+ );
71
+ return result === 1;
72
+ } catch (error) {
73
+ if (error instanceof Error && error.message.includes("NOSCRIPT")) {
74
+ const result = await redis.eval(
75
+ tokenBucketLua,
76
+ 1,
77
+ key,
78
+ capacity,
79
+ refillRate,
80
+ tokenRequest,
81
+ currentTime
82
+ );
83
+ return result === 1;
84
+ }
85
+ throw Error;
86
+ }
87
+ }
88
+
89
+ // src/core/LimiterEngine.ts
90
+ var Limiter = class {
91
+ constructor(redis, capacity, refillRate) {
92
+ this.redis = redis;
93
+ this.capacity = capacity;
94
+ this.refillRate = refillRate;
95
+ }
96
+ redis;
97
+ capacity;
98
+ refillRate;
99
+ async isAllowed({ key, tokenRequest }) {
100
+ const args = {
101
+ key,
102
+ capacity: this.capacity,
103
+ refillRate: this.refillRate,
104
+ tokenRequest
105
+ };
106
+ const redisResponse = await TokenBucket(this.redis, args);
107
+ ;
108
+ return redisResponse;
109
+ }
110
+ };
111
+ export {
112
+ Limiter
113
+ };
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "distributed-limiter",
3
+ "version": "1.0.0",
4
+ "description": "Distributed token bucket rate limiter using Redis and Lua",
5
+ "homepage": "https://github.com/Toxic209/distributed-rate-limiter#readme",
6
+ "bugs": {
7
+ "url": "https://github.com/Toxic209/distributed-rate-limiter/issues"
8
+ },
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/Toxic209/distributed-rate-limiter.git"
12
+ },
13
+ "license": "MIT",
14
+ "author": "rohit pandey",
15
+ "type": "module",
16
+ "main": "index.js",
17
+ "scripts": {
18
+ "dev": "nodemon --watch src --ext ts --exec tsx src/index.ts",
19
+ "build": "tsup src/index.ts --format esm --dts"
20
+ },
21
+ "devDependencies": {
22
+ "@types/node": "^25.9.1",
23
+ "ioredis": "^5.10.1",
24
+ "nodemon": "^3.1.14",
25
+ "ts-node": "^10.9.2",
26
+ "tsup": "^8.5.1",
27
+ "tsx": "^4.22.3",
28
+ "typescript": "^6.0.3"
29
+ },
30
+ "peerDependencies": {
31
+ "ioredis": "^5.0.0"
32
+ },
33
+
34
+ "files": [
35
+ "dist",
36
+ "db"
37
+ ],
38
+
39
+ "keywords": [
40
+ "rate-limiter",
41
+ "redis",
42
+ "token-bucket",
43
+ "distributed-systems"
44
+ ]
45
+ }