Skip to main content
The rateLimit() middleware uses Cloudflare KV to implement a sliding-window counter at the edge. Because KV is globally distributed, every Cloudflare datacenter enforces the same limit against the same shared counter — making this approach well-suited to API rate limiting where consistency matters more than sub-millisecond precision.
The KV write that increments the counter runs via req.ctx.waitUntil() — it happens after the response is sent and does not block your handler. This keeps the hot path as fast as a single KV read.

Setup

First, declare a KV namespace binding in your wrangler.toml:
Then include it in your Env type so req.env.RATE_LIMIT_KV is typed correctly:

Basic usage

RateLimitOptions reference

string | (req) => KVNamespace
required
The KV namespace to use as the counter store. Pass a resolver function ((req) => req.env.RATE_LIMIT_KV) to resolve it from req.env, or pass the binding name as a string ('RATE_LIMIT_KV') and Blaze resolves it automatically.
number
required
Maximum number of requests allowed per window period. Requests beyond this limit receive a 429 Too Many Requests response.
number
required
Window size in seconds. The counter resets at the start of each window. For example, window: 60 creates per-minute buckets.
(req) => string
Function that derives the rate-limit key from the request. Defaults to req.ip (the CF-Connecting-IP header). Use this to implement per-user, per-token, or per-route-and-IP limits.
string
default:"'Too Many Requests'"
The error message returned in the 429 JSON response body.

Custom key functions

The default key is the client IP address. Override keyFn to implement per-user or per-API-key limits:

Per-route limits

Apply rateLimit() directly on individual routes to enforce different limits for different endpoints:

Response headers

Every response — whether allowed or blocked — includes rate-limit headers so clients can track their usage and implement backoff: A client hitting the limit sees:
A client within the limit sees:
Clients can use X-RateLimit-Remaining to slow down proactively before hitting the limit, and Retry-After to implement automatic retry logic on 429 responses.