Rate limiting a Node.js API with Redis
Put counters in Redis so every API replica shares one budget. A fixed INCR window is enough for most routes; use a sliding window when bursts at the minute boundary hurt. Never rate-limit signed payment webhooks the same way as anonymous traffic.
The first time I put a public order endpoint on the internet without a limit, a misbehaving retry loop from a client hit it a few hundred times in a minute. The process stayed up. The logs and the downstream calls did not. A rate limiter on the Node.js process alone would have helped one instance and forgotten the others. I keep the counters in Redis so every replica of the API sees the same budget.
This article is the limiter I actually ship: a Redis INCR fixed window for most routes, a sliding window when a sharp boundary at the top of the minute causes trouble, and a short list of routes that must not share the public bucket. Payment webhooks belong in that last group. How those webhooks should be verified and recorded is in Reliable payment webhooks. A deploy path for the Node.js service itself is in نشر مشروع Node.js على VPS.
I also run a hosted gateway for Syriatel Cash and Sham Cash that your site or bot can call. The Syriatel Cash API is $2 per number per month, Sham Cash is $5 per account per month, setup is same day, and you do not receive source code. The limiter below sits on your API, not inside the wallet.
What the limiter is for
A limit protects two things: your process, and any paid or scarce call behind it. A public POST /orders that creates a row and maybe talks to Telegram should not accept an unbounded stream from one IP or one API key. A route that looks up a payment should be limited per key as well, or a leaked key burns your quota and fills your logs.
It does not replace authentication, and it does not prove that a payment is valid. Matching a Syriatel Cash or Sham Cash transfer is still transaction ID plus amount. Those transfers have no memo field, so a client cannot put an order code inside the wallet transfer itself. The lookup and the confirmation rules are in Syriatel Cash API: Accept Payments on Your Site. The Sham Cash path is in Sham Cash API integration.
Do not put the provider webhook URL in the same limiter as anonymous traffic. If you return 429 to a valid signed webhook, the provider will retry, and you can fall behind on confirmations you already wanted. Verify the signature first, accept the event, and apply idempotency on the event ID and the transaction ID. Rate limiting belongs on the routes a client can hammer on purpose.
A fixed window with INCR
The fixed window is enough for most APIs I run. For each key you increment a Redis counter and set an expiry on the first increment. When the count passes the ceiling, the request is rejected with 429 and a Retry-After header.
```javascript import express from "express"; import Redis from "ioredis";
const app = express(); const redis = new Redis(process.env.REDIS_URL);
function clientKey(req) { const apiKey = req.get("x-api-key"); if (apiKey) return rl:key:${apiKey}; return rl:ip:${req.ip}; }
function rateLimit({ prefix, limit, windowMs }) { return async function (req, res, next) { const key = ${prefix}:${clientKey(req)}; try { const count = await redis.incr(key); if (count === 1) { await redis.pexpire(key, windowMs); } const ttlMs = await redis.pttl(key); res.set("X-RateLimit-Limit", String(limit)); res.set("X-RateLimit-Remaining", String(Math.max(0, limit - count))); res.set("X-RateLimit-Reset", String(Math.ceil(Date.now() / 1000) + Math.max(0, Math.ceil(ttlMs / 1000))));
if (count > limit) { res.set("Retry-After", String(Math.max(1, Math.ceil(ttlMs / 1000)))); return res.status(429).json({ error: "too_many_requests" }); } return next(); } catch (err) { console.error("rate limit redis error", err.message); return next(); } }; }
app.set("trust proxy", 1); app.use(express.json());
app.post( "/orders", rateLimit({ prefix: "orders", limit: 30, windowMs: 60_000 }), async (req, res) => { res.status(201).json({ ok: true }); } );
// Webhooks stay outside the public limiter. app.post("/webhooks/payments", async (req, res) => { res.status(200).json({ ok: true }); });
app.listen(Number(process.env.PORT || 3000), "0.0.0.0"); ```
The incr then pexpire sequence has a small race: if the process dies between the two commands, the key can live without a TTL. I close that with a Lua script in production so both run atomically:
``javascript const HIT = local n = redis.call("INCR", KEYS[1]) if n == 1 then redis.call("PEXPIRE", KEYS[1], ARGV[1]) end local ttl = redis.call("PTTL", KEYS[1]) return {n, ttl} `;
async function hit(key, windowMs) { const [count, ttlMs] = await redis.eval(HIT, 1, key, String(windowMs)); return { count: Number(count), ttlMs: Number(ttlMs) }; } ```
If Redis is down, the middleware above calls next() and lets the request through. That is a choice. I prefer a short outage without a limiter over turning every API call into a 500 because the cache node restarted. If a route is expensive enough that failing open is worse, fail that route closed and leave the health check and the webhook path alone.
trust proxy is set because I usually put Nginx in front. Without it, req.ip can be the proxy every time, and one shared bucket locks out everyone. If you do not terminate TLS on a proxy you control, do not trust X-Forwarded-For blindly.
Prefer an API key as the bucket when the client has one. IP limits still catch anonymous abuse, but a mobile network or a cafe can put many honest customers on one address.
When a sliding window is worth it
A fixed one-minute window of 30 requests allows 30 at 00:59 and 30 again at 01:00. For a public form that is usually fine. For a heavier lookup, the burst at the boundary is the problem, not the average.
A sliding window keeps a Redis sorted set of timestamps and drops entries older than the window. It costs more memory and two or three Redis commands per request. I use it on routes that call a scarce dependency, and I keep the fixed window everywhere else.
``javascript const SLIDE = redis.call("ZREMRANGEBYSCORE", KEYS[1], 0, ARGV[1]) local n = redis.call("ZCARD", KEYS[1]) if n >= tonumber(ARGV[3]) then return {n, redis.call("ZRANGE", KEYS[1], 0, 0, "WITHSCORES")[2] or ARGV[2]} end redis.call("ZADD", KEYS[1], ARGV[2], ARGV[2] .. "-" .. n) redis.call("PEXPIRE", KEYS[1], ARGV[4]) return {n + 1, 0} `;
async function slidingHit(key, limit, windowMs) { const now = Date.now(); const [count, oldest] = await redis.eval( SLIDE, 1, key, String(now - windowMs), String(now), String(limit), String(windowMs) ); return { count: Number(count), oldest: Number(oldest) }; } ```
The member name includes the count so two requests in the same millisecond do not overwrite each other. Tune limit and windowMs from real traffic after a quiet day of logs, not from a round number that only looks neat.
Limits I set in practice
Public order creation: tens of requests per minute per IP, tighter per API key if the client is a bot I issued credentials to. Payment lookup by transaction ID: tighter still, because a script guessing IDs should hit the ceiling quickly even though a guessed ID will not confirm a payment without the matching amount. Admin or kitchen status updates: limited per logged-in user, not per shared shop IP.
Write the limits down next to the route. A comment in code and a line in the runbook are enough. When a shop in Homs tells me their cashier app was rejected at lunch, I want to know which bucket fired and whether the key was the shop token or the cafe IP.
Return JSON with a stable error code, plus Retry-After. A Telegram bot or a browser form can wait and retry once. A tight loop that ignores the header is exactly what the limiter exists to stop.
Go-live checks
- Redis requires a password or a private network. The URL is in the environment, not in git.
INCRandPEXPIRErun in one script, so a crash cannot leave a counter without a TTL.- A request over the limit returns 429,
Retry-After, and theX-RateLimit-*headers. A request under the limit still sets those headers. - The payment webhook route is not behind the public limiter. Signature checks and idempotency still run.
- If Redis is unreachable, the behavior is the one you chose (fail open or fail closed) and the health endpoint still answers.
- Two API instances share the same Redis database, and a test from both together cannot exceed the limit.
Frequently asked questions
Can I rate limit in Nginx and skip Redis?
Nginx can cap requests per IP at the edge, and I often do that as a coarse ceiling. It will not see your API keys, and it will not share a fine-grained budget with workers that talk to Redis. I treat Nginx as the outer fence and Redis as the limit the application means.
Does rate limiting confirm a Syriatel Cash payment?
No. Confirmation is a lookup of the transaction ID and a comparison with the order amount. There is no memo field on the transfer to carry your order number. The limiter only stops a client from asking too often.
What status should a webhook return when the limiter is involved?
If you made the mistake of limiting that route and you return 429, expect retries. Keep the webhook off that middleware. Return 2xx after you have recorded the event or decided it will never apply, as described in Reliable payment webhooks.
Where should Redis run?
On the same VPS or a nearby private host is enough for a single shop API. Do not expose the Redis port to the public internet. The Node.js publish steps I use are in نشر مشروع Node.js على VPS.