# Rate Limiter

A ***Rate Limiter*** is a system that blocks a user request and only allows a certain number of requests to go through in a specified period.

## **Why Do we need it?**

* **Prevent DDOS attacks** and malicious users from overloading our site's traffic.
    
* **Preventing** these attacks helps to **reduce costs for the company**. They need fewer servers to manage their traffic load.
    
* To **stop password guessing** and **brute-force** assaults
    

## **Prerequisites**

How will you **identify** the user?

* In an Authenticated system, we can use **user ID**
    
* In an Open API, it's common to use the **IP address**.
    

## Rate Limiting Algorithms

There are multiple algorithms available for rate limiting. Choosing one depends on what you're optimizing for—**accuracy**, **memory**, **burst** **handling**, etc.

Let’s take a deeper look into one of the simplest and most accurate: the **Sliding Window Log**.

## **Sliding Window Log**

---

Sliding Window Log is a **precise** rate limiting **algorithm** that **tracks** each individual **request’s timestamp** and checks if a user has exceeded the **allowed number of requests within a sliding time window** (e.g., last 15 minutes).

### **Let's Imagine**

* Imagine a guard at a gate who keeps a notebook with the timestamps of when people entered.
    

> The **Rule** is Only 100 people are allowed to enter within the 15 minutes.

Each time some one arrived , the **guards**

* Check the notebooks and **remove** all the **entries** older than 15 minutes
    
* **Count** the **remaining** entries
    
* If **less than 100**, let the person in and record the current time.
    
* If greater than 100 then reject the person
    

## How It Works in Code:

---

```javascript
// In-memory store
const ipStore = {};

// Middleware
app.use((req, res, next) => {
  const ip = req.ip;
  const now = Date.now();

  if (!ipStore[ip]) {
    ipStore[ip] = [];
  }

  // Remove timestamps older than 15 minutes
  ipStore[ip] = ipStore[ip].filter(timestamp => now - timestamp < 15 * 60 * 1000);

  if (ipStore[ip].length >= 100) {
    return res.status(429).json({ message: "Too many requests. Please try again later." });
  }

  // Add current request timestamp
  ipStore[ip].push(now);
  next();
});
```

## Code Explanation

---

### **Create an in-memory store**

* A JavaScript object (**ipStore**) is used to keep track of request timestamps for each IP address.
    

### **Capture user IP and current time**

* On each request, we get the user's IP (**req.ip**) and the current timestamp
    

### **Initialise or clean request log**

* If it's the user's first request, we initialise an empty array.
    
* We then filter out timestamps older than 15 minutes from their log.
    

### **Check request count**

* If the user has already made 100 requests in the last 15 minutes, respond with a **429 Too Many Requests error**.
    

### **Allow and log the request**

* If under the limit, we store the current timestamp and let the request proceed using **next()**.
    

---

## **Advantages**

* Very accurate
    
* Always enforces **X requests per sliding window** exactly.
    

## **Disadvantages**

* Memory usage increases with traffic since every request is logged individually.
    
* Needs cleanup or optimization in high-load systems.
    

## Reference Links

* [Github Repo](https://github.com/kawaljain/rate-limiter)
    
* [MDN Web Docs – HTTP 429 Too Many Requests](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429)
    
* [Express.js Middleware Docs](https://expressjs.com/en/guide/using-middleware.html)
    

## Architecture Diagram

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1747572562250/8c21901e-64e0-4590-b64c-bbbc51282176.png align="center")

## Conclusion

We explored how a simple yet accurate rate limiter works using the Sliding Window Log algorithm. While it’s perfect for small apps and demos, it may need optimizations like Redis or token bucket for high-traffic production systems.

I hope you enjoyed this..! Feel free to share your thoughts, questions, or ideas for future topics in the comments.

> ***Thanks for reading***
> 
> ***Happy coding!***
> 
> ***If you enjoyed the article and would like to show your support, be sure to:***
> 
> ***Follow me On*** [***Medium***](https://kawaljain.medium.com/)
> 
> ***Follow me On*** [***Hashnode***](https://blog.kawaljain.com/)
> 
> ***Checkout more*** [***Portfolio***](http://kawaljain.com/)
