Sliding window rate limiting in Node: 15 lines of Redis
From the work/ 16 min read
A sliding window rate limiter in 15 lines of Node and Lua, atomic in Redis, plus a Postgres version, a 429 with Retry-After and limits per route. All tested.
- Node.js
- Security
- Databases
In this article (9)
To do sliding window rate limiting in Node, store every accepted request in a Redis sorted set with its timestamp as the score. On each request, a Lua script removes what has left the window, counts what remains, and records the new request only if there is room. If there is no room, you answer 429 with Retry-After.
Below are the 15-line function (we counted), a Postgres version for apps without Redis, a server that answers 429, and a table of per-route limits. We tested the Redis code against fakeredis 2.40, a Python Redis emulator that runs Lua 5.1, and the Postgres code against PGlite (PostgreSQL 18.6 compiled to WebAssembly). Further down is what those tests prove and what they do not.
What rate limiting is and what it protects
A rate limit caps how many requests a client can make in a given time. The HTTP status for it is 429, defined in section 4 of RFC 6585 (April 2012): the user has sent too many requests in a given amount of time, which the RFC itself calls "rate limiting". MDN's 429 page describes it as asking the client to slow down.
The RFC does not define how the server identifies the user or counts requests: per resource, per server or across servers, by credentials or by cookie. You decide that, in three parts: the key (whose requests you count: an IP, an account, an API key), the limit (how many you accept) and the window (over how long).
In a store, limits protect specific routes: login, against password guessing; discount codes, against code guessing; search, against scraping; forms, against spam; and anything that calls a pay-per-use API. A rate limit authenticates no one, just as CORS does not protect your API: it only counts. And it will not stop an attack spread across thousands of IPs.
Fixed window vs. sliding window
The simplest approach is a fixed window: one counter per key per clock minute. The INCR documentation lists it as the "rate limiter" pattern: one counter per IP per second, with INCR and EXPIRE inside MULTI/EXEC. This is the version from our tests, with the time injected:
async function fixedWindow(redis, key, limit, windowMs, now = Date.now()) {
const bucket = `${key}:${Math.floor(now / windowMs)}`;
const [count] = await redis.multi().incr(bucket).pExpire(bucket, windowMs).exec();
return count <= limit;
}
bucketappends the window number to the key: every request in the same clock minute lands on the same counter, which deletes itself when it expires.multi()sendsINCRandPEXPIREtogether; the request passes if the incremented counter has not gone over the limit.
It is cheap, but it has a gap at the boundary. With a limit of 10 per minute, we sent 10 requests at second 59.9 and another 10 at second 60.1. The fixed window let all 20 through in 200 ms, because they fall in two different clock minutes. The sliding window let 10 through, because it always looks at the last 60 seconds counted back from now, not from the top of the minute.
| Algorithm | What it stores per key | Accuracy | At the minute boundary (tested) |
|---|---|---|---|
| Fixed window | One counter per window | Per clock minute | 20 of 20 passed with a limit of 10 |
| Sliding window (log) | One entry per accepted request, at most the limit | Exact over the last N seconds | 10 of 20 passed |
| Sliding window counter | Two counters, the current window and the previous one | Approximate: assumes even traffic in the previous window | Not tested |
The log costs one entry per accepted request, a handful with limits like 5 or 60, and in exchange the limit is exact. It is the one we implement.
The 15-line Redis implementation
The data structure is one sorted set per key. Each accepted request is a member: its score is the time in milliseconds and its name is a unique id. Unique matters: per the ZADD documentation, if the member already exists Redis only updates its score; it does not add it twice. If you used the timestamp as the name, two requests in the same millisecond would count as one. The same page says scores are doubles that hold integers exactly up to 2^53, so a millisecond timestamp fits without rounding.
This is the whole of limiter.mjs:
const SCRIPT = `
redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', ARGV[1] - ARGV[2])
if redis.call('ZCARD', KEYS[1]) < tonumber(ARGV[3]) then
redis.call('ZADD', KEYS[1], ARGV[1], ARGV[4])
redis.call('PEXPIRE', KEYS[1], ARGV[2])
return 0
end
local oldest = redis.call('ZRANGE', KEYS[1], 0, 0, 'WITHSCORES')
return oldest[2] + ARGV[2] - ARGV[1]`;
export async function slidingWindow(redis, key, limit, windowMs, now = Date.now()) {
const member = `${now}-${crypto.randomUUID()}`;
const args = [now, windowMs, limit, member].map(String);
const retryAfterMs = await redis.eval(SCRIPT, { keys: [key], arguments: args });
return { allowed: retryAfterMs === 0, retryAfterMs };
}
SCRIPTis Lua that Redis runs as a whole.KEYS[1]is the key;ARGV[1]is the time,ARGV[2]the window in milliseconds,ARGV[3]the limit andARGV[4]this request's id.- ZREMRANGEBYSCORE removes members scored from
-infup to now minus the window, both bounds inclusive: everything that has left the window. - ZCARD counts what is left (0 if the key does not exist). If that is under the limit,
ZADDrecords the request and PEXPIRE sets the key to expire after one window, in milliseconds. It returns 0: accepted. - With no room, ZRANGE with
0 0 WITHSCORESfetches the oldest member, since the order runs from lowest to highest score. The wait is its time plus the window minus now; per the Lua API reference, a Lua number reaches the client as an integer. - In Node,
memberjoins the time withcrypto.randomUUID(), a global in Node 22, andmap(String)is there becauseredis.eval(SCRIPT, { keys, arguments }), the signature in node-redis 6.3.1 that we tested, takes strings.nowis a parameter so tests can pin the time.
That is 15 lines, not counting the blank one: 9 for the script and 6 for the function. One of our tests reads the file and fails if the count stops being 15.
What makes the code correct is that there is no gap between counting and recording. Redis' Lua scripting documentation guarantees atomic execution: while a script runs, all other server activity is blocked, so no request can count between our ZCARD and our ZADD. The same page asks you to pass keys in KEYS, so it works the same on Redis Cluster, and explains that Redis caches each script by its SHA1: a fixed script is cached once; one generated per request keeps growing the cache.
Scroll the figure sideways to see all of it
What we tested, and against what
We do not have a Redis server installed, so we ran the code with node-redis 6.3.1 against fakeredis 2.40's TCP server on 127.0.0.1 and a random port. This is the output of node --test --test-reporter=spec redis.test.mjs, without the timing lines:
one connection: 10 allowed, 40 rejected, ZCARD 10
five connections: 10 allowed, 90 rejected
20 requests in the same ms -> ZCARD 20
non-unique member, limit 10: 20 allowed, ZCARD 1
after 15 calls, limit 5: ZCARD 5, PTTL 59994 ms
non-atomic version, limit 10, 100 requests over 5 connections: 97 allowed
10 at 59.9 s + 10 at 60.1 s, limit 10/min: fixed 20, sliding 10
- With a limit of 10, exactly 10 pass, over one connection or spread across five.
- With the timestamp alone as the name, 20 requests in the same millisecond collapse into one member and all pass. Rejected requests are not recorded, and the key expires in 60 seconds.
- The control runs the same steps as separate commands: 97 of 100 passed with a limit of 10, and 91 in another run.
Another test pins the clock: at 3 per second, the fourth request, at 300 ms, waits 700 ms. The limit of all this: fakeredis runs every command, EVAL included, under a single lock. That reproduces Redis' atomicity, but not its speed, memory or cluster behavior. Before production, run the tests against a staging Redis.
A Postgres version
If you do not run Redis, the same idea works in Postgres with a table of requests. We already used Postgres for something usually done with Redis in the job queue with SKIP LOCKED; here the trick is different: one lock per key. This is schema.sql:
CREATE TABLE rate_limit_hits (
key text NOT NULL,
at timestamptz NOT NULL
);
CREATE INDEX rate_limit_hits_key_at ON rate_limit_hits (key, at);
- Each row is an accepted request: the key and the time. No unique id is needed, because two identical rows are still two rows.
- The index on
(key, at)serves the delete and the count, which always filter by key.
And this is limiter-pg.mjs, with Postgres.js:
export async function slidingWindowPg(sql, key, limit, windowMs, now = new Date()) {
const since = new Date(now.getTime() - windowMs);
return sql.begin(async (tx) => {
await tx`SELECT pg_advisory_xact_lock(hashtext(${key}))`;
await tx`DELETE FROM rate_limit_hits WHERE key = ${key} AND at <= ${since}`;
const [{ count, oldest }] = await tx`
SELECT count(*)::int AS count, min(at) AS oldest FROM rate_limit_hits WHERE key = ${key}`;
if (count >= limit) {
return { allowed: false, retryAfterMs: oldest.getTime() + windowMs - now.getTime() };
}
await tx`INSERT INTO rate_limit_hits (key, at) VALUES (${key}, ${now})`;
return { allowed: true, retryAfterMs: 0 };
});
}
sql.beginopens a transaction on a reserved connection; if anything fails, Postgres.js issues aROLLBACK.pg_advisory_xact_locktakes an exclusive lock on the key's number and, per the advisory lock functions table, waits if someone else holds it. It is released automatically when the transaction ends.- With the lock held, it deletes old rows, counts and finds the oldest. With no room it returns the wait, as in Redis; with room it inserts and returns 0.
The lock replaces the script's atomicity. Under Read Committed, the default level, each SELECT sees what was committed before it began, so two concurrent transactions can both count 9 and both insert. With the lock, the second waits for the first to commit and sees 10. Per the advisory locks documentation, your application defines what the lock means.
About hashtext: it turns the key into the integer the lock needs, but it is internal, undocumented, and its output can change between major versions. For a lock that lives one transaction that does not matter; if two keys hash to the same number, they only wait on each other.
On PGlite 0.5.10, with five Postgres.js connections, 100 requests with a limit of 10 left 10 accepted and 10 rows; with no transaction and no lock, 64. But PGlite's socket server never overlaps two transactions, and the transaction without the lock also came out at 10. That the lock prevents double counting on a regular PostgreSQL comes from the docs, not from our test.
Two costs: every limited request is a four-statement transaction on your main database (fine for login, not for every GET on a busy API), and keys that never come back leave old rows. Schedule a periodic delete of everything older than your longest window.
Responding 429 with Retry-After
RFC 6585 says a 429 response should explain the condition, may include Retry-After, and must not be stored by a cache. The Retry-After format lives in section 10.2.3 of RFC 9110: an HTTP date or a number of seconds, a non-negative integer. That is why we round up with Math.ceil: a wait of just under 900 seconds goes out as 900, with no decimals and never as 0.
This is server.mjs, a Node server with no dependency other than node-redis:
import http from "node:http";
import { createClient } from "redis";
import { slidingWindow } from "./limiter.mjs";
const MINUTE = 60_000;
const LIMITS = {
"POST /login": { limit: 5, windowMs: 15 * MINUTE },
"POST /api/discount-code": { limit: 10, windowMs: MINUTE },
"GET /api/search": { limit: 60, windowMs: MINUTE },
};
const redis = await createClient({ url: process.env.REDIS_URL, disableOfflineQueue: true })
.on("error", (err) => console.error("redis:", err.message))
.connect();
http.createServer(async (req, res) => {
const route = `${req.method} ${new URL(req.url, "http://localhost").pathname}`;
const rule = LIMITS[route];
if (rule) {
const key = `rl:${route}:${req.socket.remoteAddress}`;
const verdict = await slidingWindow(redis, key, rule.limit, rule.windowMs).catch((err) => {
console.error("rate limiter unavailable, letting the request through:", err.message);
return { allowed: true };
});
if (!verdict.allowed) {
const seconds = Math.ceil(verdict.retryAfterMs / 1000);
res.writeHead(429, { "Content-Type": "application/json", "Retry-After": String(seconds) });
res.end(JSON.stringify({ error: "too_many_requests", retryAfterSeconds: seconds }));
return;
}
}
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: true, route }));
}).listen(Number(process.env.PORT ?? 3000));
LIMITSgives each route, method included, its limit and window; anything not listed is not limited.disableOfflineQueue: truemakes node-redis reject commands while it reconnects instead of holding them; its client configuration defaults tofalse.- The key joins the route and the socket's IP, so each route gets its own counter. If Redis fails, the
catchlets the request through and logs it. - With no room, it answers 429 with
Retry-Afterin seconds and a body that explains what happened, as the RFC asks.
This is how the sixth request to /login was answered, with curl -si -X POST against the local server and fakeredis behind it:
HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 900
Date: Wed, 11 Nov 2026 18:32:05 GMT
Connection: keep-alive
Keep-Alive: timeout=5
Transfer-Encoding: chunked
{"error":"too_many_requests","retryAfterSeconds":900}
429 Too Many Requestscarries the reason phrase Node sets by default.Retry-After: 900is 15 minutes: how long until the window's first request expires. The body repeats it for clients that do not read headers.
Scroll the figure sideways to see all of it
Do not count on the client obeying. MDN's Retry-After page warns that support on clients and servers is still inconsistent. Your server enforces the limit on every request; the header only tells the client how long it makes sense to wait.
Different limits per route
Not every route is worth the same. These are the values we would start with. They are starting points, not measurements: tune them against your logs.
| Route | Key | Limit | Window | Why |
|---|---|---|---|---|
POST /login | IP, and separately the account | 5 | 15 min | Slows down password guessing |
POST /password-reset | Account | 3 | 1 h | Every attempt sends an email |
POST /api/discount-code | IP | 10 | 1 min | Slows down code guessing |
GET /api/search | IP | 60 | 1 min | Scraping and per-query cost |
POST /contact | IP | 5 | 1 h | Spam |
POST /webhooks/shopify | None | — | — | Verify the signature and enqueue |
Login is worth counting twice, with two calls and two keys (rl:login:ip:… and rl:login:account:…): by IP, for someone trying many accounts, and by account, for someone trying one account from many IPs. Anyone can exhaust someone else's account limit, so use a short wait there, not a long lockout.
Behind a proxy or a CDN, req.socket.remoteAddress is the proxy's IP and the client's arrives in X-Forwarded-For. MDN's X-Forwarded-For page is explicit: for rate limiting, only addresses added by a trusted proxy are usable. The client writes the leftmost one, and using it lets them skip the limit.
The Shopify webhook gets no per-IP limit: Shopify calls it, not a shopper. What protects that route is verifying the webhook HMAC before doing anything; if the work is heavy, put it in a Postgres job queue and respond right away.
Scroll the figure sideways to see all of it
In the server tests, /api/search accepted 60 requests and the 61st got a 429 with Retry-After: 60, while /products, not in LIMITS, stayed at 200. With fakeredis shut down, POST /api/discount-code answered 200 and the error went to the log: that is failing open. For login you may prefer to fail closed with a 503; it is the same catch line.
Common mistakes
- Counting and recording in two commands. Other requests slip in: 97 of 100 passed with a limit of 10. Use one script, or a transaction with a lock in Postgres.
- Using the timestamp as the sorted set member. Requests in the same millisecond collapse into one. Add a unique id.
- Assuming a fixed window is exact. At the minute boundary it lets twice the limit through.
- Building the script with the key inside it. The Redis docs call it an anti-pattern: it fills the script cache and can fail on a cluster. Pass the key in
KEYS. - Trusting the leftmost
X-Forwarded-Foraddress. The client writes it. - Sending
Retry-Afterin milliseconds or with decimals. RFC 9110 asks for whole seconds. - Not deciding what happens when Redis is down. By default, node-redis holds commands while it reconnects, so the request waits. Choose fail open or fail closed, and test it.
- Letting the Postgres table grow. Schedule a periodic delete.
Frequently asked questions
Should I limit by IP or by user?
It depends on the route. Before login all you have is the IP; after it, the account or the API key identifies people better, because an office or a mobile network shares one IP across many people.
How much memory does it use in Redis?
At most as many entries per key as the limit, because the script does not record rejected requests: after 15 calls with a limit of 5, the sorted set held 5 members. Each key also expires one window after its last accepted request, thanks to PEXPIRE. We did not measure bytes: fakeredis is not the tool for that.
Does it work with several Node servers or with Redis Cluster?
Yes, as long as they all share the same Redis: the script touches a single key and receives it in KEYS, as the docs require for cluster. The time comes from each Node process via Date.now(), so a clock difference between servers shifts the window by that same amount. If you want a single clock, read the time inside the script with TIME: the Redis docs allow writes after TIME since version 5. We did not test that.
What if the client ignores Retry-After?
Nothing changes: the script keeps rejecting until a slot frees up, and since rejected requests are not recorded, hammering does not extend the wait. To penalize clients that keep hammering, add a second, longer limit.
Checklist
- Every sensitive route has its key, limit and window written down in one place.
- Counting and recording happen in one atomic step: a Lua script in Redis or a transaction with
pg_advisory_xact_lockin Postgres. - Every sorted set member carries a unique id, not just the timestamp.
- The Redis key expires with
PEXPIRE, and the Postgres table has a periodic cleanup. - The response is a 429 with
Retry-Afterin whole seconds and a body that explains it. - The IP comes from the socket or from what your trusted proxy added, never from the leftmost
X-Forwarded-Forentry. - What happens when Redis does not answer is decided and tested.
- Webhooks are not limited by IP: they are verified and enqueued.
With 15 lines and an atomic script, every sensitive route gets its cap and the client knows when to come back. If what arrives are webhooks, start by verifying the Shopify webhook HMAC and move the heavy work to a Postgres job queue. And remember that CORS does not protect your API: the server sets the limit.
Saw this on Instagram? Comment RATELIMIT on the Reel and I'll send you the guide.
Written by

Published November 11, 2026