DEV Community

Dev Cookies
Dev Cookies

Posted on

βœ… Throttling is commonly used for rate limiting – both on the frontend (UI) and backend (API)

πŸ’‘ 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));
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή 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);
Enter fullscreen mode Exit fullscreen mode

πŸ” Throttling Summary

Use Case Throttle Type Description
UI interactions Frontend Throttle Control event firing rate
API protection Backend Throttle Limit client request rate

Top comments (0)