Q19: How do you implement Rate Limiting in Express applications?

Difficulty:MediumTopic:Security

Rate limiting protects APIs from Denial of Service (DoS) attacks and brute-force credential attempts. It is commonly implemented using express-rate-limit backed by Redis.

Configuring Rate Limiter Middleware
const rateLimit = require('express-rate-limit');

const authLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minute window
  max: 5, // Limit each IP to 5 requests per window
  message: { error: 'Too many login attempts. Please try again later.' },
  standardHeaders: true, // Return standard X-RateLimit-* headers
});

app.use('/api/v1/auth/login', authLimiter);

Rate limiting blocks brute-forcing by returning HTTP 429 Too Many Requests when limits are exceeded.

Key Takeaways
  • Apply restrictive rate limits on sensitive endpoints like auth and payment processing.

  • In multi-node cluster deployments, use a centralized Redis store backing the rate limit counter.