Back to Cloudflare

Use Workers KV for Read-Heavy Distributed Data

November 5, 2026 Wasil Zafar 31 min read

Model consistency, expiration, and invalidation deliberately

Table of Contents

  1. Read-Heavy Data and a Distributed Cache
  2. Writes and Visibility Across Locations
  3. Expiration, Negative Lookups, and Hot Keys
  4. Why Locks and Critical Counters Need Another Design
  5. Design a Versioned Configuration Read Model
  6. Test Stale-Value Handling Without Claiming Global Synchrony

Read-Heavy Data and a Distributed Cache

Northwind Outfitters runs one storefront for forty countries. Every page render needs the same small document: the holiday banner, the free-shipping threshold, four feature flags, and the current returns-policy version. The document changes on Tuesday and Friday afternoons. The site serves tens of millions of page views a day, and every one of them reads that document.

That ratio — millions of reads for a handful of writes — is the shape Workers KV is built for. KV keeps its authoritative copy in a small number of central data centers and caches values at Cloudflare's edge locations after they are read. The first read in a location may travel to a regional tier and then to the central store; later reads come from cache, typically within about 10 ms for a hot key, according to Cloudflare's storage guidance.

A handful of terms make the rest of this article precise:

  • A read model is a copy shaped for reading: precomputed, denormalized, and rebuildable. The source of truth is the system allowed to decide what is current; it owns the invariant and the audit trail.
  • A namespace is an isolated key space bound to a Worker. A key is an opaque string up to 512 bytes; a value is up to 25 MiB; metadata is a JSON object of up to 1,024 bytes that can be read without fetching the value.
  • A TTL deletes a key. KV has two clocks — expirationTtl on write, from 60 seconds, and cacheTtl on read, from 30 seconds — and confusing them is the most common KV design error. The expiry table below separates them.
  • Eventual consistency means replicas converge without promising when. A negative lookup is a cached answer that a key does not exist. A hot key is one key taking a disproportionate share of reads or writes.

The analogy is a café chain's laminated allergen board. Head office prints the new board and sends it to the central depot. Each café keeps serving its current laminate until a replacement arrives. A café that asked the depot and was told "there is no board for this item" remembers that answer too, so a newly printed board can still be invisible there for a while. The laminate is the cached read; the depot is the central store; the printed original is the source of truth you must not lose.

Figure 1 shows the two paths and where the trust boundaries sit. The publisher is a privileged writer; readers only ever cross into a cache.

Read-Heavy Data and a Distributed Cache
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    subgraph PUBLISH["Publisher boundary: one writer per key"]
        P["CI job or Durable Object"]
    end
    subgraph CENTRAL["Central KV store"]
        S[("Authoritative key-value copy")]
    end
    subgraph REGION["Regional cache tier"]
        R["Regional cache"]
    end
    subgraph EDGE["Edge location: Sydney"]
        W["Worker isolate"] --> H{"Local cache hit?"}
        H -->|"yes"| V["Serve cached value"]
    end
    H -->|"no"| R
    R -->|"hit"| V
    R -->|"miss"| S
    S -->|"fill cache"| V
    P -->|"put(key, value)"| S
    S -. "no push to every location" .-> H
    V --> O["HTML response"]
    classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
    classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
    classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
    classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
    classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
    class P,R,W secondary;
    class H,V,O ok;

Fitness follows from five signals. If any row lands in the right-hand column, KV is the wrong store for that data.

SignalFits KVDoes not fit KV
Read/write ratioReads vastly outnumber writesEvery request may write
Access shapeA request needs a whole document by keyA request needs a query or a join
Rebuild pathThe value can be rebuilt from a system of recordThe value is the only copy
StalenessA minute of staleness is acceptableThe answer must be exact at the moment of the write
InvariantsNo invariant spans two readersTwo readers must see the same value at once

Configuration, feature flags, redirect maps, allow-lists, session blobs, and versioned fragments all qualify. Balances, inventory, quotas, seat counts, unique-email checks, locks, and rate-limit counters need a single serialization point, which is the subject of the fourth section.

