redis-guard
v1.0.7
Published
A rate-limiter npm package that supports all the algorithms.
Readme
redis-guard
A lightweight Redis-based rate limiter SDK for Node.js with multiple algorithm support.
Installation
npm install redis-guardQuick Start
import { getRedis } from 'redis-guard';
const { limit, disconnect } = getRedis(
{ redisUrl: 'redis://localhost:6379' },
{ algorithm: 'token-bucket', capacity: 10, refillRate: 2 }
);
const result = await limit('user-123');
if (result.allowed) {
// process request
} else {
// retry after result.retryAfter seconds
}
// cleanup
await disconnect();Algorithms
Token Bucket
Allows bursts up to the bucket capacity. Tokens refill at a steady rate over time.
const { limit } = getRedis(
{ redisUrl: 'redis://localhost:6379' },
{ algorithm: 'token-bucket', capacity: 10, refillRate: 2 }
);Leaky Bucket
Requests fill a queue that drains at a fixed rate. Rejected when the queue is full.
const { limit } = getRedis(
{ redisUrl: 'redis://localhost:6379' },
{ algorithm: 'leaky-bucket', capacity: 10, drainRate: 2 }
);Fixed Window
Divides time into fixed windows and counts requests per window. Simple but susceptible to burst at window boundaries.
const { limit } = getRedis(
{ redisUrl: 'redis://localhost:6379' },
{ algorithm: 'fixed-window', limit: 100, window: 60 }
);Sliding Window
Tracks each request timestamp in a rolling window. More accurate than fixed window — no boundary burst problem.
const { limit } = getRedis(
{ redisUrl: 'redis://localhost:6379' },
{ algorithm: 'sliding-window', limit: 100, window: 60 }
);Response
All algorithms return a RateLimitResult:
interface RateLimitResult {
allowed: boolean; // whether the request is allowed
remaining: number; // remaining capacity
retryAfter?: number; // seconds until next request is allowed (when denied)
resetAt: number; // timestamp (ms) when the limit resets
}Requirements
- Node.js > 20
- Redis server (local, Docker, or hosted)
