Lesson 25 / 30
Rate Limiting
Protect your API from abuse with rate limiting.
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, // 100 requests
timeWindow: '15 minutes',
cache: 10000, // Number of records to store
allowList: ['127.0.0.1'], // Don't limit localhost
});
// Or rate limit by user ID:
await fastify.register(rateLimit, {
max: 100,
timeWindow: '15 minutes',
keyGenerator: (req) => req.user?.id || req.ip, // Key by user ID if authenticated
});