- Prevents too many requests from overwhelming system.
- Only allow X requests per user per time window.
const requests = {};
function rateLimit(userId) {
const now = Date.now();
const window = 60000; // 1 minute
const limit = 5;
if (!requests[userId]) requests[userId] = [];
// keep only recent requests
requests[userId] = requests[userId].filter(t => now - t < window);
if (**requests[userId].length >= limit**) {
throw new Error("Too many requests");
}
requests[userId].push(now);
}
3. Semaphore (rate limiting / concurrency control)