Rate limiting
A fixed-window limiter, counted per key per binding.
Configuration
"ratelimiters": [{ "binding": "API", "limit": 100, "period": 60 }]
limit and period (in seconds) are fixed in sproutboat.jsonc.
Usage
export default {
async fetch(request, env, ctx) {
const { success } = await env.API.limit({ key: request.headers.get("cf-connecting-ip") ?? "anonymous" });
if (!success) {
return new Response("slow down", { status: 429, headers: { "retry-after": "60" } });
}
return new Response("ok");
},
} satisfies ExportedHandler<Env>;
This is the Workers Rate Limiting API: limit({ key }) resolves to { success }. await it; the call is a Promise on Workers, and awaiting is correct here too.
Sproutboat also returns resetAt with it, the time the window resets in epoch milliseconds, for an exact Retry-After. A handler that reads resetAt does not run on Workers, where the result has success only.
const { success, resetAt } = await env.API.limit({ key: "user:42" });
if (!success) {
const retryAfter = Math.ceil((resetAt - Date.now()) / 1000);
return new Response("slow down", { status: 429, headers: { "retry-after": String(retryAfter) } });
}
Method
| Method | Signature | Returns |
|---|---|---|
limit |
({ key }) |
Promise<{ success, resetAt }>. resetAt is Sproutboat-only. |