Figure 2 draws the same system as layers, including the part most diagrams omit: the write path stops at the central store. Everything to the right of it is populated by reads, on the readers' schedule.

Where a KV write stops and where a read begins A source of truth feeds a single publisher, which writes a versioned document to the central KV store. Regional and edge caches fill only when readers request the key. The diagram marks the publisher boundary, the central store, the regional tier, and two edge locations, with the visibility budget for stale reads. A write reaches the centre. A read fills the edge. Publisher boundary D1 or Durable Object system of record Publisher, one writer renders document v42 authenticated and audited derive Central KV store durable authoritative copy put() resolves here no cache invalidation sent to other locations Regional tier shared cache layer filled on demand closer than central still not the edge London edge cache hot reads stay here v42 after refresh Sydney edge cache may still serve v41 until its entry expires put replicate read read Read budget Hot: local cache, about 10 ms Cold: regional, then central First read in a location pays Visibility budget Same location: usually immediate Elsewhere: up to 60 s, or the cacheTtl you requested if longer Boundary rule KV is a read model It is not the system of record Keep a rebuild path and a backup

Writes and Visibility Across Locations

A put() resolves after the value is stored centrally. It does not wait for London, Sydney, or São Paulo to know. Cloudflare documents three consequences that matter more than any benchmark: a change is usually immediately visible at the location where it was made, but that is not guaranteed; other locations may take up to 60 seconds or more; and a location that recently read the old value, or recently cached a miss, is the slowest to notice the change.

60 seconds is a ceiling, not a schedule

The figure is the documented default window, not a global synchronization event. A larger cacheTtl on the read extends that window; a smaller one does not buy a tighter documented guarantee than 60 seconds, it only shortens how long that result stays in the local cache. Expiration is the hard stop: once it is reached, the key is deleted even when the read TTL is longer.

A worked comparison makes the window concrete. At 12:00:00 the London publisher writes v42 of the config document, changing the banner to "Holiday cutoff December 18". A London reader at 12:00:01 usually sees v42. A Sydney reader at 12:00:05 sees v41 if Sydney read that key recently and its cache entry is still valid.

If Sydney first read the key at 11:59:00 with a five-minute read TTL, v41 can be served until about 12:04:00 even though the central store has held v42 since noon. At 12:04:01 the read returns v42. If the key had an expiration set to 12:02:00, v41 disappears then regardless of the five-minute window, and readers see a missing key.

One writer per key

Concurrent writes to one key are last-write-wins, and the order observed in different locations is not a global sequence. A retried publish can therefore overwrite a newer document with an older one. Send writes for a key through one process — a CI job, a Durable Object, or the REST API — so there is a single stream.

Deletion follows the same schedule. Calling delete successfully removes the authoritative copy centrally but does not mean every location has stopped serving the value; each cache drops it when its entry expires.

The comparison below is about guarantees, not popularity. Each row answers the same question: after a successful write, what is the next reader allowed to see?

MechanismWhat a successful write guaranteesRead visibility in another locationOrdering and atomicityUse it when
Workers KVValue is stored in the central KV storeUp to 60 seconds by default, longer if cacheTtl is larger; negatives are cached tooLast write wins per key; no conditional write, increment, or transaction; one write per second per keyDerived, read-heavy documents where a minute of staleness is acceptable
Cache APIResponse is offered to the cache in the data center that called put()Not replicated at all; each data center has its own copyNo cross-location ordering; per-location replacementPer-location response caching and short-lived fragments
D1Write commits on the primary database instanceA read replica may lag; the Sessions API gives sequential consistency and monotonic reads when you pass the bookmarkSQL constraints and atomic batches on the primary; writes always go to the primaryRelational data, joins, uniqueness, read-your-writes within a session
Durable ObjectsMethod call runs single-threaded at one object, with transactional storageReaders of the same object see the committed order; another object is a different worldStrict serializability per object; no cross-object transactionCounters, locks, leases, inventory, coordination
R2Object write is strongly consistent globally, including metadata and listingImmediate read-after-write for all clientsLast writer wins; conditional If-Match and If-None-Match are evaluated atomicallyBlobs, large documents, create-once artifacts, backups

