Rate limiting
express-rate-limit
Rate limiting is a critical security technique used to control the amount of traffic a user or IP address can send to your server within a specific timeframe. It is your primary defense against Brute Force attacks and Denial of Service (DoS) attempts.
1. The Theory: Why Rate Limit?
Theory: Without rate limiting, a single malicious actor (or a buggy script) could send thousands of requests per second to your Express API.
Resource Protection: Prevents your CPU, memory, and database from being overwhelmed by a flood of requests.
Cost Control: If you use pay-per-use services (like sending SMS for OTPs or using AI APIs), rate limiting prevents a single user from running up a massive bill.
Security: Slows down attackers trying to guess passwords
2. Implementation with express-rate-limit
The most popular tool for this is the express-rate-limit middleware.
const rateLimit = require('express-rate-limit');
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes window
max: 100, // Limit each IP to 100 requests per window
message: 'Too many requests from this IP, please try again after 15 minutes',
standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
legacyHeaders: false, // Disable the `X-RateLimit-*` headers
});
// Apply to all requests
app.use('/api/', apiLimiter);3. Granular Limiting (Best Practice)
Theory: You should apply different limits to different parts of your application based on their "cost".
Public Routes: High limit (e.g., browsing study materials).
Authentication Routes: Very strict limit (e.g., login or password reset).
Resource-Intensive Routes: Strict limit (e.g., generating a PDF or complex search).
Example for Login:
const loginLimiter = rateLimit({
windowMs: 60 * 60 * 1000, // 1 hour
max: 5, // Only 5 failed attempts per hour per IP
message: 'Too many login attempts, please try again in an hour'
});
app.post('/api/auth/login', loginLimiter, authController.login);4. Production Considerations (AWS/Infrastructure)
Theory: If we are managing your own AWS EC2 instance with Nginx, you must be careful about how the server identifies the user's IP.
Trust Proxy: If Nginx is acting as a reverse proxy, the "IP" Express sees might be the local Nginx IP, not the user's IP. You must enable
app.set('trust proxy', 1)so Express looks at theX-Forwarded-Forheader.Distributed Systems: If you eventually scale to multiple EC2 instances, the default "Memory Store" for rate limiting won't work because Server A won't know how many requests Server B handled. In that case, you should use Redis to store the request counts centrally.