One runaway client script can send thousands of requests to your API in seconds, and a fixed-window limiter still lets a burst through at the edge of each window. A Redis sliding window rate limiter counts requests over the last N seconds from the moment each one arrives, so bursts are capped. This tutorial builds one as Express middleware in Node.js with Redis sorted sets, then makes it atomic with a Lua script.
Quick answer: Keep one Redis sorted set per client, with each request’s timestamp as the score. On every request, remove entries older than the window, count what is left, and add the new request only if the count is under the limit; otherwise return 429. Run those steps in one Lua script so parallel requests cannot slip past the limit.
- Start Redis and install
express,redisanddotenv. - Key a sorted set by client, for example
rate_limit:<ip>. - Run
ZREMRANGEBYSCORE,ZCARD,ZADDandEXPIREfor each request. - Return 429 with a
Retry-Afterheader when the count reaches the limit. - Move the steps into a Lua script and test with a curl loop.
In this guide
- Before You Start
- What You Will Build
- Fixed Window vs Sliding Window Rate Limiting
- Step 1: Start Redis and Set Up the Project
- How the Sliding Window Algorithm Works in Redis
- Step 2: Write the Express Middleware with node-redis
- Step 3: Set Up the Express Server
- Test It: Trigger the Limit with a curl Loop
- Step 4: Make the Check Atomic with a Lua Script
- Production Gotchas and Edge Cases
- If It Still Doesn’t Work
- Frequently Asked Questions
- Next Steps

