In Cloudflare R2, two tabs save the same profile JSON through a Worker and one edit vanishes; how do onlyIf conditions on put() prevent it?
answer
- last writer wins
- compare the etag you read
- null instead of an exception
- bare etag versus quoted httpEtag
basics
~20 sR2 is last-writer-wins, so the second save replaced the first. Send back the etag that was read and put() with onlyIf etagMatches or If-Match; if the object changed, put() returns null without writing, and the Worker answers 412.
solid answer
~40 sStrong consistency means each tab reads the latest object, but nothing stops both from writing after reading the same version: the last `put()` to finish wins. A conditional write fixes it. The Worker returns the object's `httpEtag` on `GET`, the client sends it back as `If-Match`, and the Worker calls `put(key, body, { onlyIf: new Headers({ "If-Match": etag }) })`. When the stored etag no longer matches, `put()` resolves to `null`, writes nothing, and the Worker returns 412 so the client re-reads and merges. With an `R2Conditional` object, `etagMatches` takes the bare `etag`; passing the quoted `httpEtag` throws a `TypeError`. `If-None-Match: *` makes a write create-only. The same `onlyIf` on `get()` returns an `R2Object` without a body when the condition fails, which is how a Worker answers 304.
code
javascript · 28 linesexport default {
async fetch(request, env) {
const key = "profiles/user-42.json";
if (request.method === "GET") {
const object = await env.UPLOADS.get(key);
if (object === null) return new Response("Not found", { status: 404 });
return new Response(object.body, {
headers: { "content-type": "application/json", etag: object.httpEtag },
});
}
if (request.method === "PUT") {
// Update only the version the client read; with no If-Match, only create a new profile.
const ifMatch = request.headers.get("if-match");
const condition = ifMatch ? { "If-Match": ifMatch } : { "If-None-Match": "*" };
const stored = await env.UPLOADS.put(key, request.body, {
onlyIf: new Headers(condition),
httpMetadata: { contentType: "application/json" },
});
if (stored === null) return new Response("Precondition failed", { status: 412 });
return new Response(null, { status: 204, headers: { etag: stored.httpEtag } });
}
return new Response("Method not allowed", { status: 405 });
},
};go deeper
Recall that R2 lets the last writer win, and that put() can be made conditional on the etag you read earlier.
Explain the R2Conditional fields, the Headers alternative, null on a failed put() and 412 to the client, and If-None-Match star for create-only writes.
Diagnose the lost update as a missing precondition rather than a consistency bug, and show the quoting trap between etag and httpEtag.
Decide when one object per document stops working, because of contention, the per-key write rate or the need for multi-object updates, and where that data should live instead.
## Why the edit vanished R2 is **strongly consistent**: once a `put()` resolves, every later read anywhere sees it. That guarantees freshness, not isolation. Two browser tabs can both read version A of `profiles/user-42.json`, each change a different field, and each `put()` its whole document. Both writes succeed, and the one that finishes last replaces the other. This is a **lost update**, and R2 resolves concurrent writes to one key by **last writer wins**. Writes to one key faster than about one per second are additionally rate limited (HTTP 429), which spaces writes out but does not order them. The timeline of the bug: 1. Tab 1 and tab 2 both `GET` the profile and receive version A. 2. Tab 1 changes the display name and `PUT`s version B; R2 stores it. 3. Tab 2 changes the bio, still based on version A, and `PUT`s version C. 4. R2 stores C over B. The display name change is gone, and nobody saw an error. With a precondition, step 3 carries version A's etag, R2 sees that the stored object is now B, and the write is refused. ## Conditional writes with onlyIf `put()` and `get()` accept `onlyIf`, a precondition R2 checks against the stored object before acting. As an **`R2Conditional`** object it has these fields: | Field | The operation runs when | |---|---| | `etagMatches` | the stored etag equals the given value | | `etagDoesNotMatch` | the stored etag differs from the given value | | `uploadedBefore` | the object was uploaded before the given `Date` | | `uploadedAfter` | the object was uploaded after the given `Date` | An **etag** is an identifier for one stored version of an object; R2 returns it as `etag` (bare hex) and `httpEtag` (quoted, ready for an HTTP header). Any change to the object produces a new etag, so "write only if the etag is still the one I read" is an optimistic lock. ## Two ways to pass the condition - **An `R2Conditional` object**, such as `{ etagMatches: object.etag }`. It expects the **bare** etag. Passing `httpEtag`, quotes included, throws `TypeError: Conditional ETag should not be wrapped in quotes`. - **A `Headers` object** carrying standard conditional headers: `If-Match`, `If-None-Match`, `If-Modified-Since` and `If-Unmodified-Since`. Quoted entity tags are accepted here, so a Worker can forward what the client sent. `If-Range` is the one conditional header R2 does not support. `If-None-Match: *` deserves a mention: it succeeds only when no object exists under the key, which makes a `put()` **create-only** and stops two first-time saves from racing. ## What the Worker does when the condition fails The binding reports a failed precondition as a value, not an exception: 1. On `GET`, return the body with `etag: object.httpEtag`. 2. On `PUT`, require `If-Match` (or use `If-None-Match: *` for a first save) and pass it in `onlyIf`. 3. If `put()` resolves to `null`, nothing was written; answer **412 Precondition Failed**. 4. The client fetches the current document, reapplies or merges its change, and retries with the new etag. Over the S3-compatible API the same failure arrives as an HTTP 412 `PreconditionFailed` error; only the binding uses `null`. ## Conditional reads and range reads - `get(key, { onlyIf: request.headers })` passes a browser's `If-None-Match` straight through. When the condition fails, `get()` returns an **`R2Object` without a `body`**, so the Worker can test `"body" in object` and answer 304 without reading any data, with lower latency than a full read. - `get(key, { range })` returns part of an object, for example a video player seeking. `range` is `{ offset, length }`, `{ offset }`, `{ length }`, `{ suffix }` or a `Headers` object with a `Range` header, and the result's `range` field reports the bytes actually returned, for building `Content-Range` on a 206. ## When conditions are not enough - A document edited by many people at once may need finer-grained storage than one JSON object, so that edits to different fields stop colliding. - Conditions protect one key at a time; R2 has no transaction across several objects. - For counters, locks or anything updated many times per second, R2's per-key write rate is the wrong tool.
- How does a Worker answer a browser's conditional GET with 304 from R2 without reading the object?Pass the request's headers as the condition: `get(key, { onlyIf: request.headers })`. If the browser's `If-None-Match` still matches, the condition fails and `get()` returns an `R2Object` with no `body`. Check `"body" in object`, and when it is absent return 304 with the `etag` header; otherwise stream `object.body` with 200.
- How does a Worker serve a byte range of a large R2 video for seeking?Call `get(key, { range: request.headers })` or pass `{ offset, length }` or `{ suffix }`. R2 returns only those bytes, and `object.range` reports the offset and length served. Answer 206 with a `Content-Range` built from that range and `object.size`, and stream `object.body`.
- Why does R2's strong consistency not prevent the lost update on its own?Consistency guarantees that each read sees the latest completed write. Both tabs did read the latest version; the problem is that each wrote a whole document based on what it read, and R2 accepts both writes in completion order. Only a precondition ties a write to the version it was based on.
- R2's strong consistency already prevents lost updates between writers
- A failed onlyIf on the binding's put() throws an error to catch
- etagMatches should be given object.httpEtag, quotes included
- A conditional get() still downloads the body for you to discard
- Conditional writes lift R2's one-write-per-second limit on a key