Figure 3 traces the sequence, including a second publisher and a cached miss. The success path is deliberately boring; the failure branches are the design inputs.

Writes and Visibility Across Locations
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
sequenceDiagram
    autonumber
    participant P as Publisher in London
    participant K as KV central store
    participant L as London edge cache
    participant S as Sydney edge cache
    participant R as Reader
    P->>K: put(config:current, v42)
    K-->>P: accepted, not globally visible
    R->>L: get config:current
    L-->>R: v42, fresh in London
    R->>S: get config:current
    S-->>R: v41 from cache
    Note over S: up to 60 s, longer with cacheTtl
    alt cache entry expires
        S->>K: get config:current
        K-->>S: v42
        S-->>R: v42
    else second publisher writes v43
        P->>K: put(v43) before v42 spreads
        Note over K: last write wins — cross-location order is not guaranteed
        S-->>R: v42 or v43, not a global sequence
    else Sydney cached a miss earlier
        S-->>R: 404 until the negative entry expires
    end

These are boundaries of the products, not of a particular plan. Workers KV is included in the Free and Paid Workers plans with different allowances; the private-beta Workers KV Instant is a separate product with 1 MB namespaces, no metadata, and no list pagination, and should not be assumed available. D1 read replication must be enabled per database, and without the Sessions API all queries still go to the primary. R2's strong consistency is R2's, not a property you inherit by putting KV in front of it.

The widget is a minimal publisher and reader for the Northwind document. It accepts a version from the publisher rather than incrementing one from a KV read, writes version and timestamp as metadata, clamps cacheTtl to KV's 30-second minimum, and returns no-store so a browser or downstream cache cannot add a second staleness layer.

interface Env {
  CONFIG: KVNamespace;
}

interface ConfigDoc {
  version: number;
  banner: string;
  freeShippingThreshold: number;
  flags: Record<string, boolean>;
  publishedAt: string;
}

const DEFAULT_CACHE_TTL = 60;
const MIN_CACHE_TTL = 30;

function cacheTtlFrom(url: URL): number {
  const raw = Number(url.searchParams.get("cacheTtl") ?? DEFAULT_CACHE_TTL);
  if (!Number.isFinite(raw)) return DEFAULT_CACHE_TTL;
  return Math.max(MIN_CACHE_TTL, Math.floor(raw));
}

function configKey(url: URL): string | null {
  const key = url.searchParams.get("key") ?? "config:current";
  return key.startsWith("config:") ? key : null;
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url);
    if (url.pathname !== "/config") {
      return new Response("Not found", { status: 404 });
    }

    if (request.method === "GET") {
      const key = configKey(url);
      if (key === null) {
        return Response.json(
          { error: "key_must_start_with_config:" },
          { status: 400 },
        );
      }
      const cacheTtl = cacheTtlFrom(url);
      const result = await env.CONFIG.getWithMetadata<ConfigDoc>(key, {
        type: "json",
        cacheTtl,
      });
      if (result.value === null) {
        return Response.json(
          { error: "not_found", key, cacheTtl },
          { status: 404, headers: { "cache-control": "no-store" } },
        );
      }
      const meta = result.metadata as
        | { version?: number; publishedAt?: string }
        | null;
      return Response.json(
        {
          key,
          config: result.value,
          metadataVersion: meta?.version ?? null,
          metadataPublishedAt: meta?.publishedAt ?? null,
          cacheTtl,
        },
        {
          headers: {
            "cache-control": "no-store",
            "x-kv-cache-ttl": String(cacheTtl),
          },
        },
      );
    }

    if (request.method === "PUT") {
      // Demo publisher. Keep one writer per key in production and
      // authenticate this route before exposing it.
      const body = await request.json<Partial<ConfigDoc>>();
      const { version, banner, freeShippingThreshold, flags } = body;
      if (
        typeof version !== "number" ||
        typeof banner !== "string" ||
        typeof freeShippingThreshold !== "number" ||
        typeof flags !== "object" ||
        flags === null
      ) {
        return Response.json({ error: "invalid_config" }, { status: 400 });
      }

      const doc: ConfigDoc = {
        version,
        banner,
        freeShippingThreshold,
        flags,
        publishedAt: new Date().toISOString(),
      };

      await env.CONFIG.put("config:current", JSON.stringify(doc), {
        metadata: { version: doc.version, publishedAt: doc.publishedAt },
      });

      return Response.json(
        {
          accepted: true,
          version: doc.version,
          note: "stored centrally; other locations converge on their cache schedule",
        },
        { status: 202, headers: { "cache-control": "no-store" } },
      );
    }

    return new Response("Method not allowed", { status: 405 });
  },
} satisfies ExportedHandler<Env>;

