const {result, error} = await unkey.ratelimits.limit({ duration: 600, identifier: "userId", limit: 2000, namespace: "test" })if (error) { // handle potential network or bad request error // a link to our docs will be in the `error.docs` field console.error(error.message); return;}if(!result.success){ console.log("This is blocked do some logic") return;}console.log(result);
const {result, error} = await unkey.ratelimits.limit({ duration: 600, identifier: "userId", limit: 2000, namespace: "test" })if (error) { // handle potential network or bad request error // a link to our docs will be in the `error.docs` field console.error(error.message); return;}if(!result.success){ console.log("This is blocked do some logic") return;}console.log(result);
We have a dedicated package for ratelimiting in serverless functions. It’s built with Cloudflare workers and Durable Objects to orchestrate low latency ratelimiting at the edge, without sacrificing consistency.Check out the documentation for the @unkey/ratelimit package.
Expensive requests may use up more resources. You can specify a cost to the request and
we’ll deduct this many tokens in the current window. If there are not enough tokens left,
the request is denied.Example:
You have a limit of 10 requests per second you already used 4 of them in the current
window.
Now a new request comes in with a higher cost:
Copy
Ask AI
const res = await rl.limit("identifier", { cost: 4 })
The request passes and the current limit is now at 8
The same request happens again, but would not be rejected, because it would exceed the
limit in the current window: 8 + 4 > 10
Do not wait for a response from the origin. Faster but less accurate.We observe a 97%+ accuracy when using async mode with significantly lower latency.
const {result, error} = await unkey.ratelimits.limit({ duration: 600, identifier: "userId", limit: 2000, namespace: "test" })if (error) { // handle potential network or bad request error // a link to our docs will be in the `error.docs` field console.error(error.message); return;}if(!result.success){ console.log("This is blocked do some logic") return;}console.log(result);