Lesson 27 / 32
Rate Limiting
Protect a Fastify API with @fastify/rate-limit using per-IP or per-user limits and time windows.
Why rate limit?
Rate limiting prevents abuse, protects against DDoS, and ensures fair resource allocation among clients.
Using @fastify/rate-limit
Use the Fastify rate-limit plugin for built-in protection.
import rateLimit from '@fastify/rate-limit';
await fastify.register(rateLimit, {
max: 100, // requests
timeWindow: '15 minutes',
allowList: ['127.0.0.1'], // don't limit localhost
keyGenerator: (req) => req.user?.id || req.ip, // per user if authenticated, else per IP
});