ENF News Bot
Automated News Bot
- Joined
- Apr 15, 2022
- Messages
- 4,195
Requests can require different amounts of work. A product lookup might be cheap, while a search runs an expensive database query. Use weighted requests to make expensive operations consume more of the same rate limit.
The Rate Limiting binding now accepts an optional
For example, assign one unit to a product lookup and 10 units to an expensive search. Both operations consume the same user's allowance. The following handler takes a verified user ID from your application's authentication flow:
src/index.jsjs
src/index.tsts
The
For more details, refer to Weighted requests.
Continue reading...
The Rate Limiting binding now accepts an optional
delta in limit(). Pass delta to choose how many units a call consumes.For example, assign one unit to a product lookup and 10 units to an expensive search. Both operations consume the same user's allowance. The following handler takes a verified user ID from your application's authentication flow:
src/index.jsjs
Code:
export async function handleAuthenticatedRequest(request, env, userId) {
const { pathname } = new URL(request.url);
// Assign searches a weight of 10 and other requests a weight of 1.
const delta = pathname === "/search" ? 10 : 1;
const { success } = await env.MY_RATE_LIMITER.limit({
key: userId,
delta,
});
if (!success) {
return new Response("Rate limit exceeded", { status: 429 });
}
return new Response("Success!");
}
Code:
export async function handleAuthenticatedRequest(
request: Request,
env: Env,
userId: string,
): Promise<Response> {
const { pathname } = new URL(request.url);
// Assign searches a weight of 10 and other requests a weight of 1.
const delta = pathname === "/search" ? 10 : 1;
const { success } = await env.MY_RATE_LIMITER.limit({
key: userId,
delta,
});
if (!success) {
return new Response("Rate limit exceeded", { status: 429 });
}
return new Response("Success!");
}
The
delta defaults to 1. To use delta in local development, use Wrangler 4.157.0 ↗︎ or later. For TypeScript support, use @cloudflare/workers-types version 5.20261106.1 or later.For more details, refer to Weighted requests.
Continue reading...