API rate limiting Node.js services with Redis comes down to one atomic counter per client, shared by every instance. This tutorial builds that counter in five steps with Express and node-redis. It then covers the two mistakes that break it in production and shows how to test it.
The problem
An in-memory limiter, such as a counter in a Map, only sees traffic on its own process. Run four Node instances behind a load balancer and a client gets four times the limit. The count also resets on every deploy.
Redis fixes both problems. It holds one count per client that every instance reads and writes. On the same network, a Redis round trip typically adds under a millisecond.
Prerequisites
- Node.js 20 or later, with ES modules enabled.
- Express 4 or 5. The middleware below works on both.
- Redis 6 or later, or Valkey. A local container is enough: docker run -p 6379:6379 redis:7.
- The redis npm package (node-redis), version 4 or later. If you use ioredis, the eval call signature differs, and step 2 shows both.
Pick an algorithm before you write code
Three algorithms cover almost every API. Each one trades accuracy against memory and complexity.
Fixed window counter
This stores one integer per client per window. It is cheap and easy to reason about. The catch is that a client can send a full quota at 0:59 and another at 1:00, so short bursts can reach twice the limit.
Sliding window log
This uses a Redis sorted set with one timestamp per request. It is exact, but memory grows with the limit. At 1,000 requests per minute, you store up to 1,000 entries per client.
Token bucket
Tokens refill at a steady rate, and each request spends one. This allows controlled bursts and smooths traffic. The trade-off is a longer Lua script that is harder to review.
Our position: start with a fixed window. For most APIs the boundary burst does not matter, and your team will debug the simple version correctly at 2 a.m. Move to a sliding log or token bucket only when a downstream service cannot absorb a 2x burst.
You get limits sized to your real traffic instead of guesses when we build this for clients — ask us about yours.
Build API rate limiting Node.js middleware in five steps
Step 1: Connect to Redis once
Create one client at startup and share it across requests. Opening a connection per request is a common way to exhaust connections.
import { createClient } from 'redis'; export const redis = createClient({ url: process.env.REDIS_URL }); redis.on('error', (err) => console.error('redis', err)); await redis.connect();
The error listener matters. Without it, a Redis disconnect emits an unhandled error event that can crash the process.
Step 2: Write the counter as a Lua script
The script increments the count and sets the expiry on the first hit. It then returns the count and the milliseconds left in the window. Redis runs a script as one atomic unit, so no other command lands in between.
local count = redis.call('INCR', KEYS[1]) if count == 1 then redis.call('PEXPIRE', KEYS[1], ARGV[1]) end return { count, redis.call('PTTL', KEYS[1]) }
In node-redis 4, call it with redis.eval(script, { keys, arguments }), and pass every argument as a string. In ioredis, the call is redis.eval(script, 1, key, windowMs).
const hit = (key, windowMs) => redis.eval(SCRIPT, { keys: [key], arguments: [String(windowMs)] });
Under high traffic, load the script once with SCRIPT LOAD and call EVALSHA. This avoids sending the script text on every request. The Redis documentation covers both commands in its scripting section.
Step 3: Choose the key
The key decides who shares a limit. Prefer an API key or authenticated user ID. Fall back to IP only for anonymous traffic.
const id = req.get('x-api-key') ?? req.user?.id ?? req.ip; const key = `rl:${req.baseUrl}:${id}`;
Hash the API key with SHA-256 before putting it in a Redis key, so a Redis dump does not leak credentials. Including the route prefix lets you set a tighter limit on /login than on /search.
Step 4: Return 429 with the right headers
Status 429 Too Many Requests is defined in RFC 6585. Add a Retry-After header in seconds. Well-behaved clients will back off instead of retrying in a tight loop.
const [count, ttl] = await hit(key, windowMs); res.set('RateLimit-Remaining', String(Math.max(0, limit - count))); if (count > limit) { res.set('Retry-After', String(Math.ceil(ttl / 1000))); return res.status(429).json({ error: 'rate_limited' }); } next();
The RateLimit-* header names come from an IETF draft that is not final yet. Many APIs send them anyway. Just document what yours returns.
Step 5: Decide what happens when Redis fails
Wrap steps 3 and 4 in try/catch. Fail open by calling next() for most read APIs, because a limiter outage should not become a full outage. Fail closed with a 503 for login, password reset and payment routes, where abuse costs more than downtime.
try { /* steps 3 and 4 */ } catch (err) { log.warn(err); return failOpen ? next() : res.sendStatus(503); }
Also set a short timeout so a slow Redis does not stall every request. Timeout options differ between node-redis versions. Check the docs for the version you run rather than copying a setting from a blog post.
The two mistakes that cause production bugs
1. Running INCR and EXPIRE as separate calls
If the process dies between the two calls, the key never expires. That client stays blocked forever, and the support ticket arrives days later.
A GET-then-SET check has a second flaw. Two concurrent requests can both read 99 and both pass a limit of 100. The Lua script in step 2 closes both gaps.
2. Trusting the wrong IP
Behind a load balancer, req.ip is the balancer's address unless Express trusts the proxy. Every user then shares one counter, and the whole API returns 429 at once.
The opposite mistake is app.set('trust proxy', true). That lets any client spoof X-Forwarded-For and get a fresh limit on each request. Set it to the exact number of proxy hops, usually app.set('trust proxy', 1), as the Express guide on proxies explains.
How to test it
Start with a unit test. With supertest and a limit of 5 per minute, send six requests. Assert that the last one returns 429 with a Retry-After header.
for (let i = 0; i < 5; i++) await request(app).get('/api').expect(200); const res = await request(app).get('/api').expect(429); expect(res.headers['retry-after']).toBeDefined();
Next, test concurrency, because that is where non-atomic code fails. Run two app instances against one Redis and send traffic to both with autocannon: npx autocannon -c 50 -a 500 http://localhost:3000/api. With a limit of 100, the 2xx count across both instances should be exactly 100, as long as the run ends inside one window.
Finally, stop Redis mid-test. Confirm that each route fails open or closed as you decided. Use a separate Redis database or key prefix for tests, and flush it between runs.
FAQ
Should I use express-rate-limit instead of writing my own?
Often, yes. express-rate-limit with the rate-limit-redis store gives you a tested limiter in a few lines of setup. Write your own when you need a different algorithm or full control over how each route behaves when Redis fails.
What limit should I set for my API?
Measure first. Find the 99th percentile of requests per client per minute over a normal week, and set the limit at two to three times that. Login routes need tighter limits, typically 5 to 10 attempts per 15 minutes, to slow down credential stuffing.
Does Redis Cluster work with this Lua script?
Yes, because the script touches a single key. Redis Cluster requires every key in one script to live in the same hash slot. If you later add a second key, use a hash tag such as rl:{user42} so both keys land together.