Notice what the publisher does not do: it does not read the current version and add one, because that read can be stale and two publishers would then write the same number. The version comes from the build that produced the document. The 202 response means "the central store accepted this", not "the world has it". If the next request must observe the write, send it to the same place that made the decision — a Durable Object — rather than to KV.

Expiration, Negative Lookups, and Hot Keys

TTL design starts with a written number: the staleness budget. If merchandising tolerates five minutes of an old banner, use a five-minute read TTL and leave the document without an expiration. If a legal notice must disappear at midnight, set an absolute expiration so deletion does not depend on caches honoring a TTL. KV rejects a write TTL below 60 seconds and an absolute expiration less than a minute ahead; the read TTL floors at 30 seconds, lowered from 60 in January 2026.

ClockWhere it is setMinimumWhat it controlsBeats the other?
expirationOn write, as an absolute time60 seconds aheadDeletes the key at a fixed momentYes — deletion wins over any read TTL
expirationTtlOn write, in seconds from now60 secondsDeletes the key after a relative delayYes — same deletion rule
cacheTtlOn read30 secondsHow long one location serves its copy without checking upwardNo — cannot outlive expiration

The clocks compose in one direction. Expiration deletes the data and wins over everything, including a larger read TTL. The read TTL only limits how long a location may serve its copy without checking upward, so a large value on a key with a near expiration is wasted, and a small value on a key with no expiration still leaves the documented 60-second window.

Negative lookups are the part teams forget. If Sydney asks for config:canary and the key does not exist, Sydney caches that miss. Creating the key in London does not erase Sydney's cached "no". The new value can remain invisible there for up to 60 seconds, or longer if the reader requested a larger cacheTtl. The same rule applies to deletes and to keys that expired: absence is a cached fact. Cloudflare's pricing FAQ is explicit that fetching a missing key is still a billed read, so a miss is not free either.

Two strategies are defensible. Make absence a positive value: write {"state":"absent"} with a short expirationTtl, so the application controls the tombstone and distinguishes "not found" from "not yet propagated". Or avoid lookups whose miss is normal on the hot path: keep a manifest key with the current version and derive per-entity keys from it instead of probing each entity. Neither removes the window; both make it observable and bounded.

Hot keys fail in two shapes. A hot read key is the good case: one popular document is cached at every edge and costs little after the first read.

A hot write key hits a hard ceiling

KV permits one write per second to the same key, so a counter, live scoreboard, or per-tenant pointer updated by every request fails long before traffic peaks. Reads also stampede when a popular entry expires: thousands of requests in one location can miss together and head for the regional tier. Vary TTLs slightly across clients, and keep a last-known-good document in module scope so a cold read degrades to older content instead of an error.

Listing and bulk reads are not query operations. A list returns at most 1,000 keys per page under a prefix, in lexicographic UTF-8 order; a bulk read returns values for up to 100 keys in one call.

const values = await env.CONFIG.get<ConfigDoc>(
  ["config:current", "config:canary"],
  { type: "json", cacheTtl: 60 },
);
// A Map: every requested key is present; absent ones map to null.
# One page of keys under a prefix. Repeat with the returned cursor.
npx wrangler kv key list --binding=CONFIG --prefix=config:

Ordering and billing differ too. A bulk read counts as one external operation against the 1,000-per-invocation ceiling, but billing is per key. Listing is billed, eventually consistent, and paginated; a deleted or expired key leaves a tombstone, so an empty page does not prove the end. Only list_complete does.

