Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 36 ยท Storage: R2, KV and D1

Workers KV: Key-Value Storage at the Edge

Use Workers KV from a Worker: create a namespace, read and write values with get, put, list and delete, set expirations and metadata, tune cacheTtl and avoid common KV mistakes.

Workers KV is the simplest Cloudflare storage product: a global dictionary of string keys and values. You put a value under a key, and Workers anywhere can read it back quickly. It is designed for data that is read often and changed rarely: redirect maps, feature flags, translations, cached API responses, per-site configuration.

KV is not available on this site, so the Worker code is read-only. The runnable parts model KV's behavior (including its limits) in plain JavaScript.

Create a namespace and a binding

A namespace is one KV database. Create it and bind it to your Worker:

Terminal
npx wrangler kv namespace create REDIRECTS
# prints a block to paste into wrangler.jsonc, with the namespace id
JSONC
{
  "kv_namespaces": [{ "binding": "REDIRECTS", "id": "<namespace id>" }]
}

Inside the Worker the namespace is env.REDIRECTS. You can also work from the command line:

Terminal
npx wrangler kv key put --binding=REDIRECTS "/old-page" "https://example.com/new-page"
npx wrangler kv key get --binding=REDIRECTS "/old-page"
npx wrangler kv key list --binding=REDIRECTS

(Add --local while developing so you touch the local emulated copy, not production.)

The API

JavaScript
export default {
  async fetch(request, env) {
    const path = new URL(request.url).pathname;

    // read a string (null if the key does not exist)
    const target = await env.REDIRECTS.get(path);
    if (target) return Response.redirect(target, 301);

    // other read types
    const cfg  = await env.REDIRECTS.get("config", { type: "json" });
    const raw  = await env.REDIRECTS.get("logo", { type: "arrayBuffer" });

    // write
    await env.REDIRECTS.put("visited", "yes");

    // write with expiry and metadata
    await env.REDIRECTS.put("session:abc", JSON.stringify({ user: 7 }), {
      expirationTtl: 3600,                    // seconds from now
      metadata: { createdBy: "login" },
    });

    // delete
    await env.REDIRECTS.delete("old-key");

    // list keys by prefix (paged: up to 1000 per call)
    const page = await env.REDIRECTS.list({ prefix: "session:", limit: 100 });
    // page.keys: [{ name, expiration?, metadata? }], page.list_complete, page.cursor

    return new Response("not found", { status: 404 });
  },
};

Useful details:

  • get returns null for a missing key, not an error.
  • Values can be strings, JSON, ArrayBuffer or streams. The maximum value size is large (tens of MiB), keys are limited to a few hundred bytes. Check the current limits page.
  • expirationTtl (seconds) or expiration (Unix timestamp) makes keys delete themselves. The minimum TTL is 60 seconds.
  • metadata is a small JSON object (up to 1 KB) returned by list without reading values, handy for filtering.
  • getWithMetadata(key) returns the value and its metadata together.

Eventual consistency, concretely

KV prioritizes read speed. A value is stored centrally and cached in each data center after it has been read there. Two consequences:

  1. A write is visible immediately in the location that made it and after propagation elsewhere, typically within a minute but with no guarantee.
  2. A read may return a cached value for up to cacheTtl seconds (default 60, minimum 60) after a change.

You can raise cacheTtl for rarely-changing data to cut latency further:

JavaScript
const settings = await env.SETTINGS.get("site", { type: "json", cacheTtl: 3600 });

Also, writes to the same key are rate-limited (about one per second), so KV cannot be a hot counter, a lock or a queue. Use Durable Objects for those jobs.

A KV stand-in

This stand-in implements get, put with expirationTtl, delete and list with a prefix, so you can try the usual patterns and see TTL expiry.

JS A KV-like namespace

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Pattern: a redirect table

The most common KV use is a Worker that looks up a path and redirects. It keeps the data outside the code, so editors can change a redirect without a deploy.

JS Redirect Worker over a KV stand-in

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Common mistakes

  • Storing a counter or lock. There is no atomic increment, and same-key writes are rate-limited.
  • Expecting instant global updates. Design for a short stale window or add a version number in the key.
  • One huge JSON blob for everything. Every read pulls the entire value. Split into keys such as product:123.
  • Forgetting null. Always handle a missing key.
  • Using KV as the main database. Keep source-of-truth data in D1, and treat KV as a fast copy.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does env.NAMESPACE.get('missing') return when the key does not exist?

    get resolves to null for absent keys, so code should check for null.
  2. 2. What is the minimum expirationTtl for a KV key?

    KV requires at least 60 seconds for expirationTtl (and the default cache time is 60 seconds as well).
  3. 3. Why is KV a bad fit for a page-view counter?

    Concurrent read-modify-write cycles would lose updates, and KV propagation is delayed. Use a Durable Object or D1.
  4. 4. How can you read key names and their small metadata without fetching every value?

    list() returns names, expirations and metadata, which lets you filter without loading values.

Summary

  • A KV namespace is a global key-value store bound to a Worker as env.NAME; use get, put, delete, list and getWithMetadata.
  • Values can expire (expirationTtl, minimum 60 s) and carry small metadata.
  • Reads are fast but eventually consistent; cacheTtl trades freshness for speed.
  • Good for redirects, flags, config and cached results; bad for counters, locks and relational data.

Next: R2: Object Storage Without Egress Fees