v1.0.0 · MIT · Node ≥ 18

rate.limit(
  'user-123',
  { backend: 'redis' }
)

Token bucket and sliding window rate limiting for Node.js. Memory in development, Redis in production — one line changes the backend.

18kb
published size
44
tests passing
0
prod dependencies
// live demo — token bucket
limiter.check('api-key-xyz') 10 req / 10s
tokens 10 / 10
time key result remaining
// memory backend

Dev in minutes

No Redis needed to get started. Drop in the memory backend and the full API is available immediately.

import { RateLimiter } from '@anantduhan/limiter-core';

const limiter = new RateLimiter({
  strategy: 'token-bucket',
  rate: 100,
  window: '1 minute',
  burst: 150,
  backend: 'memory',   // ← dev
});

const { allowed, remaining } =
  await limiter.check('user-123');

if (!allowed) {
  res.status(429).json({ error: 'slow down' });
}
// redis backend

Ship to prod

Change one field. The same keys, the same methods, the same behaviour — now atomic across every server in your fleet.

import { createClient } from 'redis';

const redis = createClient({
  url: process.env.REDIS_URL,
});
await redis.connect();

const limiter = new RateLimiter({
  strategy: 'token-bucket',
  rate: 100,
  window: '1 minute',
  burst: 150,
  backend: 'redis',     // ← prod
  redisClient: redis,
});

// identical API from here
// express

Express middleware

Rate limit by IP, user ID, API key, or any value you extract from the request.

import { expressMiddleware }
  from '@anantduhan/limiter-core';

app.use(expressMiddleware(limiter, {
  keyExtractor: (req) =>
    req.user?.id ?? req.ip,

  onLimitReached: (req, res, r) =>
    res.status(429).json({
      retryAfter: r.retryAfter,
    }),

  skip: (req) =>
    req.path === '/health',
}));
// fastify

Fastify plugin

Registered as a Fastify plugin. Runs in the preHandler hook and cleans up on server close automatically.

import { fastifyPlugin }
  from '@anantduhan/limiter-core';

await app.register(fastifyPlugin, {
  limiter,

  keyExtractor: (req) =>
    req.headers['x-api-key']
    ?? req.ip,
});

// X-RateLimit-* headers added
// automatically to every response
// Retry-After on 429s
// what's inside

Built for production from day one

01 — strategy
Token bucket
Smooth rate limiting with configurable burst. Tokens refill gradually — a quiet user banks credit for later.
02 — strategy
Sliding window
Exact per-window counting with no burst. Every request in the last N milliseconds is counted precisely.
03 — backend
Atomic Lua scripts
Redis operations run as a single atomic Lua script. No lost updates under concurrent load across any number of servers.
04 — reliability
Clock skew handling
Uses Redis TIME command, never client Date.now(). NTP drift between app servers cannot corrupt your buckets.
05 — reliability
Fail open
If Redis is unreachable, requests are allowed through and the error is logged. Downtime in your cache layer won't take down your API.
06 — ops
Auto-expiring keys
Keys expire after 2× the window with no activity. Inactive users never accumulate stale entries in Redis.
// how it stacks up

Compared to alternatives

package @anantduhan/limiter-core express-rate-limit bottleneck redis-rate-limiter
distributed (Redis) ✓ ✗ ✗ ✓
memory + redis same API ✓ ✗ ✗ ✗
token bucket ✓ ✓ ✓ ✗
sliding window ✓ ✓ ✗ ✗
burst allowance ✓ ✗ ✓ ✗
clock skew handling ✓ ✗ ✗ ✗
express + fastify adapters ✓ express only ✗ ✗
TypeScript ✓ ✓ ✓ ✗
// get started

Install in 30 seconds

Zero configuration needed to start. Swap to Redis when you're ready to scale.

$ npm install @anantduhan/limiter-core click to copy
peer deps: redis ≥ 4 (optional) · express ≥ 4 (optional) · fastify ≥ 4 (optional)