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

javascriptsnippet
41 lines
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();

How it works

Count the function guard as the entire surface area of Rate Limiter Flexible Redis Points.

Await points sequence the asynchronous work; a rejection lands at the awaiting line. Reach for rate-limiter-flexible and what you get is RateLimiterRedis, createClient — that is the whole API contact area.

The result comes back as an object carrying true, remainingPoints, msBeforeNext.

What to watch for

  • Dependency check: rate-limiter-flexible and redis — not built-in, must be present in the project.
  • The guard rej instanceof Error short-circuits the flow with an early throw when its condition holds.

Putting it to use

The primary signature is async function guard(userId)

The call returns true, remainingPoints, msBeforeNext — destructure what you need at the call site.

Core lines

const burst = await Promise.all(
Array.from({ length: 5 }, () => guard('user-9')),
);
if (rej instanceof Error) throw rej; // Redis 故障,交给保险限流器兜底
return {
allowed: false,
remaining: rej.remainingPoints,
retryAfterMs: rej.msBeforeNext,
};
const res = await limiter.consume(userId, 1);

Interactive Tools for This Topic

FAQ

Does `guard` modify its input?
No. Nothing passed in is written to, which makes the call safe on shared data.
Do I need to install anything before running this?
Yes: `rate-limiter-flexible` and `redis` must be present in the project or the import fails at load time.