Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added rate limiter for all APIs #27

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions api/middleware/rateLimiter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Rate Limiting using Token bucket algorithm

// Maximum number of requests allowed in a given time frame
const REQUEST_LIMIT = 5;

// Time frame in milliseconds
const WINDOW_SIZE = 10000;

// Initialize with REQUEST_LIMIT number of tokens
const tokens = Array(REQUEST_LIMIT).fill(1);

var time = new Date().getTime();

export const rateLimiter = (req, res, next) => {
if (tokens.length && new Date().getTime() - time < WINDOW_SIZE) {
tokens.pop();
next();
} else {
if (new Date().getTime() - time >= WINDOW_SIZE) {
const len = tokens.length;
for (let i = 0; i < 5 - len; i++) {
tokens.push(1);
}
time = new Date().getTime();
rateLimiter(req, res, next);
} else {
res.status(429).json({
message: `You have exceeded the ${REQUEST_LIMIT} requests in ${WINDOW_SIZE} ms limit !! , ${
new Date().getTime() - time
}`,
status: 429,
});
}
}
Comment on lines +1 to +34
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can't we use some library that provides a lot more functionality and use build that ?
Basically RateLimiter class with multiple configurations like algorithm, different rate limit, and so on

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Understood the requirement. We can I guess. Let me work on it.

};
5 changes: 5 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import cors from "cors"; // Import cors package
import Routes from "./api/routes";
import startServer from "./startServer";

import { rateLimiter } from "./api/middleware/rateLimiter"; // Import rate limiter middleware

const app = new Express();

//added cors to avoid cors error
Expand All @@ -18,6 +20,9 @@ app.use(bodyParser.json());
// Support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));

// Added Rate Limiter
app.use(rateLimiter);

// Initialize Routes
Routes.init(app);

Expand Down