UsefulKey

Cloudflare KV

Cloudflare KV-backed fixed window and token bucket store.

Overview

  • Rate limit store implemented on Cloudflare KV for Workers.
  • Uses per-identifier keys with TTL for fixed windows; stores token bucket state as a string.

Usage

import { CloudflareKvRateLimitStore, usefulkey } from "betterkey";

export default {
  async fetch(req: Request, env: { RATE_LIMIT_KV: KVNamespace }) {
    const rateLimitStore = new CloudflareKvRateLimitStore(env.RATE_LIMIT_KV, {
      keyPrefix: "usefulkey:rl",
    });
    const uk = usefulkey({ adapters: { rateLimitStore } });
    // ...
    return new Response("OK");
  }
};

Client compatibility

  • Object exposing get(key), put(key, value, { expirationTtl? }), optional delete(key).

Options

OptionTypeDefaultDescription
keyPrefixstring"usefulkey:rl"Namespace prefix for counters and token buckets.

Keys

  • Fixed window: "<keyPrefix>:<namespace>:<identifier>" with expirationTtl set to window seconds
  • Token bucket: same key storing "<tokens>:<lastRefillMs>"

Limitations

  • KV does not expose TTL read; the adapter approximates reset by adding the full window on each increment.
  • Under contention, windows may skew slightly strict because TTL is reset on each write.