What this thread does
Do first: For Cloudflare Workers, use Wrangler 4.36.0 or later; for other supported serverless runtimes, install @upstash/ratelimit.
Short answer
Use the request's authenticated user ID as the limiter key. Cloudflare documents user IDs and user-plus-route keys; Upstash accepts a user identifier for individual limits. Cloudflare's binding is approximate and local to each location. Cloudflare, Upstash
What to do
For Cloudflare, add a ratelimits entry to the Worker configuration:
| Field | Value or constraint |
|---|---|
name | MY_RATE_LIMITER in the documented example |
namespace_id | "1001" in the example; a positive integer represented as a string, unique within the account |
simple | The only supported configuration type |
simple.limit | Example threshold 100 units per period in each location |
simple.period | Example 60 seconds; accepted values 10 or 60 |
Call the binding before the protected action:
const { success } = await env.MY_RATE_LIMITER.limit({ key: userId });
if (!success) return new Response("Rate limit exceeded", { status: 429 });
The key accepts a string; each call consumes 1 unit by default. Identical namespace_id values on the same account share counters for the same key within a location, including across Workers. Cloudflare configuration and API
For Upstash, run npm install @upstash/ratelimit. Import Ratelimit from @upstash/ratelimit and Redis from @upstash/redis; create the Upstash Redis instance first. Redis.fromEnv() requires UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN, configured in the deployment environment. Initialize the limiter once and call it by user ID:
const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(10, "10 s") });
const { success, pending } = await ratelimit.limit(userId);
This example allows 10 requests per 10 seconds. Check success before the protected action. For Cloudflare, the Redis adapter import is @upstash/redis/cloudflare. When analytics or multi-region synchronization is enabled in an edge runtime, pass pending to context.waitUntil(pending). Upstash setup
Limits and open questions
Cloudflare counts are eventually consistent: awaiting a check does not synchronize all instances, and requests can exceed the threshold. For one strict limit across locations, Cloudflare directs requests through the same Durable Object and persists the counter. IP or country keys can group unrelated users. Cloudflare accuracy and key guidance
Upstash's timeout defaults to 5 seconds and allows a request through if the backend exceeds that timeout. analytics defaults to false; the Redis-key prefix defaults to @upstash/ratelimit. Features, setup
Not for: Better Auth’s built-in authentication-route limiter.
Sources
- Rate Limiting (Cloudflare).
- Ratelimit getting started (Upstash).
- Ratelimit features (Upstash).
Started from a post by @Cloudflare, packaged by the editor. Original post