Node.js · Backend · API · Security

Rate Limiting a Node.js API: Fixed Window, Sliding Window and Token Bucket with Redis

How to rate limit a Node.js API properly: choosing fixed window, sliding window or token bucket, atomic Redis implementations, 429 responses, headers and proxy pitfalls.

Sander Yazıcıoğlu Published: 4 min read Türkçe oku

Rate Limiting a Node.js API: Fixed Window, Sliding Window and Token Bucket with Redis

Rate limiting usually gets added the day after something goes wrong: a script hammering a login endpoint, a customer's CI job polling a status API in a tight loop, or a single test run firing thousands of requests at a shared service. I have added limits in all three situations, and the lesson was the same each time. The algorithm matters less than three details: what you key on, where the counter lives, and what the client is told when it is refused.

What are you protecting?

Write down the goal before picking an algorithm, because each one answers a different question:

GoalKeyTypical limit
Stop credential stuffingIP + username5 attempts / 15 min
Fair share of an expensive endpointAPI key or user id60 / min
Protect the database from burstsGlobal or per tenantToken bucket
Cost control for LLM callsUser idDaily quota

A single global middleware with "100 requests per minute per IP" rarely matches any of these. Users behind one corporate NAT share an IP, while an attacker rotates through many.

The three algorithms

Fixed window. Count requests per key in buckets such as "12:01". Simple and cheap, but a client can send the full limit at 12:01:59 and again at 12:02:00, so it briefly gets double the rate at the boundary.

Sliding window. Either store every timestamp (a "log", accurate but memory-heavy) or approximate with two fixed windows: current + previous * (1 - elapsedFraction). The approximation is what most production systems use, and it removes the boundary spike.

Token bucket. Each key has a bucket of capacity tokens that refills at a steady rate; each request takes one. It allows short bursts up to the capacity while enforcing an average rate. It is the best fit for APIs where clients legitimately send batches.

Where the counter lives

An in-memory Map works for a single process and is fine for local development. The moment you run two instances behind a load balancer, each instance only sees part of the traffic and the effective limit multiplies. Use a shared store; Redis is the usual choice because its operations are atomic and keys can expire on their own. The Redis caching patterns post covers the basics of running it.

Fixed window in Redis

INCR followed by a separate EXPIRE has a gap: if the process crashes between them, the key never expires and the client is blocked forever. Send both in one transaction, and use NX (Redis 7+) so the expiry is set only once per window:

import Redis from 'ioredis';
const redis = new Redis(process.env.REDIS_URL!);

async function fixedWindow(key: string, limit: number, windowSec: number) {
  const window = Math.floor(Date.now() / 1000 / windowSec);
  const redisKey = `rl:${key}:${window}`;
  const [[, count]] = (await redis
    .multi()
    .incr(redisKey)
    .expire(redisKey, windowSec, 'NX')
    .exec()) as [[Error | null, number], unknown];
  return { allowed: count <= limit, remaining: Math.max(0, limit - count) };
}

Token bucket as a Lua script

The token bucket needs a read, a calculation and a write. Doing that from Node in separate calls is a race between concurrent requests. A Lua script runs atomically inside Redis:

-- KEYS[1] bucket key; ARGV: capacity, refill per ms, now in ms
local capacity = tonumber(ARGV[1])
local rate = tonumber(ARGV[2])
local now = tonumber(ARGV[3])
local data = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(data[1]) or capacity
local ts = tonumber(data[2]) or now
tokens = math.min(capacity, tokens + (now - ts) * rate)
local allowed = 0
if tokens >= 1 then
  tokens = tokens - 1
  allowed = 1
end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], math.ceil(capacity / rate))
return allowed
redis.defineCommand('takeToken', { numberOfKeys: 1, lua: tokenBucketLua });

// 20-request burst, refilling 10 tokens per second
const allowed = await (redis as any).takeToken(`tb:${apiKey}`, 20, 10 / 1000, Date.now());

Passing Date.now() from the app means instance clocks must be roughly in sync; NTP is normally enough. The expiry deletes idle buckets, which are equivalent to full ones anyway.

Telling the client what happened

A refused request should return 429 Too Many Requests with a Retry-After header in seconds. Well-behaved clients, including most HTTP libraries' retry plugins, respect it. Also expose the remaining budget so clients can slow down before they hit the wall. The IETF draft headers are RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset:

res.set('RateLimit-Limit', String(limit));
res.set('RateLimit-Remaining', String(remaining));
if (!allowed) {
  res.set('Retry-After', String(retryAfterSec));
  return res.status(429).json({ error: 'rate_limited', retryAfter: retryAfterSec });
}

Keep the error body in the same format as the rest of your API, as described in the REST API design guide.

Pitfalls I have hit

  • Wrong client IP behind a proxy. Behind Cloudflare or a load balancer, req.ip is the proxy's address unless Express is told to trust it: app.set('trust proxy', 1) for one hop. Never trust X-Forwarded-For blindly when the app is reachable directly, or clients can spoof any IP.
  • Limiting health checks. Exclude probe and metrics endpoints, or a busy monitor will mark the service unhealthy.
  • Failing closed when Redis is down. Decide explicitly. For most endpoints, allowing traffic and logging is better than a full outage; for login, failing closed may be the right call.
  • Counting before authentication. Unauthenticated requests should be limited by IP before the expensive auth lookup, authenticated ones by user afterwards.

Do you need to write it yourself?

Often not. express-rate-limit with a Redis store covers fixed and sliding windows and sets the standard headers. Cloudflare's rate limiting rules stop abusive traffic before it reaches the origin at all, which pairs well with the techniques in protecting contact forms from spam. Writing your own is worth it when you need a token bucket, per-tenant quotas, or limits tied to cost rather than request count.

Conclusion

Pick the key and the goal first, then the algorithm: fixed window for simple caps, sliding window to remove boundary spikes, token bucket when bursts are legitimate. Keep counters in Redis with atomic operations, return 429 with Retry-After, and get the client IP right behind proxies. Those details decide whether the limiter protects you or just blocks your best customers.

All articles →