How I Protected My Express API from Spam and High AI Costs Using Redis
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…
My backend API faced a major issue: it was vulnerable to spam attacks and high costs related to external AI services. To address this, I implemented rate limiting using Redis. In-memory solutions, like a JavaScript object to track request counts, proved ineffective due to memory leaks and scaling issues. Redis offers a centralized solution, storing data in RAM outside the Node.js app, ensuring that all server instances share the same count.
I configure two levels of protection: a global limit of 100 requests per 15 minutes for regular routes, and a stricter limit of 5 requests per 10 minutes for heavy routes such as AI generation or OTP emails. To set up this rate limiting, I first establish a Redis connection in the `config/redis.js` file using the `redis` package.
Then, I create middleware in `middlewares/rateLimiter.js` utilizing the `express-rate-limit` and `rate-limit-redis` packages. The global limiter is applied to all routes with a window of 15 minutes and a limit of 100 requests, while the strict limiter is applied to heavy routes with a window of 10 minutes and a limit of 5 requests.
Finally, the rate limiters are applied to the specific routes, ensuring my Express API remains protected from spam and costly AI service usage.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.