← Back to Backend, page 2

backend-0040 · Hard senior

How do you implement a rate limiter shared by many servers with Redis, why must the check be atomic, and should the limiter fail open or fail closed?

Keep the limiter state in Redis so all servers share it. A sliding window log fits a sorted set: remove entries older than the window, count the rest, add the new request if under the limit. The three steps must be atomic, or concurrent requests all pass the check before any is recorded and the limit is exceeded. A Lua script (or a transaction with the right guards) runs them as one unit. Decide what happens when Redis is down: fail open (allow) for availability, or fail closed (reject) for protection.

Full answer

Design

  • Key per client: rl:{api_key}. Sorted set: score = timestamp in milliseconds, member = unique request id.
  • Script (one atomic call): ZREMRANGEBYSCORE key 0 (now - window); count = ZCARD key; if count < limit then ZADD key now member, PEXPIRE key window, return allowed and remaining; else return denied and the time until the oldest entry leaves the window.
  • Use the Redis server clock (TIME command in the script) so that application servers with clock drift do not disagree.
  • Set an expiry so idle clients do not stay in memory. Memory is O(limit) per client. For very high limits use the counter or token bucket variants.

Why atomic

  • Separate commands (count, then add) let 20 concurrent requests all read count 4 with a limit of 5, and all add. A MULTI/EXEC block does not help for read-then-decide logic, because the decision happens in the client. Lua scripts execute without interleaving.

Operational choices

  • Fail open or closed? A limiter outage that blocks all traffic is often worse than the abuse it prevents, so many APIs fail open and alert. Fail closed for security sensitive limits (login, password reset).
  • Add a short local timeout to Redis calls so the limiter cannot slow the API.
  • Return 429, Retry-After and RateLimit headers. Shard keys in Redis Cluster by client.
javascript
const Redis = require('ioredis');
const redis = new Redis(process.env.REDIS_URL);

const LUA = `
  local now = tonumber(redis.call('TIME')[1]) * 1000 + math.floor(tonumber(redis.call('TIME')[2]) / 1000)
  local window, limit = tonumber(ARGV[1]), tonumber(ARGV[2])
  redis.call('ZREMRANGEBYSCORE', KEYS[1], 0, now - window)
  local count = redis.call('ZCARD', KEYS[1])
  if count < limit then
    redis.call('ZADD', KEYS[1], now, ARGV[3])
    redis.call('PEXPIRE', KEYS[1], window)
    return {1, limit - count - 1}
  end
  return {0, 0}
`;
let seq = 0;
const requestId = () => `${process.pid}-${++seq}`;

const atomicCheck = async (client, key) => (await client.eval(LUA, 1, key, 10000, 5, requestId()))[0] === 1;

// The racy version: count, decide in the client, then add.
async function racyCheck(client, key) {
  const count = await client.zcard(key);
  if (count >= 5) return false;
  await client.zadd(key, Date.now(), requestId());
  return true;
}

async function limiter(client, key, onError) {
  try { return await atomicCheck(client, key); } catch (err) { return onError === 'open'; }
}

(async () => {
  await redis.del('bk40:racy', 'bk40:atomic');
  const burst = 20;
  const racy = (await Promise.all(Array.from({ length: burst }, () => racyCheck(redis, 'bk40:racy')))).filter(Boolean).length;
  const atomic = (await Promise.all(Array.from({ length: burst }, () => atomicCheck(redis, 'bk40:atomic')))).filter(Boolean).length;
  console.log('limit 5, 20 concurrent requests -> racy check allowed more than 5:', racy > 5, '| atomic script allowed:', atomic);
  console.log('key expires on its own     :', (await redis.pttl('bk40:atomic')) > 0);

  // Redis is unreachable: choose a policy.
  const broken = new Redis({ port: 1, lazyConnect: true, enableOfflineQueue: false, maxRetriesPerRequest: 0, retryStrategy: () => null });
  broken.on('error', () => {});
  console.log('Redis down, fail open      :', await limiter(broken, 'x', 'open'), '| fail closed:', await limiter(broken, 'x', 'closed'));

  await redis.del('bk40:racy', 'bk40:atomic');
  redis.disconnect(); broken.disconnect();
})();

Runs on the local Redis server. Twenty requests start at once against a limit of five, once with a racy check and once with the Lua script. The outage is simulated with a connection to a closed port. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): limit 5, 20 concurrent requests -> racy check allowed more than 5: true | atomic script allowed: 5 key expires on its own : true Redis down, fail open : true | fail closed: false

Key points

  • Share limiter state through Redis.
  • Run remove, count and add as one atomic Lua script.
  • A check-then-add race lets bursts through the limit.
  • Use the Redis clock and key expiry.
  • Decide fail open or fail closed per use case.

Common mistakes

  • Counting and adding in separate commands.
  • Using each app server's own clock.
  • No key expiry.
  • Failing closed for every endpoint and turning a Redis outage into a full outage.
  • Using a sorted set for very high limits where a counter is enough.

Follow-ups

  • How would you implement a token bucket in a Lua script?
  • How does Redis Cluster affect the key design?
  • How do you test a limiter under concurrency?

Tips

  • Explain the race with numbers.
  • Say 'one atomic script'.
  • State your fail open or closed policy.