Conditional PutObject Is a Primitive, Not the Whole Lock Protocol
The documented guarantee is narrow, and it is about one request. R2 evaluates conditional write headers atomically, as part of the same write that commits the object. When several clients race to create an absent key with a create-once condition, at most one succeeds and the rest receive a precondition failure.
A Terraform lock is a protocol wrapped around that request. Acquisition, holder identity, expiry, release and the state write are separate steps with separate guarantees. The primitive settles the first step and says nothing about the other four.
The tempting inference is that create-once means two applies cannot interleave. That follows only if every later step is fenced by the same object acquisition created. Here the lock object guards entry; nothing documented says it guards the state write at the end of the run.
| Layer | What it must guarantee | Conditional put provides it | Failure when absent |
|---|---|---|---|
| Acquisition | One winner among concurrent creators | Yes, documented | Two writers enter together |
| Identity | The loser can name the holder | No, the object body carries it | Wrong lock cleared by hand |
| Expiry | A dead holder stops blocking | No timer exists | Lock outlives the run, or is cut short |
| Release | Only the holder deletes the object | Not by itself | A stale release removes a live lock |
| State write | The write lands only for the holder | No, last completion wins | Paused writer overwrites a successor |
Retries make the primitive ambiguous from the client's own side. Suppose the first create-once put commits and the response is lost; the SDK retries, the retry sees an existing key, and it returns a precondition failure. The client now holds a failure caused by its own success, and the status code alone cannot separate the two cases.
Only the lock body resolves that ambiguity. Read the object and compare its holder, operation and creation time with the run that is asking. A match means you already own the lock and the failure was a self-conflict; a mismatch means someone else does. That comparison is the reason identity is written into the object at all.
Holder identity is recorded, not enforced. The lock object names an operation, a principal and a creation time, and the losing client prints them. That is a diagnostic that lets an engineer check the right lock, not an authorization check on who may delete it.
Expiry is a runbook policy, because the object has no clock. Nothing in the lock counts down. Age is evidence to be combined with proof that the process is gone, which is why "stale after thirty minutes" belongs in a document rather than in the backend configuration.
Fencing is the layer that is missing entirely. A fencing token is a value that grows monotonically so an older holder's write can be rejected. The lock ID is a nonce that protects the unlock call; it does not travel with the state write, so a paused process can resume all the way to its own write.
Renewal is where a lease design usually breaks. Terraform acquires the lock once and releases it at the end, so there is no renewal to get wrong. If you build a lease on top of the object, renewal has to be a compare-and-swap against the current ETag, because delete-then-create leaves a window in which another writer legitimately wins.
A lease you implement yourself needs three fields. Holder, expiry and an epoch that only increases. The epoch is what turns the record into a fence: a write carrying an older epoch can be rejected even while its process is still alive.
None of this is a transaction across keys. The guarantee is per object. A lock on the state key says nothing about a snapshot key, an attic copy or a second root's state, which is why recovery writes need their own serialization.
Name the layers before testing any of them. A rejection proves acquisition. A named holder proves identity was stored. A takeover after a proven-dead holder proves the expiry policy. None of the three proves the resumed writer is fenced.
Figure 1 separates the documented request from the protocol steps that have to be earned by observation.
%%{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
A["Create-once put
If-None-Match: *"] --> B{"Key absent at
commit time?"}
B -->|"yes"| C["One winner
holds the lock"]
B -->|"no, or lost the race"| D["412 PreconditionFailed
second writer refused"]
C --> E["Lock object records
ID, who, operation, created"]
E --> F{"Holder still alive?"}
F -->|"yes"| G["Wait, or stop and coordinate"]
F -->|"no"| H["force-unlock with the lock ID"]
H --> I["Next writer acquires"]
C --> J["State write at end of run
not conditional on the lock"]
H -.->|"paused holder resumes"| J
J --> K["Last completed write wins"]
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 A,B,C primary;
class E,H,I secondary;
class G warn;
class D,K danger;
The dashed edge is the whole problem: a holder that was declared dead is not a holder that stopped running. Figure 2 redraws the same protocol as layers, so the boundary is visible rather than implied.
This is the difference between a compatibility note and a protocol claim. "R2 supports conditional writes" is true and insufficient. "This client, on this endpoint, refused a second writer and survived an interrupted first writer" is a claim someone can review.
Run Two Independent Clients Against One State Key
The test needs four clients, not two. A and B prove rejection; C and D prove what happens when a holder is interrupted rather than cooperative. All of them use the same bucket, key and workspace, because a test on a different key answers a different question.
Pin the versions and leave nothing ambient. Terraform 1.17.1 on every host, the lockfile setting enabled in the backend file, and Cloudflare provider 5.28.1 only in the bootstrap root that created the bucket. The test root installs no provider, so a plugin download cannot explain a difference between clients.
Hold the endpoint and the credentials constant. Every client uses the same R2 access key pair against the same account host, with region = auto. Different credentials would test IAM policy, which is worth testing separately and is not this experiment.
| Test parameter | Value | Why it must match |
|---|---|---|
| Terraform CLI | 1.17.1 | Lockfile behavior follows the binary |
| Backend locking | use_lockfile = true | Opt-in; default is off |
| Bucket and key | One scratch key | Locks are scoped to one key |
| Endpoint | Same account host | A proxy can rewrite headers |
| Region | auto | Keeps client paths comparable |
| Credentials | Same key pair | Isolates locking from IAM |
| Second writer timeout | -lock-timeout=0s | Refused, not queued |
| Provider | None in the test root | No plugin in the path |
The lock timeout is the experiment's clock. Writer B runs with a zero-second timeout so the result is immediate and unambiguous. A long timeout turns a refusal into a wait, and a wait looks the same whether the backend is locked or merely slow.
Writer A has to hold long enough to observe. A scratch resource whose create sleeps for two minutes gives you a window to inspect the lock object, launch B, and record the request identifiers from each step. The sleep is the instrument, not the workload.
Give each writer a distinct identity. Two terminals on one laptop share a hostname, and the holder field then looks identical in both error blocks. Use two machines, so the printed identity separates the runs instead of decorating them.
Do not order events by wall-clock time across hosts. Two machines drift, and a container can be seconds off after a resume. Order by request identifiers and by server-side timestamps where you have them; use local timestamps only to bracket a window you already know.
Workspaces multiply the keys, and each key needs its own test. The default workspace and every named workspace resolve to different object paths, so a lock proven on one says nothing about the other. Test the key your production root actually resolves to, not the short name printed in the backend file.
Prefix-scoped credentials can pass the test and fail the release. If a key pair may create the lock object but not delete it, acquisition succeeds and the run finishes with a stale lock every time. That is why the pass condition is the object disappearing, not merely the second writer being refused.
Yesterday's stale lock looks exactly like today's live one. Age alone does not separate them; the operation and holder strings do, together with a check that the named process or runner no longer exists. Two writers, one of them a ghost, is the ordinary shape of this failure.
The delayed client is the one that changes the conclusion. Pause a third apply while it runs, clear its lock through the documented unlock path, let a fourth writer take over, then resume the third. It continues with no notification that its claim was removed, and a write from it at that point is the fencing failure the test is looking for.
Read each observation as evidence about exactly one layer. A rejection is acquisition evidence. A holder string is identity evidence. A takeover after a proven-dead process is expiry evidence. The resumed writer is the fencing test, and it is allowed to fail.
The serial is not a writer count. Two writers that both start from serial N will both publish N+1, so the surviving object cannot reveal that two writes happened. Only an external run log, or the object's last-modified time compared with your timestamps, distinguishes one writer from two.
Figure 3 shows the decision path a second writer actually walks, including the branch most runbooks leave out.
%%{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
S["Second client
plan or apply"] --> L["Create lock object
If-None-Match: *"]
L -->|"precondition failure"| E["Error acquiring the state lock
exit non-zero"]
L -->|"success"| H["Holds the lock and runs"]
E --> R{"Holder identity and age
consistent with a live run?"}
R -->|"yes"| W["Wait, or stop and coordinate"]
R -->|"no, process is gone"| F["force-unlock the recorded LOCK_ID"]
F --> H2["Successor acquires"]
H2 --> P{"Paused original
resumes?"}
P -->|"no"| OK["One state write"]
P -->|"yes"| BAD["Two state writes
last completion wins"]
H --> BAD
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 S,L,R primary;
class E,H,H2,F secondary;
class OK ok;
class W warn;
class BAD,P danger;
Write the sequence down as you go. The moment A acquires, the moment B fails, the moment the lock object disappears, and the moment the paused process resumes — each with the request identifier if there is one. A reconstruction after the fact is a narrative; a contemporaneous log is evidence.
Expect the second writer to fail fast and loudly. A refusal is the good outcome, because it arrives before any resource is touched. The dangerous result is a second writer that waits and then succeeds, which means locking was never active on that key.
A Timeout and a Later 404 Do Not Prove an Earlier Write Failed
The 404 is a statement about the read, not about the write. R2 documents it precisely: a negative read says the object did not exist when the read was processed. An earlier put whose outcome is unknown may still commit after that read returns.
That inverts the usual intuition about strong consistency. Strong consistency means you never see stale data. It does not mean the service waits for your in-flight request, and it certainly does not cancel it. The absence is current, not final.
A timeout is the client giving up, not the server stopping. The request may still be queued, mid-commit, or already committed with the response lost on the way back. "Timeout, then 404" is two observations that are entirely compatible with a successful write.
Definitive completion is one of exactly two things. A response you actually received, or a definitive error the service returned before closing the exchange. Connection reset, deadline exceeded, a killed process and a dropped TLS session are all ambiguity wearing different clothes.
Not every error code is definitive either. A precondition failure is definitive, because the service evaluated the condition and rejected the write. A server error, a reset or a gateway timeout is not, because the commit may have happened before the failure was generated.
Retries turn one write into several with one outcome. Client libraries retry on timeouts and connection errors, so a single logical acquire can produce two or three requests. What matters is the outcome of the set, and whether your log can distinguish "my own retry was refused" from "another holder exists".
Infrastructure can manufacture the ambiguity where none existed. An egress proxy with a thirty-second idle timeout will cut a connection while the write is still committing at the far end. The client then reports a transport failure, the object appears seconds later, and the timeline looks impossible unless you know the proxy exists.
| Observation | What it proves | What it does not prove |
|---|---|---|
| Precondition failure on create | The key existed at commit time | Who wrote it, or that they still hold it |
| Negative read on head or get | Absent at the moment of the read | Absent once an in-flight write commits |
| Client timeout, no response | Your client stopped waiting | The service stopped processing |
| Success response with an ETag | This write committed | A later writer has not overwritten it |
| Lock read after a timed-out delete | Present at read time | Present after that delete completes |
The clean probe is to repeat the conditional write. For the lock key, issue the same create-once put again: a precondition failure means the ambiguous write did commit, and success means it did not. One extra request converts ambiguity into a definitive answer.
Do not reuse that probe on the state object. The state key normally exists, so a create-once retry always fails and carries no information. For state, the equivalent check is content: pull the object, compare serial and lineage with the snapshot record, and hash the bytes.
Release has the same ambiguity in the other direction. A delete that timed out may still complete after you read the lock as present. If your recovery decision depends on that object being gone, confirm it after the delete has definitively finished, or treat the lock as still held.
Capture a request identifier while you still can. Cloudflare returns one on responses; when no response arrived, your client log is the only handle. An incident note without a timestamp and an identifier is a story rather than a record.
Figure 4 splits what the client observed from what the service was doing at the same instants.
The recovery rule follows from the same sentence. When the outcome of a lock acquire is unknown, do not clear a lock you cannot see and do not assume one you cannot find. Probe, then reconcile, then write.
Restore a Protected Snapshot Without Creating Duplicate Owners
A restore is a write, and it usually cannot take the lock it needs. The lock blocking recovery is the same lock the restore would acquire. That is why the recovery owner needs a path that does not depend on the failed writer's cooperation.
Stop writers before you move bytes. Quiesce every path that can reach the key: scheduled pipelines, local shells, and the -lock=false habit someone keeps for emergencies. If you cannot enumerate the writers, scope the credential down instead, because the writer you forgot is the one that overwrites you.
Snapshot the bad state before you restore the good one. The state you are about to overwrite may be the only record of resources the failed apply created. Copy it out with a checksum, name it for the incident, and treat it as evidence rather than rubbish.
Inspect the lock object rather than assuming it. If it exists and its holder is provably gone, unlock with the recorded ID. If the holder might be alive, wait or kill the process first; deleting the object under a live process is exactly how the resumed-writer problem gets created.
Restore into a new key before touching the live one. A restore target beside the live key gives you somewhere to validate that no writer is pointed at. Parse it there, list addresses, compare lineage and serial with the snapshot record, and plan against it.
| Restore target | Duplicate-owner risk | Use when |
|---|---|---|
| Same key after an unlock | High if the old holder resumes | The holder is proven dead |
| New key, then one push | Low, a single final write | Default incident path |
| Second bucket | Low, but leaves two addresses | Account or jurisdiction failure |
| Live write with locking disabled | Highest, no serialization | Never |
A plan is not a read-only operation on this backend. Planning acquires the lock and can persist refreshed state, so running one outside the controlled window puts a writer back into the system while you are measuring it. Plan after quiescing, not before.
Only the authoritative key receives the final write. When the restored file is proven, push it to the live key and immediately plan again. A restore that ends at a successful push with no no-change plan is unfinished, because the push proves transport and not ownership.
Duplicate owners come from two addressable states. If the old key still exists and something still reads it, two roots can believe they own the same resources. Retire it deliberately: copy it to an attic prefix, record the checksum, and remove write access rather than leaving it in place "just in case".
Write the owner down where the next engineer will look. A short register naming the authoritative key, the retired keys, the snapshot store and the recovery owner turns a memory into a document. The register belongs beside the runbook, not inside the state it describes.
Lineage is the guard you already have. Pushing a state file whose lineage differs from the destination is refused. That refusal is a control; forcing past it converts a detected mismatch into an undetected duplicate estate.
Validate against remote reality, not the file. The snapshot claims a set of resources. A plan run inside the controlled window shows whether those objects still exist and still match. A file that parses perfectly can describe an estate that has moved on.
Duplicate owners are detectable before the first apply. List the addresses in the restored file and compare the identity of each remote object with what the provider reports. A state that names an object the remote no longer has, and two states that name the same remote object, are both visible before anything is written.
Figure 5 shows the ownership difference between restoring beside the live key and restoring over it.
One write, one owner, one plan. That is the whole acceptance test for a restore, and it is also the shortest description of what the incident runbook is protecting.
Write a Backend Acceptance Record with Explicit Limits
An acceptance record is a claim with a boundary drawn around it. It names the client, the endpoint, the flags and the failure that was actually observed, then names what was not tested. "R2 locking works" is not reviewable; "1.17.1 refused a second writer on this key" is.
Approve the path you exercised, not the product. Two hosts, one key, lockfile enabled, one interrupted holder. That is a real result and a narrow one, and the narrowness is the point: it says nothing about an older CLI, a workspace layout, or a proxy that rewrites headers.
| Field | Example value | Why it bounds the claim |
|---|---|---|
| Client | Terraform 1.17.1 | Lockfile behavior follows the binary |
| Backend flags | lockfile on, skip flags recorded | A missing skip changes the call path |
| Endpoint and region | Account host, auto | A proxy or alias is a different path |
| Credential scope | One key, state prefix only | Wider credentials add writers |
| Test key | One scratch key | Locks do not span keys |
| Observed failure | Precondition failure, non-zero exit | The actual event, not the intent |
| Untested | Old CLIs, workspaces, other clients | The honest remainder |
Write the untested column before the incident. Nobody wants to discover during recovery that the accepted configuration excluded the path they now need. The limits are more useful than the approval, because they tell the next engineer when to stop trusting the record.
Re-test when any field in the table changes. A CLI upgrade, a new egress proxy, another jurisdiction, or a move from one key to workspaces all change the path. Add a row; do not amend the old one, because the old result was true for the old path.
Record the expiry policy and the unlock authority as fields of their own. Who may clear a lock, on what evidence, and how long a run may hold one before it is investigated. Those are policy decisions an incident needs immediately, and none of them live in the backend file.
Keep the evidence beside the record and redact it. The error block, the sequence of events, the snapshot checksum and the lineage pair are enough to reconstruct the test. Account identifiers and key material are not part of the claim.
Give the record an expiry date and a review trigger. An acceptance note with no date quietly becomes an assumption. Re-open it when the CLI, the endpoint or the network path changes, and archive it rather than editing history when the answer moves.
The card below is the trace to run, and the fields to keep, in the order that produces usable evidence.
Qualify the state protocol
Status: scratch account, no production state. Four clients and one key. The output is a signed acceptance record with an explicit untested list, not a claim that the backend is generally safe.
Prerequisites. Terraform 1.17.1 on every host; one R2 access key limited to the scratch prefix; the account host and region = auto in a backend file; lockfile enabled; Cloudflare provider 5.28.1 only in the separate bootstrap root.
| # | Do | Pass condition |
|---|---|---|
| 1 | Create the scratch bucket and one test key under a lab prefix | Private bucket, one key, no other writers |
| 2 | Init every client against that key | Same endpoint, same flags, no provider installed |
| 3 | Client A applies a resource whose create sleeps for two minutes | Lock object present, A named as holder |
| 4 | Client B plans with a zero lock timeout during the sleep | Non-zero exit with a lock error naming A |
| 5 | Pause client C mid-run, unlock with the recorded ID, start D | D acquires and completes |
| 6 | Resume C and let it finish | Note whether C writes state after D — this is the fencing result |
| 7 | Restore the pre-test snapshot into a restore key, then push once | Lineage matches, plan proposes no changes |
| 8 | Retire the old key and confirm no writer still reads it | One addressable state, one owner |
Expected observations. B is refused before it produces a plan. The lock block names a path, operation, holder and creation time. After the resume in step 6, the serial alone cannot say which writer landed, so compare the object's last-modified time with the run logs. Step 7 ends with a no-change plan, not merely a successful push.
Failure checks. The run fails if B waits and then succeeds, because locking was off. It fails if the 404 after a timed-out acquire is treated as proof the acquire failed. It fails if step 6 shows a resumed writer overwriting a successor and the record still claims the protocol is fenced.
Record explicitly. Client version, backend flags, endpoint, credential scope, test key, the observed failure, and the untested list from the table above. Attach the lock error block, the four timestamps, the request identifiers, the snapshot checksum and the lineage pair.
Cleanup. Destroy the scratch root, delete the lab prefix, then the bucket. Confirm the state object, the lock object and the restore key are all gone, and revoke the test credential.