Rate limiting with Cloudflare KV

By

Updated

Tagged: Cloudflare

Rate limit Cloudflare Workers API routes with KV fixed-window counters and expirationTtl cleanup. Soft limits that work with KV eventual consistency.

Someone can point a bot loop at your public API route and run up your LLM bill fast.

Rate limiting stops that, and on Cloudflare Workers, KV is the simplest way to build it without setting up Durable Objects, Redis, or another service.

I added this to one of my apps for its free LLM tools. Each visitor gets five roasts per day, keyed by an anon token and their IP.

Because KV is eventually consistent, two requests arriving at the exact same millisecond can both read count: 0. That makes this a good fit for abuse protection and soft limits, though you wouldn’t use it for a strict billing quota.

Fixed-window counters

Fixed-window rate limiting groups requests into time buckets, counts how many arrive in the current bucket, and rejects anything past your limit.

A window key looks like this:

rl:roast:anon_abc:1.2.3.4:293120

It joins an rl: prefix, the route name, the caller identity, and the current window number (Math.floor(now / windowSeconds)).

Once the time window rolls over, the next request automatically starts using a fresh key, and the old keys expire on their own (more on that below).

The implementation

Here’s the helper function that checks and updates the counter in KV:

async function checkRateLimit(kv, opts) {
  const window = Math.floor(Date.now() / 1000 / opts.windowSeconds)
  const kvKey = `rl:${opts.name}:${opts.key}:${window}`

  const raw = await kv.get(kvKey)
  const count = raw ? parseInt(raw, 10) || 0 : 0

  if (count >= opts.limit) {
    return { allowed: false, remaining: 0, limit: opts.limit }
  }

  await kv.put(kvKey, String(count + 1), {
    expirationTtl: Math.max(60, opts.windowSeconds),
  })

  return { allowed: true, remaining: opts.limit - count - 1, limit: opts.limit }
}

It reads the current count for the key. If the caller has already hit the limit, it returns allowed: false; otherwise it increments the counter and lets the request through.

Because that read-then-write isn’t atomic, two concurrent requests can both read 0 and write 1. You might occasionally let six requests through when the limit is five, which is acceptable for bot protection.

Caller identity

Rate limiting by IP alone penalizes everyone sharing a NAT, while relying only on a cookie lets bots get around it by rotating cookies.

Combining both into a single caller key works much better:

function rateLimitKey(anonToken, request) {
  const ip =
    request.headers.get('CF-Connecting-IP') ??
    request.headers.get('X-Forwarded-For')?.split(',')[0]?.trim() ??
    'unknown'
  return `${anonToken}:${ip}`
}

On Cloudflare, CF-Connecting-IP gives you the real client IP, so use that whenever you have it.

Automatic cleanup with expirationTtl

Every kv.put call passes an expirationTtl, which tells KV to delete the key automatically after that many seconds.

Set it to at least your window length. I use Math.max(60, windowSeconds) so even short windows get a one-minute floor, and you never need a cron job to sweep old counters.

Why eventual consistency is fine

KV reads can be stale across the globe. A write can take up to 60 seconds to become visible in other locations, so a counter might briefly undercount.

That would be a problem for a hard billing meter, where every single request has to be counted accurately. When your goal is stopping someone from hammering a free roast endpoint, letting a few extra requests slip through while writes propagate is fine as long as sustained abuse gets blocked.

Fail open on KV errors

If KV is down or your binding is misconfigured, you don’t want to block legitimate users.

Wrap the check in a try/catch and allow the request when KV throws:

async function safeRateLimit(kv, opts) {
  try {
    return await checkRateLimit(kv, opts)
  } catch (err) {
    console.error('[rate-limit] KV error, allowing request:', err)
    return { allowed: true, remaining: opts.limit, limit: opts.limit }
  }
}

Letting traffic pass during a brief KV outage is much better than returning a 500 error on every POST.

Using it in a route

You can drop the helper straight into a route handler like this:

const rate = await safeRateLimit(env.CACHE, {
  name: 'roast',
  key: rateLimitKey(anonToken, request),
  limit: 5,
  windowSeconds: 86400, // one day
})

if (!rate.allowed) {
  return new Response('Too many requests', { status: 429 })
}

Bind your KV namespace in wrangler.jsonc as CACHE (or whatever name you like), then pass env.CACHE into the helper.

When to reach for something else

If you need a precise, atomic counter or real-time limits across many Workers, reach for a Durable Object with in-memory state or an external store instead.

For stopping casual abuse on a free tool, though, KV fixed windows are cheap and get the job done.

Parse a Retry-After header

Test delay-seconds and HTTP-date Retry-After values and see the exact time the wait ends:

Retry-After ParserInteractive · runs in your browser

The reference time needs a timezone. Z means UTC. A date in the past waits 0 seconds.

Not parsed

Wait

Want me to talk about your product? You can sponsor this site.

Related posts about cloudflare: