← Back to Node.js, page 8

nodejs-0152 · Hard senior

How do you build a rate limiter for a public API that works across several Node.js instances, and how do you report limits to clients?

An in-memory limiter is per instance, so the real limit grows with the number of instances. Keep the counters in Redis and make the check-and-update atomic with a Lua script (a token bucket or a window counter). Key by API key or user first and IP second, answer 429 with Retry-After and rate limit headers, and decide what to do when Redis is down (usually fail open with an alert).

Full answer

Why Redis

  • With three instances and an in-memory limit of 100 per minute, a client can send up to 300. A shared store gives one counter.
  • A read followed by a write from several instances is a race. A Lua script runs atomically inside Redis, so check and update happen as one step.

Algorithms

  • Fixed window: INCR a key per window and set EXPIRE. Simple, but allows a burst of 2x the limit across a window boundary.
  • Sliding window log or counter: smoother, more memory or math.
  • Token bucket: a bucket of N tokens refills at a steady rate. It allows short bursts and limits the average. Store tokens and the last refill time; compute the refill on each request using Redis TIME so instance clocks do not matter.

API behaviour

  • Respond 429 Too Many Requests with Retry-After (seconds). Add RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset headers (the standard is still a work in progress at the IETF, so some APIs use X-RateLimit-*).
  • Identify callers by API key or user id. Use IP as a fallback, and remember that many users can share one IP (NAT) and that X-Forwarded-For can be faked unless your proxy sets it.
  • Different limits per plan and per route (login attempts need much stricter limits than reads).
  • Expire keys so memory is bounded.

Failure policy

  • If Redis is unavailable: fail open (allow, log, alert) for normal routes, fail closed for dangerous ones (login, payment). Use a short timeout so Redis problems do not slow all requests.
  • Add a small local limiter as a second layer for abuse spikes.

Test: parallel requests from several clients, clock changes, and expiry of idle keys.

javascript
const Redis = require('ioredis');

const redis = new Redis(process.env.REDIS_URL || 'redis://127.0.0.1:6379');
const prefix = `rl-demo:${process.pid}:`;

// Token bucket in Lua: KEYS[1] = bucket, ARGV = capacity, refill tokens per second, cost
redis.defineCommand('takeToken', {
  numberOfKeys: 1,
  lua: `
    local capacity = tonumber(ARGV[1])
    local rate = tonumber(ARGV[2])
    local now = redis.call('TIME')
    local nowMs = now[1] * 1000 + math.floor(now[2] / 1000)
    local state = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
    local tokens = tonumber(state[1]) or capacity
    local ts = tonumber(state[2]) or nowMs
    tokens = math.min(capacity, tokens + (nowMs - ts) * rate / 1000)
    local allowed = 0
    local retryMs = 0
    if tokens >= 1 then
      tokens = tokens - 1
      allowed = 1
    else
      retryMs = math.ceil((1 - tokens) * 1000 / rate)
    end
    redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', nowMs)
    redis.call('PEXPIRE', KEYS[1], math.ceil(capacity / rate * 1000) + 1000)
    return { allowed, math.floor(tokens), retryMs }
  `,
});

async function limit(apiKey) {
  const [allowed, remaining, retryMs] = await redis.takeToken(prefix + apiKey, 5, 1);   // burst 5, refill 1 per second
  return { allowed: allowed === 1, remaining, retryAfterSeconds: Math.ceil(retryMs / 1000) };
}

async function main() {
  const results = [];
  for (let i = 0; i < 8; i++) results.push(await limit('key-A'));
  console.log('key-A:', results.map((r) => (r.allowed ? 'ok(' + r.remaining + ')' : 'DENIED')).join(' '));
  console.log('Retry-After for the denied requests:', [...new Set(results.filter((r) => !r.allowed).map((r) => r.retryAfterSeconds))].join(','), 'second(s)');
  console.log('key-B has its own bucket:', (await limit('key-B')).allowed);

  // Parallel requests share the same atomic bucket (as if they came from different instances).
  const parallel = await Promise.all(Array.from({ length: 20 }, () => limit('key-C')));
  console.log('20 parallel requests, allowed:', parallel.filter((r) => r.allowed).length, '(capacity is 5)');

  const keys = await redis.keys(prefix + '*');
  const ttl = await redis.pttl(keys[0]);
  console.log('buckets expire by themselves:', ttl > 0);
  await redis.del(...keys);
  await redis.quit();
}
main();

The Lua script runs inside Redis. The script needs a running Redis server and shows a burst of 5, the denial after it, and 20 parallel requests sharing one bucket. Install first with npm install ioredis (run here with ioredis 6.1.1). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): key-A: ok(4) ok(3) ok(2) ok(1) ok(0) DENIED DENIED DENIED Retry-After for the denied requests: 1 second(s) key-B has its own bucket: true 20 parallel requests, allowed: 5 (capacity is 5) buckets expire by themselves: true

Key points

  • An in-memory limiter multiplies the limit by the instance count.
  • A Lua script makes check and update atomic.
  • Token bucket allows bursts and limits the average rate.
  • Return 429 with Retry-After and rate limit headers.
  • Choose fail open or fail closed per route.

Common mistakes

  • Using an in-memory limiter on several instances.
  • Reading the count and writing it back in two separate commands.
  • Trusting X-Forwarded-For from any client.
  • No Retry-After, so clients retry immediately.
  • Using the same limit for login and for read endpoints.

Follow-ups

  • Why is a fixed window limiter allowed to burst to twice the limit?
  • How would you rate limit by user and by IP at the same time?
  • What happens to your service if Redis is slow?

Tips

  • Start with 'in-memory limits multiply by instance count'.
  • Say that Lua makes the step atomic.
  • State the fail-open decision.