Neither belongs in a hot request path as an unbounded scan. Maintain an index key, or store small display fields in metadata, which a list returns without a second read. Use bulk reads for "load these twelve fragments", not for "load everything and filter in the Worker".

Why Locks and Critical Counters Need Another Design

KV has no atomic increment, no compare-and-swap, no conditional put, and no transaction. Every read-modify-write is therefore a guess about a value that may have changed.

The counter is the smallest demonstration. Two Workers read views = 41 at the same time, both compute 42, and both write 42. Forty-two is not wrong because the arithmetic failed; it is wrong because the second write erased the first increment. Last-write-wins makes the loss silent. At one write per second per key, the same design also caps throughput far below what a popular page needs.

The lock has the same shape plus a worse failure mode:

  1. Worker A reads lock:job and gets null.
  2. Worker B reads lock:job and also gets null, because A has not written yet and because the negative lookup may itself be cached.
  3. Both write their own owner value with a 60-second lease.
  4. Both conclude they hold the lock and both run the job.

A KV lock is a hint, not a lock

Adding a unique owner does not help, because KV cannot reject the second write. Even in one location, two concurrent calls can both observe absence before either write lands. The 60-second minimum lease is coarse too: a paused holder that resumes after its lease expired can still write, because there is no fencing token and no conditional write to reject it.

Figure 4 contrasts the two designs. The upper path shows both KV writers winning; the lower path shows a Durable Object serializing acquire and issuing a fence that invalidates the stale holder.

Why a KV lock is not a lock, and what replaces it In the upper panel, Worker A and Worker B both read a missing KV lock key and both write an owner, so both run the job. In the lower panel, a Durable Object receives both acquire calls in one order, grants a lease with fence 7 to Worker A, grants fence 8 to Worker B after expiry, and rejects Worker A's later write because its fence is stale. Attempted acquire in KV: both writers observe absence Worker A get(lock) returns null Worker B get(lock) returns null KV key lock:job no conditional put last write wins no fence token A writes owner A A runs the job B writes owner B B also runs the job Two owners. One invariant broken. Lease in a Durable Object: one order, one fence Worker A acquire() Worker B acquire() Counter object single-threaded transactional storage fence increments alarm expires lease A holds lease, fence 7 writes with fence 7 B gets fence 8 after expiry A's stale fence 7 is rejected

The replacement is not "a bigger KV". It is a different consistency boundary:

  • Counters and quotas. Use one Durable Object per counter, or a SQL statement such as UPDATE counters SET n = n + 1 WHERE id = ? in D1. Both give an atomic increment; neither is a KV operation.
  • Locks and leases. Use a Durable Object with an owner row, an expiry, and a monotonic fence. Downstream writes carry the fence and are rejected if stale, and an alarm expires the lease if the holder disappears.
  • Create-once artifacts. Use R2 with If-None-Match: *, evaluated atomically, or a uniqueness constraint in D1. KV has no equivalent.
  • Approximate counts. Shard the key (views:0 through views:15), increment one shard per request, and sum on read. Losing a write is fine for a vanity metric and unacceptable for inventory, billing, or a rate limit.
  • Serialized work. Put the job on a Queue and make the consumer idempotent. Queues deliver at least once, not exactly once, so the handler still needs a deduplication key.

Each replacement has a cost. A Durable Object lives in one location, so distant callers pay a round trip and one object has a throughput ceiling. D1 writes go to one primary, so write latency follows geography. R2 conditional writes are strongly consistent but are object operations, not millisecond coordination. KV buys read scale by giving up write coordination; these products buy coordination by giving up some of KV's read economics.

The boundary condition to write down is the invariant, not the data. "This job runs once" and "this counter is exact" are invariants. "This banner is the latest" is a freshness preference. Put invariants behind a serialization point; put freshness preferences behind KV.

Design a Versioned Configuration Read Model

The lab needs one document and three commands. The document is the value the Worker publishes; the commands create the namespace, start the dev server, and publish the first version.

{
  "version": 1,
  "banner": "Standard shipping",
  "freeShippingThreshold": 75,
  "flags": { "checkout_v2": false }
}
# Create the namespace, then bind the returned id as CONFIG.
npx wrangler kv namespace create CONFIG