Before You Start
- Node.js 18 or newer (a current LTS release is best).
- Docker to run Redis locally, or any Redis server you can reach.
- A bash or zsh terminal for the test loop. The tutorial takes about 25 minutes.
- Your real limit, such as 100 requests per minute per client. The demo uses 5 per 10 seconds so you can see it trigger.
What You Will Build
.env– the port and the Redis URL.rateLimiter.js– the middleware, first with a Redis transaction and then with a Lua script.server.js– a small Express app with one protected route.
Fixed Window vs Sliding Window Rate Limiting
Most basic rate limiters use a fixed window. Say the limit is 100 requests per minute: the counter resets at exactly 12:00:00, then 12:01:00, and so on. That leaves a gap anyone can use.
A client can send 100 requests at 12:00:59 and another 100 at 12:01:01. The limiter sees two valid windows, but your server just took 200 requests in two seconds. This is the boundary burst problem.
A sliding window limiter looks back from the moment each request arrives. With a 60-second window, it counts only the requests made in the last 60 seconds, regardless of where the clock’s minutes start.
Redis sorted sets (ZSETs) make this efficient. Every member of a sorted set has a numeric score, and Redis can delete or count members by score range in one command.
Step 1: Start Redis and Set Up the Project
Run this in your terminal to start a local Redis container:
docker run --name redis-limiter -p 127.0.0.1:6379:6379 -d redisThen create the project and install the packages:
mkdir redis-rate-limiter
cd redis-rate-limiter
npm init -y
npm install express redis dotenvCreate a .env file in the project folder to store the connection details:
PORT=3000
REDIS_URL=redis://localhost:6379How the Sliding Window Algorithm Works in Redis
Each client (an IP address here, or an API key) gets its own sorted set in Redis. Each request is stored as one member: the score is the Unix timestamp in milliseconds, and the value is the timestamp plus a random suffix, so two requests in the same millisecond do not collapse into one entry.
For every new request, the limiter runs four steps:
- Remove every member older than the current time minus the window size, with ZREMRANGEBYSCORE.
- Count the members left, with ZCARD.
- If the count is under the limit, add the current request with ZADD.
- Set an expiry on the whole key with EXPIRE, so keys of idle clients do not stay in memory forever.
If the count is already at the limit, the request is rejected with HTTP 429 Too Many Requests.
Step 2: Write the Express Middleware with node-redis
Create a file named rateLimiter.js. It uses the official node-redis client:
const redis = require('redis');
const { randomUUID } = require('crypto');
const client = redis.createClient({
url: process.env.REDIS_URL || 'redis://localhost:6379'
});
client.on('error', (err) => console.error('Redis Client Error', err));
(async () => {
await client.connect();
})();
const rateLimiter = (options) => {
const { windowMs, maxLimit } = options;
return async (req, res, next) => {
const ip = req.ip;
const key = `rate_limit:${ip}`;
const now = Date.now();
const clearBefore = now - windowMs;
try {
// Start a Redis transaction
const [removed, count] = await client
.multi()
.zRemRangeByScore(key, 0, clearBefore)
.zCard(key)
.exec();
if (count < maxLimit) {
await client
.multi()
.zAdd(key, { score: now, value: `${now}-${randomUUID()}` })
.expire(key, Math.ceil(windowMs / 1000))
.exec();
res.setHeader('X-RateLimit-Limit', maxLimit);
res.setHeader('X-RateLimit-Remaining', maxLimit - count - 1);
return next();
} else {
res.setHeader('X-RateLimit-Limit', maxLimit);
res.setHeader('X-RateLimit-Remaining', 0);
res.setHeader('Retry-After', Math.ceil(windowMs / 1000));
return res.status(429).json({ error: 'Too many requests, please try again later.' });
}
} catch (err) {
console.error('Rate limiter error:', err);
// Fail open in production so rate limiter issues don't crash your app
return next();
}
};
};
module.exports = rateLimiter;The cleanup and count run inside a transaction with .multi(), so they execute back to back without other commands in between. The middleware also sets X-RateLimit-Limit and X-RateLimit-Remaining headers so clients can see how many requests they have left.
The limiter keys on req.ip only. The X-Forwarded-For header is set by the client, so if you read it directly anyone can dodge the limit by changing it. If your app sits behind a proxy or load balancer, configure Express’s trust proxy setting so req.ip is the real client address.
Step 3: Set Up the Express Server
Create a server.js file that applies the middleware to every route. The limit is 5 requests per 10 seconds to make testing easy:
require('dotenv').config();
const express = require('express');
const rateLimiter = require('./rateLimiter');
const app = express();
const PORT = process.env.PORT || 3000;
// Apply the rate limiter: 5 requests max per 10 seconds
const limiter = rateLimiter({ windowMs: 10000, maxLimit: 5 });
app.use(limiter);
app.get('/api/resource', (req, res) => {
res.json({
message: 'Success! You accessed the protected resource.'
});
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});Start the server from your project folder:
node server.jsYou should see Server running on port 3000.
Test It: Trigger the Limit with a curl Loop
Open a second terminal and send 7 requests half a second apart:
for i in {1..7}; do
curl -i http://localhost:3000/api/resource
echo ""
sleep 0.5
doneThe first five responses are HTTP/1.1 200 OK, with X-RateLimit-Remaining counting down from 4 to 0. The sixth and seventh are HTTP/1.1 429 Too Many Requests with Retry-After: 10 and the JSON error message.
Wait 10 seconds and run the loop again: you get five 200s and two 429s again, because the earlier requests have aged out of the window. If you run it after only a few seconds, requests are rejected until the oldest timestamp turns 10 seconds old; after that, one slot frees up each time an earlier request leaves the window. That gradual recovery is the difference from a fixed window, where capacity comes back all at once.
To see the stored data, list the keys with docker exec redis-limiter redis-cli --scan --pattern 'rate_limit:*'. You will see one key per client address.
Step 4: Make the Check Atomic with a Lua Script
The first version makes two round trips to Redis: one transaction to clean and count, and a second to add the new timestamp if the limit was not reached.
Under heavy load that split creates a race condition. If two requests from the same client reach two server instances at the same moment, both can read a count below the limit before either has written its timestamp, and the client gets past the limit. It is the same check-then-act problem a Redis distributed lock in Node.js solves, but here a script is simpler.
Redis runs a Lua script as a single operation; no other client can change the data while it runs. Replace the contents of rateLimiter.js with this version. server.js stays the same, because the exported function takes the same options:
const redis = require('redis');
const { randomUUID } = require('crypto');
const client = redis.createClient({
url: process.env.REDIS_URL || 'redis://localhost:6379'
});
client.on('error', (err) => console.error('Redis Client Error', err));
(async () => {
await client.connect();
})();
// Define the Lua script for atomic sliding window rate limiting
const slidingWindowScript = `
local key = KEYS[1]
local now = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local limit = tonumber(ARGV[3])
local member = ARGV[4]
local clearBefore = now - window
redis.call('zremrangebyscore', key, 0, clearBefore)
local currentRequests = redis.call('zcard', key)
if currentRequests < limit then
redis.call('zadd', key, now, member)
redis.call('expire', key, math.ceil(window / 1000))
return {1, limit - currentRequests - 1}
end
return {0, 0}
`;
const rateLimiterLua = (options) => {
const { windowMs, maxLimit } = options;
return async (req, res, next) => {
const ip = req.ip;
const key = `rate_limit:${ip}`;
const now = Date.now();
try {
// Execute the Lua script atomically inside Redis
const result = await client.eval(slidingWindowScript, {
keys: [key],
arguments: [now.toString(), windowMs.toString(), maxLimit.toString(), `${now}-${randomUUID()}`]
});
const [allowed, remaining] = result;
res.setHeader('X-RateLimit-Limit', maxLimit);
res.setHeader('X-RateLimit-Remaining', remaining);
if (allowed === 1) {
return next();
} else {
res.setHeader('Retry-After', Math.ceil(windowMs / 1000));
return res.status(429).json({ error: 'Too many requests, please try again later.' });
}
} catch (err) {
console.error('Lua rate limiter error:', err);
return next();
}
};
};
module.exports = rateLimiterLua;The whole check-and-add now happens in one network round trip and cannot be interrupted. Restart the server and run the curl loop again; you should get the same five 200s and two 429s.
This limiter protects your own API from incoming traffic. For the opposite problem, staying under another service’s limit when you call it, see how to handle external API rate limits with BullMQ.
Production Gotchas and Edge Cases
Memory use of sorted sets
Sorted sets use more memory than a simple counter, because every request adds a member. With many active clients making many requests per window, Redis memory grows quickly.
Always set a TTL on each key with the EXPIRE command, as the code does. Also configure an eviction policy such as volatile-lru. When Redis reaches its maxmemory limit, it then evicts the least recently used keys that have a TTL (which includes every rate-limiting key) instead of rejecting writes.
Clock drift across servers
The algorithm uses Date.now() from each Node.js server, so differences between server clocks make limiting inconsistent. If server A’s clock is 200 milliseconds ahead of server B’s, requests spread across both can be wrongly blocked or allowed.
Keep server clocks in sync with NTP (Network Time Protocol). Alternatively, read the time inside the Lua script with the Redis TIME command instead of passing the client-side timestamp.
If It Still Doesn’t Work
ECONNREFUSED 127.0.0.1:6379: Redis is not running. Start it withdocker start redis-limiter. If the error mentions::1, setREDIS_URL=redis://127.0.0.1:6379.- No request ever gets a 429: check the server log for
Rate limiter error. The middleware fails open, so any Redis error lets every request through. - All your users hit the limit together in production: behind a proxy,
req.ipis the proxy’s address. Set Express’strust proxysetting to match your proxy setup. - The loop sends one request to a URL with
{1..7}in it: your shell does not expand braces. Run the loop in bash or zsh.
Frequently Asked Questions
What happens if the Redis server goes down?
Requests pass through without a limit. The middleware catches Redis errors and calls next(), which is called failing open: a broken limiter does not lock out every legitimate user. If you need strict protection, fail closed instead and return 503 Service Unavailable from the catch block.
Should I rate limit static assets?
No, apply the limiter to dynamic API routes only. Running it on images, CSS and JavaScript files spends Redis work on requests that are cheap to serve and often cached. Focus it on sensitive endpoints such as login, signup, password reset and checkout.
How does a sliding window compare to a token bucket?
A sliding window log is more exact but uses more memory. It stores one entry per request, while a token bucket stores only a token balance and a last-updated time in a single Redis hash. The token bucket allows short bursts by design; the sliding window caps every window strictly.
Next Steps
You now have an atomic Redis sliding window rate limiter for Express. Set the window and limit to your real numbers, apply stricter limits to sensitive routes, and decide whether each route should fail open or closed. Login and verification-code endpoints are a good first target; the guide to building an OTP verification system with Redis and Node.js shows where this limiter fits.

