Server
For the complete documentation index, see llms.txt. Prefer markdown by appending .md to documentation URLs or sending Accept: text/markdown.

Caching

Cloudflare KV and application caching in Edge Kit, including keys, expiration, invalidation, consistency, and customer-specific data.

Caching lets your application reuse a result instead of recomputing or refetching it for every request. Edge Kit includes a Cloudflare KV binding and shared read, write, and delete operations, giving you a starting point for cached public data, small configuration values, and expensive external responses.

Workers KV stores values by key and distributes reads across Cloudflare's network. Your feature chooses the value, its lifetime, and what should happen when it is missing or out of date.

Why Workers KV?

Workers KV suits frequently read values that change less often, with distributed reads and expiration controls built in. A Worker binding makes it available alongside your application data. Its eventual consistency is a useful tradeoff for cached summaries and public settings; current access decisions still belong in authoritative server state.

Cache layers

Different parts of the application can reuse data for different reasons:

LayerTypical use
TanStack QueryReusing fetched data across views in the current application session
Workers KVReusing server-side values across requests and Worker instances
HTTP cachingLetting browsers or an explicitly configured public cache reuse responses
D1Keeping authoritative product records and relationships

Refreshing a client query does not automatically remove a KV entry. Likewise, deleting a server cache entry does not immediately replace the data already displayed in an open browser. Connect both layers to the lifecycle of the feature that owns the data.

Data fetching covers the client layer, while storage explains file responses and access policies.

Suitable values

Good candidates are read frequently, change less often, and tolerate some delay before every location sees an update. Examples include a public directory response, a computed product summary, or non-sensitive display configuration fetched from another service.

KV is eventually consistent. A changed or deleted value can take time to propagate, including cached misses. Design the feature around that behavior rather than assuming every subsequent request immediately sees the latest write. Cloudflare's consistency documentation explains the model.

Authoritative decisions

Use the database and trusted server state for ownership, current subscription access, or an allowance that must be enforced accurately. A distributed cache is useful for display data, but stale values should not grant a customer access they no longer have.

For a counter that must update atomically or a workflow requiring coordinated writes, choose a storage model designed for that operation rather than treating KV as a transactional database.

Keys and values

A cache key identifies everything that changes the result. Include the relevant resource, language, filters, and a format version when the stored representation can evolve.

For example, public catalog summaries might use keys such as:

catalog:summary:v1:en
catalog:summary:v1:es

The included KV wrapper reads and writes strings. Serialize structured values deliberately, validate them when reading, and handle missing or older values. A new deployment may encounter an entry created by the previous release.

Keep keys predictable enough to invalidate and investigate. Avoid placing email addresses, access tokens, or other sensitive customer details in key names.

Cache lifecycle

A common approach is cache-aside:

  1. Build the key from validated inputs and the result's scope.
  2. Read the stored value and use it if its format is acceptable.
  3. On a miss, load or compute the result from its authoritative source.
  4. Store the result with an appropriate expiration.
  5. Return the result to the caller.

The shared KV operations provide the resource access; your feature supplies this policy. The write operation accepts Cloudflare's put options, including expiration controls. The KV write API lists their supported values and constraints.

For example, a server operation can cache a small public summary for five minutes:

import { env } from "cloudflare:workers";

import { kv } from "@/lib/kv";

await kv.put({
  namespace: env.KV,
  key: "catalog:summary:v1:en",
  value: JSON.stringify({ totalProducts: 42 }),
  options: { expirationTtl: 300 },
});

The count is example data; your feature supplies the computed result. A missing or expired entry should lead back to the source, and the reader should validate the stored representation before using it.

Choose the lifetime around the cost of stale data. A public summary may tolerate minutes of delay, while a customer editing their own record usually expects an immediate result from the database.

Invalidation

When a product update makes an entry obsolete, either remove the affected key or write the replacement value. An expiration provides a backstop for entries that were not explicitly refreshed.

Keep the invalidation near the operation that changes the underlying data. If a background task refreshes a public summary, its completion should update the relevant cache entry as part of the same product workflow.

Versioning the key lets a release use a new representation without interpreting old cached data. Give obsolete values an expiration or cleanup policy so changing the key does not leave them indefinitely.

Private data

Authorize a private request before returning a cached result. Scope the entry to the customer or resource whose permissions determine it, and avoid public HTTP cache headers on private responses.

Decide how deletion, account changes, and permission changes affect those entries. Short expiration alone does not make a stale permission decision safe. For most new private features, start with protected database reads and add caching after you identify a specific performance need.

Local development

The existing KV binding gives local development its own simulated namespace. Configure your production namespace through Wrangler and inspect local values through Local Explorer.

Check the first request, a repeated request, expiration, and an update to the underlying record. Also check malformed or missing cached values, so the feature can recover by reading its source rather than failing permanently on an old entry.

How is this guide?

Last updated on

On this page

Ship globally on the edge. In minutes.Try Edge Kit