A Correctness Requirement Is More Precise Than Fast Storage
Harbor Line runs a ferry with 240 seats. At 09:00, 230 are sold; forty requests arrive in the same second, two seats each. In the good outcome five succeed and the manifest shows 240. In the bad one it shows 250 and a confirmed family is left on the dock. Both can come from fast storage; only one from storage chosen against a stated rule.
That rule is an invariant: a statement that must hold before and after every operation, not merely eventually. Harbor Line's capacity invariant is confirmed_seats(sailing) <= 240; its per-customer invariant is seats(sailing, customer) <= 4. The page-view counter has no invariant at all, because nobody is denied boarding over an approximate number. Those facts point at three products, before any configuration.
State semantics are the set of read and write histories a system permits.
Four guarantee families appear in the Cloudflare docs, and each one leaves out something the others promise.
| Model | What it promises | What it leaves unresolved | Where it shows up |
|---|---|---|---|
| Serialization point — linearizable, or strictly serializable with transactions | Every operation appears to take effect at one instant between invocation and response, in real-time order | Nothing about cost, latency, or availability | Durable Objects, which Cloudflare describes this way (Choosing a data or storage product) |
| Sequential consistency | All clients agree on one total order that respects each client's program order | Real-time order across clients | D1's Sessions API (D1 read replication) |
| Eventual consistency | Convergence once writes stop | When convergence happens | KV, where changes "may take up to 60 seconds or more" to appear elsewhere (How KV works) |
| Read-your-writes and monotonic reads | A read after your own acknowledged write observes it; successive reads never move backwards | Any global order — these are per-client promises | Redirects and refreshes, where users notice it first |
The last row is the one that gets lost between requests, and it is the one an invariant usually depends on.
The mental model is a ticket office with three artifacts. The notice board at every pier is KV: cheap to read, reprinted on a schedule, allowed to lag. The ledger with couriers is D1: one head-office ledger, regional photocopies, and a receipt number — a bookmark — that lets a clerk say "do not serve me a page older than this." The ticket window is a Durable Object: one clerk per sailing, one transaction at a time, and the receipt is handed over only after the entry is in the book.
The invariant chooses the artifact. The artifact does not choose the invariant. Figure 1 turns that into a decision path, and its first branch is a stop: if you cannot state the invariant, no storage comparison can be evaluated, because every product looks fast in a demo that never violates the rule.
%%{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
R["Business rule:
never confirm more than 240 seats"] --> I["Restate as an invariant:
confirmed seats at most 240
and 4 per customer"]
I --> Q1{"Can a stale read
violate the invariant?"}
Q1 -->|"no: staleness only changes
what is displayed"| K["KV candidate:
cache plus version metadata"]
Q1 -->|"yes"| Q2{"Must more than one row
or key change together?"}
Q2 -->|"no: one guarded write
can decide it"| D["D1 candidate:
constraint plus guarded write"]
Q2 -->|"yes, or the decision spans
an await or external call"| O["Durable Object:
one ID, one serialized writer"]
I -->|"cannot state it"| X["Stop: no storage choice
can be evaluated"]
K --> T["Test the failure mode:
stale read, negative cache,
lost update"]
D --> T
O --> T
T -->|"invariant violated"| I
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 I primary;
class R,K,Q2,D,O,X secondary;
class Q1,T danger;
Figure 2 shows the same argument as layers, because the common failure is not picking the wrong product. It is picking the product first and then writing an invariant that the product happens to satisfy. The red path is the backwards order: a team benchmarks writes, chooses the fastest, and then discovers that the property it needs — "my own write is visible on the next request" — was never on the benchmark.
The rest of this article walks down those layers for one system. It compares what KV, D1, and Durable Objects actually promise, designs the stale-read and concurrent-write tests that distinguish them, and finishes with an exercise that runs the same invariant against all three designs.
KV Visibility and Cache Effects
KV keeps the authoritative copy in a few central data centers. It fills edge caches when keys are read, and a write lands centrally rather than being pushed to every location. That explains most KV surprises.
The visibility budget is explicit. Changes are usually immediately visible where they were made, but that is "not guaranteed and therefore it is not advised to rely on this behaviour." Elsewhere they may take up to 60 seconds or more. Visibility is slower where a previous version was recently read — and a read that returned "not found" is cached too, so creating a key can be as invisible as changing one (How KV works).
Three controls, and only one of them changes what a read returns. Expiration is set on write; cache TTL is set on read; metadata travels beside the value.
Expiration is write-side; cache TTL is read-side. Expiration deletes the key, with a platform minimum of 60 seconds. Cache TTL controls how long a response stays cached — default 60 seconds, minimum 30 since January 2026 — so raising it improves hot-read latency and lengthens staleness. It is not invalidation (KV limits, changelog).
Metadata detects staleness; it cannot remove it. Up to 1,024 bytes can carry a version, so a reader knows it is behind and stops acting on an old value. The read itself is no fresher.
Write limits decide the shape of the workload. Writes to the same key are limited to one per second on both plans, and there is no compare-and-set, multi-key transaction, or conditional write. If two writers update one key, the later write wins and the earlier is gone (KV limits).
A banner, feature flag, redirect map, or public profile card fits KV. The value is a whole document by key, it can be rebuilt from a system of record, a minute of staleness changes presentation but not entitlement, and one writer owns each key.
A seat count fails on three counts. Reads and writes must agree at one instant, the update is a read-modify-write, and one hot key breaks the write ceiling. No cache-TTL tuning fixes a lost update. The table compares the mechanisms on the criteria that decide an invariant, not on average latency.
| Mechanism | Guarantee you may rely on | Staleness to budget | Conflict rule | What you still own |
|---|---|---|---|---|
| KV write | Durable central write; usually visible at the writing location, not guaranteed | Other locations may lag; no upper bound is promised beyond "60 seconds or more" | Last write to the key wins; no conditional write | Choosing one writer per key and never doing read-modify-write |
| KV cached read | A value that was current at some recent point | Up to 60 seconds or more; negative results are cached; cacheTtl default 60 s, minimum 30 s | None detectable without your own version field | A stale policy and a version check in metadata |
| D1 primary statement | Atomic and serialized with other statements on that database | None for the statement itself | Row-level last writer; use a guarded UPDATE to decide | The predicate that encodes the invariant |
| D1 batch | All statements commit, or the sequence rolls back | None within the batch | Same as the primary | Keeping the batch short; no interactive transaction across requests |
| D1 replica read, no session | A snapshot that may be arbitrarily behind the primary | Unbounded replica lag | Not applicable to reads | Tolerating a read that moves backwards |
| D1 session read | Sequential consistency: monotonic reads and writes, writes-follow-reads, read-your-writes | Bounded only by the bookmark you carry | Not applicable to reads | Carrying the bookmark into the next request |
| Durable Object | Strict serializability per object; one instance per ID | None inside the object | Your code decides; storage operations serialize | Identity, sharding, and idempotency |
Figure 3 shows the same boundary as a sequence. The failure branch is the normal one: a reader in another region has the previous value cached, and the write has no way to reach into that 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','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 E as Editor in London
participant K as KV central store and caches
participant R as Reader in Sydney
participant O as Durable Object for the key
E->>K: put(banner, v42)
K-->>E: 200 written centrally
Note over K: no push to the Sydney cache
R->>K: get(banner), cacheTtl 60
alt Sydney still holds v41
K-->>R: v41, stale but valid
else key was absent and the miss was cached
K-->>R: null, although v42 exists
end
E->>O: write through the key owner
O->>O: serialize writers, choose v43
O->>K: put(banner, v43)
O-->>E: 200 plus version 43
R->>K: get(banner) and compare metadata version
alt version is at least the one the reader needs
K-->>R: v43, usable
else version is older
K-->>R: v41, reader retries or labels it stale
end
KV cannot answer 'at least version 43'
A KV reader can only read, compare its metadata, and decide. That is why Cloudflare's write-after-write pattern routes every write for a key through a Durable Object, then lets other Workers read KV (How KV works). The object serializes writers, but KV still serves possibly stale reads: the pattern improves the write history, not the read guarantee.
If the next screen must show the new value, do not read it from KV. Read it from the object or from D1.
D1 Sessions and Relational Updates
D1 is managed SQLite. Each database is single-threaded and processes queries one at a time; each database is backed by a single Durable Object, and each read replica is a different Durable Object with the same behavior (D1 limits). That is why a single statement is atomic and a guarded UPDATE can decide an invariant.
Without replication, every query goes to one primary. With read replication, Cloudflare adds read-only copies in ENAM, WNAM, WEUR, EEUR, APAC, and OC. Replication is asynchronous, so a replica "may be arbitrarily out of date"; that gap is replica lag. Writes always go to the primary, even when they arrive through a replica (D1 read replication).
Replication alone breaks the confirmation screen. Write, redirect, read a replica, see the old manifest. The Sessions API fixes that by attaching a bookmark — a position in the global write order — to every query in a session, and a session started with a bookmark is served by a replica caught up to at least that position. Within a session, D1 documents sequential consistency: monotonic reads and writes, writes-follow-reads, and read-your-own-writes.
A session is a bookmark chain, not a cookie or a lock. If the bookmark does not travel to the next request, the next request gets a new unconstrained session and the guarantee resets. A redirect, a background job, or a mobile retry at another edge is a new request. Figure 4 draws the boundary.
The bookmark must travel with the request
D1's primary serializes statements, but your application is not automatically strongly consistent: every read that does not carry a bookmark may be served by a replica that is arbitrarily behind. A bookmark is a freshness constraint, not an authorization token, and it only helps if the next request actually presents it.
Read-your-writes is a protocol, not a property you buy. Carry the bookmark in a header or HTTP-only cookie and pass it into the session; start the critical screen at the primary; or render the committed result from the write response and skip the read.
Conflicts need the same discipline. D1 serializes statements, but two requests can still read, compute, and write around each other. Put the decision inside the statement, and carry the bookmark rather than remembering it:
The statement inserts one row or none, and the result reports which. A unique request id makes retries idempotent. A batch() is the multi-statement unit — D1 runs in auto-commit and rolls back the sequence if a statement fails (D1 database API) — but a batch cannot branch on a result, so the guard belongs in the statement.
Design the stale-read test before the feature
Record every operation with invocation and response timestamps, the bookmark, the serving region, and whether the primary answered. Then assert three things: a read carrying the write's bookmark sees the row, one bookmark chain never regresses, and a read without a bookmark may be stale and is labeled so.
A local pass proves nothing about replicas. The serving-region fields are undefined under wrangler dev, so a green local run is not evidence of replica behavior.
A beta with a 24-hour rollback
Read replication was introduced as a public beta in April 2025; confirm its current status and the per-database toggle before promising it (changelog). Disabling it takes up to 24 hours for replicas to stop serving, so a rollback is not instantaneous.
Durable Object Identity and Coordinated Mutation
A Durable Object is the smallest unit of coordination you can name. One ID maps to one instance, globally, and that instance runs in one location with private SQLite storage. All requests for the same ID are serialized by that instance. The storage API provides transactions, and Cloudflare describes the resulting guarantee as strict serializability (Choosing a data or storage product).
The hard part is not the transaction. It is the identity.
Three spellings produce three IDs. A client books the 08:00 sailing as a hyphenated date key, a cron job writes the same sailing in ISO form, and a mobile retry appends a timezone offset. Name hashing turns each string into its own ID, so three spellings produce three objects and three independent 240-seat counters. The transaction inside each object is perfect. The system still oversells by 480 seats, because the invariant was never scoped to one object. Figure 5 shows the before and after.
Three mechanisms do the work inside one object. Input gates stop new events while synchronous JavaScript runs and while a storage operation is in flight. Output gates hold responses until pending writes are durable, so a client never receives a success storage did not accept. Write coalescing merges writes without an intervening await into one atomic commit (Rules of Durable Objects).
The gate is not a lock
It is per object, not per system. An outbound fetch opens it, so a read, an external call, and a write are three separate decisions unless you close the gap. blockConcurrencyWhile() closes it unconditionally — right for schema setup, wrong for request handling, where a 5 ms callback caps throughput near 200 requests per second. For multi-statement read-modify-write during traffic, use transactionSync().
Three boundary conditions belong in the design review:
- Single-threaded is not FIFO. An object may process request events out of arrival order. If order matters, encode it as a sequence number or version.
- Identity is a schema decision.
idFromName()is deterministic for the same string, but a string is not a canonical entity. Canonicalize before hashing, store the canonical key on the D1 row, and never let two formats reachidFromName(). - Memory is not state. Eviction or an uncaught exception loses in-memory fields while SQLite survives. A counter in a class property can reset to zero; one in a row cannot. Alarms are at-least-once with up to six retries, so charge idempotently (Alarms).
The tradeoff is throughput and blast radius. One object handles roughly 500 to 1,000 simple requests per second, so the atom of coordination must be small: one sailing, one room, one document. Shard by the entity that owns the invariant.
Durable Objects are not always necessary. If one guarded SQL statement can decide the invariant, D1 is simpler and queryable with ordinary SQL. Reach for an object when the decision spans a read and a write, includes an external call, changes several keys together, or must share state with a long-lived connection.
Choose Storage for a Counter, Profile, and Reservation
Three routes, one sailing, one variable. Each arm reaches the same fixtures through a different mechanism, so the storage decision is the only thing that changes.
Choose Storage for a Counter, Profile, and Reservation
Execution status: design-only. Not executed. Planning baseline 2026-11-02; documentation re-checked 2026-11-05. No local or hosted run occurred, and no measured result is claimed. Observations below are acceptance criteria, not findings.
Inputs and invariants. Sailing S has capacity 240 and 230 seats taken, leaving 10; the per-customer limit is 4; customer C has a versioned profile; a page-view counter may be approximate. The six invariants are I1 capacity, I2 per-customer cap, I3 read-your-writes, I4 monotonic reads, I5 profile version, and I6 counter lag.
Prerequisites. Node.js 22 LTS or current, a terminal, current Wrangler, and an account with Workers and D1. The Free plan covers the single-region arms: 10 D1 databases at 500 MB, and SQLite-backed Durable Objects at 1 GB each (D1 limits, Durable Objects limits). If the database settings show no replication toggle, run that arm as a design review and label it. Use invented customers and no real payment provider.
Minimal setup. The widget above defines the routes. Seed D1 and the object with 230 seats and the same canonical key, and keep the KV arm as the negative control.
Steps.
| Step | Action | Expected |
|---|---|---|
| 1 | Read the sailing through all three routes | 230 taken and 10 remaining, so the fixtures agree before concurrency |
| 2 | Send 40 concurrent requests of 2 seats from 20 customers to the D1 route | 5 successes, 35 clean 409s or idempotent replays, total 240; reset and repeat on the object route |
| 3 | Reset and repeat on the KV route | Lost updates and a total that is not 240; a clean pass means the test never overlapped |
| 4 | Reset to 230 seats taken, then send three concurrent requests of 2 seats from one customer | At most two successes under D1 and the object, the third rejected by I2 |
| 5 | After a booking, read the confirmation with and without the returned bookmark | The first sees the booking; the second may be stale and must say which path served it |
| 6 | Read three times on one bookmark chain while a writer adds bookings | No decrease; with unconstrained sessions a decrease is permitted and must be labeled |
| 7 | Read the profile at version 7 from two clients, then write from both | One success at version 8 and one 409 |
| 8 | Send 500 view events | A monotonic, approximately correct counter; one KV key throttles, one object serializes at its ceiling |
Expected observations. D1 and the object preserve I1 and I2 by different mechanisms; KV violates I1; the profile has one winner per version.
Failure checks.
- A 200 with no booking row means the output path lied.
- A total above 240 means the guard ran outside the write.
- A total below 240 with rejections means the guard was too strict or a valid insert rolled back.
- Two rows for one
request_idmeans idempotency lived in application code. - An old manifest after a 201 means the bookmark was dropped.
- A stale-version write means the version predicate or the result metadata was ignored.
Cost dimensions. Tens of requests, one database, one object, a few kilobytes. KV Free allows 1,000 writes and 100,000 reads per day, with one write per second per key; D1 bills rows read and written; Durable Objects bill requests, duration, and stored GB-months (KV limits, D1 pricing, Durable Objects pricing).
Cleanup. Delete the Worker, database, namespace, and any route; remove .wrangler/state and results; discard invented records. If replication was enabled, disable it and note that replicas may take up to 24 hours to stop.
Show Which Designs Preserve Each Stated Invariant
Planned exercise: execution not yet performed. Documentation was verified on 2026-11-05 against the pages below. No product was tested, no local or hosted run occurred, and no measurement is claimed. The planning baseline is 2026-11-02.
Pass evidence. Keep a history, not a screenshot: one row per operation with the request ID, invariant inputs, status, bookmark, serving region, and committed total.
- I1, capacity. The total never exceeds 240; 201s equal new bookings; no 5xx counts as a success.
- I2, per-customer cap. No customer exceeds 4 seats, and the rejection carries a distinct conflict reason.
- I3, read-your-writes. A read carrying the write's token observes the write; one without it may be stale and says so.
- I4, monotonic reads. One bookmark chain never regresses; independent sessions may.
- I5, profile conflict. Exactly one writer wins per version; the loser gets 409.
- I6, counter. Monotonic, bounded error, and never read by an entitlement, billing, or capacity path.
Fail evidence — any one of these voids a pass.
- A total above capacity, or a booking without a seat count.
- A 200 whose write vanishes after a restart.
- A duplicate
request_id. - A stale-version overwrite.
- A confirmation screen showing pre-write data when a valid bookmark was presented.
- A claim of "strong consistency" that cannot name the serialization point.
A pass produced by running everything sequentially is a baseline. Keep the KV negative control in the report: showing it fail is more credible than omitting it.
Self-check, with explanations.
Why is "D1 is strongly consistent" not a sufficient design statement? It names a product, not a history. Without replication, one primary serves every query and a statement is atomic. With replication, a read without a bookmark may hit an arbitrarily stale replica. The claim is true only when you add "for a session carrying a bookmark" or "for queries routed to the primary."
Why can a Durable Object still oversell? Its guarantee is scoped to an ID, and the ID comes from a string. Two spellings of one sailing produce two objects, each with a correct 240-seat transaction that cannot see the other. Canonicalizing identity, not strengthening the transaction, is the fix.
Why does a KV read return "missing" for a key that exists? Negative lookups are cached like any result. A location that recently asked and was told "no" keeps answering "no" for a while after creation, on the same order as a changed value: up to 60 seconds or more. A version check mitigates the symptom; only a different read path fixes the guarantee.
What a pass cannot prove
Replica lag is not exposed as a number, and the serving-region field says only where a query ran. A pass from one region does not prove the absence of a violation anywhere else.
- Local runs cannot observe global behavior. Neither KV propagation nor D1 replication is reproduced locally, and the serving-region fields are
undefinedunderwrangler dev. - Read replication was a public beta, and disabling it can take up to 24 hours for replicas to stop serving.
- Durable Object throughput is per object, not per namespace.
- Plan and price details are dated. The 50 MB D1 result limit (effective 2026-11-04), allowances, and prices must be re-checked.
- No hosted validation was performed, so every expected observation is an acceptance criterion, not a measurement.
References (verified 2026-11-05):
- Choosing a data or storage product: https://developers.cloudflare.com/workers/platform/storage-options/
- How Workers KV works: https://developers.cloudflare.com/kv/concepts/how-kv-works/
- Workers KV limits: https://developers.cloudflare.com/kv/platform/limits/
- Workers KV pricing: https://developers.cloudflare.com/kv/platform/pricing/
- Reduced minimum cache TTL for Workers KV: https://developers.cloudflare.com/changelog/post/2026-01-30-kv-reduced-minimum-cachettl/
- Cloudflare D1: https://developers.cloudflare.com/d1/
- D1 global read replication: https://developers.cloudflare.com/d1/best-practices/read-replication/
- D1 read replication public beta: https://developers.cloudflare.com/changelog/post/2025-04-10-d1-read-replication-beta/
- D1 database API, including
withSession()andbatch(): https://developers.cloudflare.com/d1/worker-api/d1-database/ - D1 limits: https://developers.cloudflare.com/d1/platform/limits/
- D1 pricing: https://developers.cloudflare.com/d1/platform/pricing/
- Durable Objects: https://developers.cloudflare.com/durable-objects/
- Rules of Durable Objects: https://developers.cloudflare.com/durable-objects/best-practices/rules-of-durable-objects/
- Durable Objects alarms: https://developers.cloudflare.com/durable-objects/api/alarms/
- Durable Objects limits: https://developers.cloudflare.com/durable-objects/platform/limits/
- Durable Objects pricing: https://developers.cloudflare.com/durable-objects/platform/pricing/
- Durable Objects: Easy, Fast, Correct — Choose three: https://blog.cloudflare.com/durable-objects-easy-fast-correct-choose-three/
- Jepsen consistency models: https://jepsen.io/consistency/models