Q1. What is rate limiting and why is it important?
Rate limiting restricts the number of requests a client can make in a given time period. It prevents brute-force attacks, DDoS attacks, and ensures fair usage of server resources. It's essential for public APIs and login endpoints.
Q2. How do you implement rate limiting in Express?
Use express-rate-limit middleware. Example: const limiter = rateLimit({ windowMs: 15*60*1000, max: 100 }); app.use('/api', limiter). This allows 100 requests per 15 minutes per IP. You can customize the message and skip certain requests.
Q3. What is the difference between rate limiting and throttling?
Rate limiting blocks requests after reaching a limit. Throttling slows down responses (like delaying) rather than blocking. Both protect servers. Throttling can be implemented with custom middleware that adds delays using setTimeout.
Q4. How do you slow down responses for security?
Add artificial delays to sensitive endpoints like login. This makes brute-force attacks slower. Example middleware: const slowDown = (req, res, next) => { setTimeout(next, 1000); }; app.post('/login', slowDown, loginHandler).
Q5. What are best practices for rate limiting?
Apply stricter limits on authentication endpoints (e.g., 5 attempts per minute). Use different limits for different user roles. Store rate limit data in Redis for distributed apps. Return appropriate headers (X-RateLimit-Limit, X-RateLimit-Remaining).
