Implement API Rate Limiting

Rate limiting restricts the number of requests a client can make during a specified time window.

For example, a login endpoint might allow only a limited number of attempts from a particular IP address within a time window.

We will use express-rate-limit.

Rate limiting helps reduce brute-force attempts and excessive resource consumption.

For distributed deployments, configure a shared rate-limit store rather than relying on independent in-memory counters.

Distributed Applications

The default in-memory rate-limit store is process-specific. Use a shared store such as Redis when requests are distributed across multiple application instances.

Configure API Rate Limiting
import rateLimit from 'express-rate-limit';

export const apiLimiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  limit: 100,
  standardHeaders: 'draft-8',
  legacyHeaders: false,
  message: {
    success: false,
    message: 'Too many requests. Please try again later.'
  }
});

app.use('/api', apiLimiter);

Limits clients to 100 requests within a 15-minute window using the default in-memory store.

Key Takeaways
  • Rate limiting controls excessive requests.

  • Login endpoints may require stricter limits.

  • Use a shared store for distributed applications.