💡 What is Rate Limiting?
Rate limiting is a technique to control how many times a function/API can be called in a given time period.
🛠️ How Throttling Helps in Rate Limiting
🔁 Throttle Function ensures that a function executes at most once every X milliseconds, even if it’s triggered many times.
✅ Real-World Examples of Throttling as Rate Limiting:
🔹 Frontend (Browser)
- Button Spam Prevention: Prevent a user from submitting a form 10 times in a second.
- Scroll Event: Load more items only once every 1 second.
- Resize Event: Avoid recalculating layout continuously during resizing.
// Button click throttling (Frontend rate limiting)
const button = document.getElementById("clickBtn");
button.addEventListener("click", throttle(() => {
console.log("API called at", new Date().toLocaleTimeString());
}, 2000));
🔹 Backend (API Layer)
In the backend, rate limiting is enforced using throttling algorithms like:
Algorithm | Description |
---|---|
Fixed Window | X requests per time window |
Sliding Window | Adjusts based on real-time usage |
Token Bucket | Tokens refill at intervals; requests consume tokens |
Leaky Bucket | Requests flow at a fixed rate (leak rate) |
Example with Express.js Middleware:
const rateLimit = require("express-rate-limit");
const limiter = rateLimit({
windowMs: 60 * 1000, // 1 minute
max: 10, // limit each IP to 10 requests per windowMs
message: "Too many requests. Please try again later.",
});
app.use("/api/", limiter);
🔁 Throttling Summary
Use Case | Throttle Type | Description |
---|---|---|
UI interactions | Frontend Throttle | Control event firing rate |
API protection | Backend Throttle | Limit client request rate |