Rate Limiter Flexible Redis Points

Enforce a distributed rate limit with rate-limiter-flexible backed by Redis points, insurance fallback, and per-key consumption tracking.

JavascriptNodeResilience

Code

snippet
import { RateLimiterRedis } from 'rate-limiter-flexible';
import { createClient } from 'redis';

const redis = createClient({ url: 'redis://127.0.0.1:6379' });
await redis.connect();

const limiter = new RateLimiterRedis({
  storeClient: redis,
  keyPrefix: 'rl:api',
  points: 100,
  duration: 60,
  insuranceLimiter: {
    points: 60,
    duration: 60,
  },
});

async function guard(userId) {
  try {
    const res = await limiter.consume(userId, 1);
    return {
      allowed: true,
      remaining: res.remainingPoints,
      resetMs: res.msBeforeNext,
    };
  } catch (rej) {
    if (rej instanceof Error) throw rej; // Redis 故障,交给保险限流器兜底
    return {
      allowed: false,
      remaining: rej.remainingPoints,
      retryAfterMs: rej.msBeforeNext,
    };
  }
}

const first = await guard('user-9');
const burst = await Promise.all(
  Array.from({ length: 5 }, () => guard('user-9')),
);
console.log(first.allowed, burst.filter((b) => !b.allowed).length, 'throttled');
await redis.quit();