If tutorials available on this website are helpful for you, please whitelist this website in your ad blocker😭 or Donate to help us ❤️ pay for the web hosting to keep the website running.
अगर आप एक backend developer हो या किसी production-grade Node.js API पर काम कर रहे हो, तो एक concept आपको ज़रूर आना चाहिए -
Rate Limiting — मतलब एक user कितनी बार एक fixed time में API call कर सकता है। ये system आपकी app को DDoS attacks, bot spam, या API abuse से protect करता है।
इस blog में हम step-by-step समझेंगे -
Rate limiter क्या होता है
Custom rate limiter क्यों बनाएं जब packages available हैं?
Code example (pure Node.js/Express)
Memory optimization options
●●●
Rate limiter एक logic होता है जो किसी client को limited number of requests allow करता है एक defined window में (e.g. 100 requests per 15 minutes).
अगर user limit cross करे, तो उन्हें error response मिलता है — mostly 429 Too Many Requests.
आप third-party packages जैसे express-rate-limit use कर सकते हो,
But अगर आप:
Granular control चाहते हो
Custom memory store use करना चाहते हो (e.g., Redis)
Interview में impress करना चाहते हो 😎
तो एक अपना custom rate limiter लिखना best option है।
सबसे simple strategy है Fixed Window -
हर user/IP के लिए एक counter maintain करते हैं।
हर request पर counter increment होता है।
एक time window के बाद counter reset होता है।
●●●
// rateLimiter.js
const rateLimitMap = new Map();
function rateLimiter(limit = 100, windowMs = 15 * 60 * 1000) {
return (req, res, next) => {
const ip = req.ip;
const currentTime = Date.now();
if (!rateLimitMap.has(ip)) {
rateLimitMap.set(ip, { count: 1, startTime: currentTime });
return next();
}
const userData = rateLimitMap.get(ip);
if (currentTime - userData.startTime < windowMs) {
if (userData.count < limit) {
userData.count++;
return next();
} else {
return res.status(429).json({
error: 'Too many requests. Please try again later.'
});
}
} else {
// Reset window
rateLimitMap.set(ip, { count: 1, startTime: currentTime });
return next();
}
};
}
module.exports = rateLimiter;🧪 Use It in Express App
// app.js
const express = require('express');
const app = express();
const rateLimiter = require('./rateLimiter');
app.use(rateLimiter(5, 60 * 1000)); // 5 requests per minute
app.get('/', (req, res) => {
res.send('Welcome! You are within the rate limit.');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});●●●
Memory shared नहीं होती across multiple servers.
Restart से data clear हो जाता है।
scalability के लिए Redis या external store use करो ।
Rate limiter हर serious backend application का part होना चाहिए — especially public APIs के लिए।
अगर आपको custom control चाहिए या आप interview में edge चाहते हो, तो custom rate limiter banana must-know skill है।
ये concept आपके data structures, algorithmic thinking, और system design का real-world use case भी है।
●●●
Loading ...