# Start the dev server in one terminal.
npx wrangler dev

# In a second terminal, publish the v1 document.
curl -X PUT http://localhost:8787/config \
  -H 'content-type: application/json' \
  -d '{"version":1,"banner":"Standard shipping","freeShippingThreshold":75,"flags":{"checkout_v2":false}}'

# Seed the canary key directly, bypassing the Worker.
npx wrangler kv key put --binding=CONFIG config:canary '{"version":1}'
Guided exercise

Design a Versioned Configuration Read Model

Execution status: design-only; not executed for this article. Every expected result below is an acceptance criterion, not a measurement. The planning baseline is 2026-11-02; product pages were re-checked on 2026-11-05. No hosted multi-region run was performed, so this exercise cannot prove global timing.

Prerequisites. A current Node.js LTS release, npm, a current Wrangler release, curl, and a Cloudflare account on the Workers Free plan. KV is included on Free and Paid plans; the Free allowances at the time of writing are 100,000 reads and 1,000 writes per day, which is enough for this exercise. No paid add-on is required.

Minimal setup. Scaffold a Worker project, then bind the namespace you created as the CONFIG binding in wrangler.jsonc. Set the compatibility date to 2026-11-05, paste the Worker widget into the source file, and start the dev server with the commands above.

The exercise is seven checks. Each row pairs one action with the observation that proves it.

#ActionExpected observation
1Publish the v1 document with the command above202 and accepted: true
2Read the config endpointv1, metadataVersion: 1, and header x-kv-cache-ttl: 60
3Read with ?cacheTtl=30, then ?cacheTtl=5The header reports 30 both times: the widget clamps to KV's minimum rather than sending an invalid value
4Publish v2 with a new bannerThe next read in this single wrangler dev location usually shows v2 immediately; a local observation, not a guarantee
5Read the canary key, seed it as above, then read againFirst read: 404 not_found. After creation it may still return 404 until the cached miss expires — the lesson, not a bug
6Read a key outside the config prefix400; the demo refuses keys that do not start with config:
7List keys twice with a small page limitLexicographic order and a cursor when more remain; an empty page does not prove completion

Failure checks. Each symptom has one likely cause:

  • Versions differ after one publish. A reader is outside the cache window; record the cacheTtl and location first.
  • The version goes backwards. The publisher read a stale version and incremented it, or two publishers raced; move version assignment to the build.
  • A key stays 404 long after creation. A negative lookup is cached, or the write went to another namespace.
  • A list loop never ends. It ignores the completion flag or reuses the first cursor.
  • A PUT returns 202 but never becomes readable. Writer and reader are bound to different namespaces; that is configuration, not consistency.

Cost dimensions. Local development is USD 0. On the Free plan, this stays within 100,000 reads and 1,000 writes per day if you do not loop; missing-key reads are still billed. On the Paid plan, as published on 2026-10-30, reads are USD 0.50 per million after 10 million per month, writes and deletes USD 5.00 per million after 1 million each, list requests USD 5.00 per million after 1 million, and storage USD 0.50 per GB-month after 1 GB. Re-check before budgeting.

Cleanup. Remove the test data in this order:

  • Delete config:current with npx wrangler kv key delete --binding=CONFIG config:current.
  • Delete config:canary the same way.
  • Delete the namespace with npx wrangler kv namespace delete --namespace-id NAMESPACE_ID, remove the binding from wrangler.jsonc, and stop the dev server.
  • Delete .wrangler/state if you want a clean local slate. Deleting the Worker without deleting the namespace can leave billable stored data behind.

Test Stale-Value Handling Without Claiming Global Synchrony

Planned exercise: execution not yet performed. The planning baseline is 2026-11-02, documentation was re-checked on 2026-11-05, and no hosted multi-region test was run. The pass criteria below describe what a correct deployment must demonstrate; they are not measured results.

