When I was building my backend API, I realized a big problem: anyone could spam my endpoints.
If a user repeatedly reloads a page or hits an endpoint calling an external AI service, it can crash the server or run up high API costs.
To fix this, I added Rate Limiting.
Here is why I used Redis for it and how I set it up.
The Problem with Simple In-Memory Limiters At first, I thought about saving request counts in a simple JavaScript object: This works locally, but has two big flaws: 1)Memory Leaks: The requestCounts object keeps growing in memory forever. 2)Breaks when Scaling: If you deploy multiple instances of your app behind a load balancer, each server keeps its own count.
A user can easily bypass the limit by hitting different servers.
The Solution: Centralized Redis Store Redis stores data in RAM outside our Node.js app.
Because it is centralized, all server instances share the exact same count.
How I Configured It in My Project In my app, I use two levels of protection: Global Limit: 100 requests per 15 minutes for normal routes.
Strict Limit: 5 requests per 10 minutes for heavy routes (like AI generation or OTP emails).
What I Learned 1)Stop requests early: Blocking bad traffic at the middleware layer saves database reads and server CPU cycles. 2)Redis is fast: Checking limits in Redis takes less than 1ms. 3)Remember trust proxy: If hosting on Render or behind Nginx, add app.set('trust proxy', 1) in Express so it reads the user's real IP instead of the load balancer IP. 💻 GitHub:https://github.com/nikhilsingh2764/invoice-Genrator 🚀 Live API:https://invoice-backend-drqr.onrender.com/ 📑 Postman Collection: (https://www.postman.com/technical-physicist-35686083-s-team/invoice-generator-api/collection/39798617-83cff721-5ce7-4e00-ba58-0d49017d3f39?action=share&creator=39798617)