Lesson 9 of 9 · 23m
Edge Storage: KV, R2, Durable Objects, and Consistency
Choosing the right state primitive — and understanding exactly what consistency you did not buy.
The easiest way to wreck an edge architecture is to choose storage by convenience instead of consistency. Cloudflare offers several state primitives, each excellent inside its contract and dangerous outside it. Your job is to know the contract before the data becomes important.
KV is for read-heavy, eventually consistent data
Workers KV is globally distributed and optimized for fast reads. Writes propagate eventually — often quickly, not synchronously. That makes KV good for feature flags, configuration, public keys, routing tables, and small rarely-changing values.
const flags = await env.FLAGS.get("checkout", { type: "json", cacheTtl: 60 });Notice the local cache TTL: even KV does not need to be read fresh on every request. KV is a bad fit for counters, inventory, sessions whose revocation must be immediate, or anything where two writes must be ordered.
R2 is object storage, not a database
R2 stores blobs with S3-style APIs and no egress fees in the Cloudflare model. It is ideal for images, exports, static assets, backups, and large immutable artifacts. It is not designed for high-rate small transactional mutations. If you find yourself rewriting JSON objects in R2 to emulate rows, you have invented a slow database with awkward failure modes.
Durable Objects are the consistency primitive
Durable Objects give you strongly consistent, single-threaded state for one logical object. They are the answer when many edge requests need coordinated access to one thing: a room, a session, a rate-limit ledger, a game lobby, a collaborative document.
const id = env.ROOMS.idFromName(roomName);
const room = env.ROOMS.get(id);
return room.fetch(request);The object ID is the routing key. Every request for that name goes to the same object instance, wherever Cloudflare places it. That gives you ordering and coordination — at the cost of one object's throughput being finite. Sharding matters.
D1 and queues fill different holes
D1 is SQLite at the edge: familiar relational semantics for small-to-medium application data, with replication behavior you must read carefully for your chosen mode. Queues decouple work so a user request can acknowledge quickly while a consumer retries asynchronously. Neither replaces the need to decide what must be consistent now.
Field notes
- If a value must be correct immediately after write, KV is the wrong tool no matter how convenient the API is.
- Put object keys and sharding strategy in the design document. Renaming a Durable Object namespace or resharding later is real work.
- Store large immutable content in R2 and references elsewhere; do not stuff megabytes into KV or Durable Object storage.
- Every primitive has a different backup, restore, and audit story. Decide how you prove correctness before an incident forces the question.
Was this lesson helpful?