2.1.7 • Published 4 months ago

rate-limiter-algorithms v2.1.7

Weekly downloads
-
License
MIT
Repository
github
Last release
4 months ago

Rate Limiter Algorithms

Library that provides different algorithms to perform rate limiting.

NPM Version NPM Downloads LICENSE

Example with Node.js

import { createServer } from "node:http";
import { RateLimiter } from "rate-limiter-algorithms";

const limiter = new RateLimiter({
    algorithm: "token-bucket",
    limit: 5,
    windowMs: 5000,
});

const server = createServer(async (req, res) => {
    const ip = req.socket.remoteAddress || "any unique key";

    try {
        const { isAllowed, clientData } = await limiter.consume(ip);

        // set rate limiting headers
        const headers = limiter.getHeaders(clientData);
        for (const header of headers) {
            res.setHeader(header[0], header[1]);
        }

        if (!isAllowed) {
            res.writeHead(429, "Too many requests");
            res.end("Failure");
            return;
        }
        res.end("Success");
    } catch (error) {
        console.error("Error in rate limiting:", error);
    }
});

server.listen(3000, "127.0.0.1", () => {
    console.log("Listening on 127.0.0.1:3000");
});

Config

OptionTypeExplanation
algorithmstringValues: token-bucket, fixed-window-counter, sliding-window-logs, sliding-window-counter
windowMsnumberDuration of time in milliseconds when algorithm updates its counter.
limitnumberMaximum amount of points that client can consume
storeStoreStore which contains clients data based on chosen algorithm. Defaults to Memory Store

Date Stores

Memory Store

Default in-memory option. Example:

import { RateLimiter, MemoryStore } from "rate-limiter-algorithms";

const limiter = new RateLimiter({
    algorithm: "token-bucket",
    limit: 5,
    windowMs: 5000,
    store: new MemoryStore(),
});

Redis Store

Uses rawCall function to send raw commands to Redis. Example for node-redis :

import { RateLimiter, RedisStore } from "rate-limiter-algorithms";
import { createClient } from "redis";

const client = createClient();
client.connect();

const limiter = new RateLimiter({
    algorithm: "token-bucket",
    limit: 5,
    windowMs: 5000,
    store: new RedisStore({
        prefix: "rla:", // it's default prefix
        rawCall: (...args: string[]) => client.sendCommand(args),
    }),,
});

Raw command list:

LibraryFunction
node-redis(...args: string[]) => client.sendCommand(args)
ioredis(command: string, ...args: string[]) => client.call(command, ...args)

License

All code and documentation are (c) 2024-Present Eugene Shumilin and released under the MIT License

2.1.6

4 months ago

2.1.5

7 months ago

2.1.7

4 months ago

2.1.4

9 months ago

2.1.2

11 months ago

2.1.3

11 months ago

2.1.1

1 year ago

2.1.0

1 year ago

2.0.0

1 year ago

1.0.0

1 year ago