Token bucket and sliding window rate limiting for Node.js. Memory in development, Redis in production — one line changes the backend.
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' }); }
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
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', }));
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
| 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 | ✓ | ✓ | ✓ | ✗ |
Zero configuration needed to start. Swap to Redis when you're ready to scale.