DEV Community

Visakh Vijayan
Visakh Vijayan

Posted on

Best Practice: Rate Limiter in API

When designing an API, the important thing to keep in mind is the ethical usage of the API. If the API is provided as a third party service i.e. protected via a token it is possible that it can be misused by too frequent access.

Further, if your API is public, there is chance that bots could hit it continuously and cause high usage of server resources. To cater to all of this we need a mechanism to check the number of requests made.

express-rate-limiter is an npm package that allows us to do so. By adding this middleware we restrict IPs from accessing a/all routes to n times per minute/second.

Here is how

// rate-limiter.middleware.ts

import rateLimit from 'express-rate-limit';

export const rateLimiter = rateLimit({
    windowMs: 1 * 60 * 1000, // 1 minutes
    max: 100, // Limit each IP to 100 requests per windowMs
    standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
    legacyHeaders: false, // Disable the `X-RateLimit-*` headers
});

Enter fullscreen mode Exit fullscreen mode

This middleware basically says that each IP is restricted to make up to 100 requests every minute. More than that it throws a 429-Too Many Requests error.

// in app.ts
app.use(rateLimiter);
Enter fullscreen mode Exit fullscreen mode

For the first 100 requests across your API endpoints, it works fine. The 101st one throws a 429 error.

Once the minute is passed it reverts back and you can make 100 requests again.

This way you have prevented too many hits to your server.

Top comments (0)