Dynamic Rate Limits
See how to create dynamic rate limits with the Rick & Morty API sample.
Creating dynamic rate limits#
This example shows how to create dynamic rate limits with the Rick And Morty API sample: https://github.com/zuplo-samples/rick-and-morty
Walkthrough#
We will make the rate-limiting policy more dynamic, based on properties of the customer. Update the metadata of your two API Key consumers to have a property customerType
. Set one to free
and another to premium
.
Now add a new module to the files section by clicking on the +
next to the Modules folder and choose new empty module.
Add the following code to your module.
import { ZuploContext, ZuploRequest } from "@zuplo/runtime";
export function rateLimit(request: ZuploRequest, context: ZuploContext) {
const user = request.user;
// premium customers get 1000 requests per mintue
if (user.data.customerType === "premium") {
return {
key: user.sub,
requestsAllowed: 1000,
timeWindowMinutes: 1,
};
}
// free customers get 5 requests per minute
if (user.data.customerType === "free") {
return {
key: user.sub,
requestsAllowed: 5,
timeWindowMinutes: 1,
};
}
// everybody else gets 30 requests per minute
return {
key: user.sub,
requestsAllowed: 30,
timeWindowMinutes: 1,
};
}
Now we'll reconfigure the rate-limit policy to wire up our custom function. Add the api-key-inbound
policy and the rate-limit-inbound
policy in the Route Designer. Make sure the api-key-inbound
policy is above the rate-limit-inbound
policy as the order matters (you need to authenticate the user before you can rate limit them).
Once you have added both policies, click on the rate-limit-inbound
policy to edit it.
Update the configuration
{
"export": "RateLimitInboundPolicy",
"module": "$import(@zuplo/runtime)",
"options": {
"rateLimitBy": "function",
"requestsAllowed": 2,
"timeWindowMinutes": 1,
"identifier": {
"export": "rateLimit",
"module": "$import(./modules/rate-limit)"
}
}
}
This identifies our rate-limit
module and the function rateLimit
that it exports.
Create a new API Key#
Create a new API Key for a free user and try to make more than 5 requests per minute.
Go to Project Settings > API Key Consumer > Add New Consumer
Add the following metadata:
{
"customerType": "free"
}
Copy the API Key and try to test the API by going to the test console:
Discover More Examples
API Linting
See how to use API linting to enforce api consistency and require Zuplo features like policies.
Backend for Frontend (BFF) Auth
Optimize UX and security in web applications with this approach.
Custom Rate Limiting
Invoke the Rate Limit policy programatically and then modify the 429 response.
Custom Modules
How to bundle custom node modules to use in your Zuplo project.