Pass evidence. A run is credible when all of the following hold:

  • A publish returns 202, and a reader in the publishing location usually observes the new version on the next uncached read; the test records location and cacheTtl rather than claiming a global time.
  • A reader in a second location may serve the previous version, with the delay bounded by the documented 60-second window or the cacheTtl under test.
  • A key whose expiration has passed reads as missing even when a larger cacheTtl was requested; expiration wins.
  • A cached miss can survive the key's creation for the documented window; the first post-create 404 is expected, not a failed write.
  • A bulk read returns a Map with null for absent keys, billed per key though one external operation.
  • Pagination terminates on the completion flag, not an empty keys array, and returns metadata without a per-key read.
  • A second write to the same key inside one second is rejected or throttled; record the actual error rather than assuming a status code.

Fail evidence. A claim of immediate global visibility; a version regression after a retry; a counter that loses an increment under two concurrent writers; a lock that two Workers both believe they hold; an unbounded list scan in a request handler; a stale value served beyond the key's expiration; a 404 that persists after the negative-cache window with no namespace mismatch to explain it.

Self-check.

Why not use KV for a "likes" counter? Two Workers can read the same value and write the same increment, and KV has no conditional write to stop the second. The lost update is silent, and one write per second per key caps the rate anyway. Use a Durable Object or a SQL increment.

You published in London, and Sydney still serves the old banner after 90 seconds. What are the two likely explanations? Either Sydney's cached entry has a cacheTtl longer than 90 seconds, or the response is not coming from KV at all: a browser, CDN, or application cache is replaying the old body, or the publisher wrote a different key or namespace. The 60-second figure is the documented upper bound for the default window, not a promise that every cache is refreshed at exactly 60.000 seconds.

Is list() a consistent snapshot? No. It is eventually consistent and paginated, keys come back in lexicographic UTF-8 order, and tombstones can produce an empty page while list_complete is still false. Use it for maintenance and inventory, not for a request-path decision that must see every key.

Unresolved limitations. No hosted run was performed, so no latency, propagation time, error rate, or throughput was measured. No Wrangler, workerd, or TypeScript version is pinned; the code targets the KV binding API documented in June 2026 and re-checked on 2026-11-05. The 60-second figure is the documented default ceiling, and Cloudflare's wording allows longer delays where a key was recently read.

Several claims are dated observations. The exact error for exceeding the per-key write limit was not verified. Workers KV Instant is in private beta and excluded from every claim here. Pricing, Free-plan allowances, and the 30-second cacheTtl minimum are dated observations. R2, D1, and Durable Object rows summarize documented consistency models and were not benchmarked.

References (verified 2026-11-05):

  • Choosing a data or storage product: https://developers.cloudflare.com/workers/platform/storage-options/
  • How KV works: https://developers.cloudflare.com/kv/concepts/how-kv-works/
  • KV limits: https://developers.cloudflare.com/kv/platform/limits/
  • KV pricing: https://developers.cloudflare.com/kv/platform/pricing/
  • Read key-value pairs, including cacheTtl: https://developers.cloudflare.com/kv/api/read-key-value-pairs/
  • Write key-value pairs, expiration, and metadata: https://developers.cloudflare.com/kv/api/write-key-value-pairs/
  • List keys and pagination: https://developers.cloudflare.com/kv/api/list-keys/
  • Delete key-value pairs: https://developers.cloudflare.com/kv/api/delete-key-value-pairs/
  • Bulk reads, up to 100 keys: https://developers.cloudflare.com/changelog/post/2025-04-10-kv-bulk-reads/
  • Reduced minimum cacheTtl to 30 seconds: https://developers.cloudflare.com/changelog/post/2026-01-30-kv-reduced-minimum-cachettl/
  • D1 global read replication and Sessions API: https://developers.cloudflare.com/d1/best-practices/read-replication/
  • R2 consistency model: https://developers.cloudflare.com/r2/reference/consistency/
  • Durable Objects overview: https://developers.cloudflare.com/durable-objects/
  • Cache API: https://developers.cloudflare.com/workers/runtime-apis/cache/
  • Workers limits, including operations per invocation: https://developers.cloudflare.com/workers/platform/limits/

Next in the Series

In Store and Deliver Objects With R2, we'll explore Connect object APIs, private access, and browser delivery.