In this lesson, you will learn how to implement tiered API rate limiting to dynamically enforce usage quotas based on a user's subscription status.
Why Tiered Throttling?
In a professional API environment, not all users are created equal. A "Free" user might be limited to 60 requests per minute, while a "Premium" subscriber may be allowed 5,000. By integrating rate limiting as middleware, we can inspect a user's subscription tier—retrieved via your previously implemented API Key Management—and apply the appropriate constraints before the request hits your business logic.
Implementing the Logic
The core idea is to map tier identifiers to specific configuration objects. When a request arrives, the middleware identifies the user’s tier and selects the corresponding limit.
const tierLimits = {
free: { windowMs: 60000, max: 60 },
pro: { windowMs: 60000, max: 5000 }
};
const rateLimiter = (req, res, next) => {
// Assume 'req.user' was populated by your API Key Management middleware
const tier = req.user.tier || 'free';
const limit = tierLimits[tier];
// Logic to track current count in Redis (Distributed Lock Management)
const currentUsage = getUsageFromStore(req.user.id);
if (currentUsage > limit.max) {
return res.status(429).send('Rate limit exceeded for your tier.');
}
next();
};
Architectural Flow
When a request enters the pipeline, the API Key Management middleware authenticates the user. Once the user's identity is resolved, our rateLimiter middleware performs a lookup against the tierLimits dictionary.
Using Distributed Lock Management (like Redis) is critical here because it ensures that usage counts are consistent across multiple server instances. If a "Free" user exceeds their count, the middleware halts the chain, returning a 429 Too Many Requests status code. This approach keeps your code clean and separates "access control" (who they are) from "usage policy" (how much they get).
By decoupling these policies into separate middleware blocks, you maintain a flexible system where upgrading a user's subscription instantly grants them access to higher throughput without changing a single line of business logic.
Key Takeaway: API rate limiting by tier transforms your API into a scalable product by mapping subscription levels to specific, enforceable usage thresholds during the request-handling pipeline.