Learn how to manage request rates with practical throttling strategies for RESTful APIs.
📚� Get StartedAPI throttling is a technique to control the rate of requests between a client and server to prevent abuse and ensure fair usage. This prevents DDoS attacks and resource exhaustion.
Proper API throttling protects your infrastructure from overload while maintaining a good developer experience. It's a fundamental part of API security and scalability.
# Express.js middleware example:
app.use((req, res, next) => {
const ipAddress = req.ip;
const rate = redis.get(`api-rate:${ipAddress}`);
if (rate >= 100) {
return res.status(429).json({ error: 'Rate limit exceeded' });
}
redis.incr(`api-rate:${ipAddress}`);
return next();
});
Explore different throttling patterns and their tradeoffs in modern API design.
Easiest to implement but can lead to bursts of requests
More accurate but requires complex logging
Balances fairness and accuracy with burst tolerance
Learn how to implement throttling effectively in your applications
Track metrics like:
Here's how to implement API throttling with Redis and Express.js
redis
express
const Redis = require('ioredis');
const redis = new Redis();
app.use('/api', async (req, res, next) => {
const ip = req.ip;
const key = `rate-limit:${ip}`;
const window = 60 * 5; // 5 minute window
try {
const count = await redis.get(key);
if (count >= 100) {
return res.status(429).json({
error: 'Too Many Requests',
retry_after: Math.ceil((window - (Date.now() - lastRequestAt)) / 1000)
});
}
// Store current timestamp
await redis.multi()
.set(key, Date.now())
.expire(key, 300) // 5 minutes expiration
.exec();
next();
} catch (err) {
next(err);
}
});
Common default limits are 100-1000 requests per minute, but should be adjusted based on API sensitivity and infrastructure capacity.
Always implement minimum throttling for API keys to prevent accidental or malicious abuse of administrative endpoints.
Return HTTP 429 Too Many Requests with a Retry-After header and a JSON error message with remaining reset time.
Implement robust rate limiting in your APIs with the techniques discussed in this article.