पाठ 25 / 30
Rate Limiting
Rate limiting के साथ अपने API को abuse से protect करें।
Rate limit क्यों?
Rate limiting abuse को prevent करता है, DDoS से protect करता है, और clients के बीच fair resource allocation सुनिश्चित करता है।
@fastify/rate-limit उपयोग करना
Built-in protection के लिए Fastify rate-limit plugin उपयोग करें।
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
});