Introduction to the Limiter API
The Limiter API is designed to help developers manage and control the rate of operations performed in their web applications. This API ensures that your application remains efficient, performant, and protected from potential overloading or misuse. Below are dozens of useful API examples to guide you through its powerful features.
Rate Limiting
Rate limiting is essential to control how frequently an operation can be performed. Here’s how to implement a basic rate limiter:
const rateLimiter = new Limiter({ tokensPerInterval: 5, interval: "minute" });
async function handleRequest(req, res) {
try {
// Consume 1 token per request
await rateLimiter.removeTokens(1);
res.send("Request processed successfully.");
} catch (err) {
res.status(429).send("Too Many Requests");
}
}
Concurrency Limiting
Concurrency limiting ensures that only a certain number of operations can be performed concurrently. Here is an example of its implementation:
const concurrencyLimiter = new Limiter({ maxConcurrent: 3 });
async function handleTask(task) {
return await concurrencyLimiter.schedule(() => {
return performTask(task);
});
}
Time Window Limiting
Time window limiting allows control of the number of requests in specified time windows. Below is an example:
const timeWindowLimiter = new Limiter({ tokensPerInterval: 100, interval: "hour" });
async function trackUserActivity(userAction) {
try {
await timeWindowLimiter.removeTokens(1);
logActivity(userAction);
} catch (err) {
console.error("Limit reached for this time window");
}
}
API Usage in an Application
Here’s a sample application that utilizes the above-discussed APIs:
const express = require("express");
const Limiter = require("limiter").RateLimiter;
const app = express();
const rateLimiter = new Limiter({ tokensPerInterval: 5, interval: "minute" });
const concurrencyLimiter = new Limiter({ maxConcurrent: 3 });
const timeWindowLimiter = new Limiter({ tokensPerInterval: 100, interval: "hour" });
app.use(async (req, res, next) => {
try {
await rateLimiter.removeTokens(1);
next();
} catch {
res.status(429).send("Too Many Requests");
}
});
app.post("/task", async (req, res) => {
try {
await concurrencyLimiter.schedule(() => {
return handleTask(req.body.task);
});
res.send("Task processed successfully.");
} catch (err) {
res.status(500).send("Task could not be processed.");
}
});
app.get("/activity", async (req, res) => {
try {
await timeWindowLimiter.removeTokens(1);
res.send("Activity tracked successfully.");
} catch (err) {
res.status(429).send("Limit reached for this time window");
}
});
app.listen(3000, () => {
console.log("Server running on port 3000");
});
This comprehensive guide should help you implement and use the Limiter API to improve your application’s performance and reliability.
Hash: cc79c176b387b977d533e35726e0da5ee914180da6625f5915443ed67f5c3889