Node.js: Handling Rate Limiting in a REST API with Redis and Express
I recently switched to I'm sure I'm missing something obvious here, but I'm relatively new to this, so bear with me... I'm building a REST API using Node.js with Express and I need to implement rate limiting to prevent abuse of my endpoints. I've decided to use Redis as the store for the rate limit counters. I installed the `express-rate-limit` and `connect-redis` packages, but I'm running into issues with the rate limit not being applied correctly. Hereβs a simplified version of my code: ```javascript const express = require('express'); const rateLimit = require('express-rate-limit'); const RedisStore = require('connect-redis')(session); const session = require('express-session'); const redis = require('redis'); const app = express(); const redisClient = redis.createClient(); const limiter = rateLimit({ store: new RedisStore({ client: redisClient }), keyGenerator: (req, res) => req.ip, windowMs: 15 * 60 * 1000, // 15 minutes max: 100 // limit each IP to 100 requests per windowMs }); app.use(limiter); app.get('/api/resource', (req, res) => { res.send('This is a rate limited resource'); }); app.listen(3000, () => { console.log('Server running on port 3000'); }); ``` When I test it, I notice that the limit seems to reset too quickly. For example, after reaching the limit of 100 requests, if I wait just a few seconds and then make a request, it's letting me through again, which I assume is not the intended behavior. I've checked the Redis store and it looks like the keys are being created, but I can't figure out why the limit is this lenient. I've also confirmed that the Redis server is running and accessible. In the `express-rate-limit` documentation, it mentions that if the `store` option is provided, it should use that for storing the rate limits, but I'm not seeing any specific examples for integrating Redis. Does anyone know how to properly configure the rate limiter with Redis in this setup, or potential reasons why the limits are not being enforced as expected? I would appreciate any insights or examples if you've faced a similar issue. For context: I'm using Javascript on Windows. Is there a better approach? My development environment is macOS. What's the best practice here? For reference, this is a production web app.