Conditional Requests & Idempotency Keys
The same validators that speed up reads also make writes safer. Two patterns handle the hard cases: concurrent edits and retried creates.
Optimistic concurrency with If-Match
Section titled “Optimistic concurrency with If-Match”When two clients edit the same resource, the second can unknowingly overwrite the first — the “lost update” problem. Conditional writes prevent it: the client sends the ETag it last saw in If-Match, and the server applies the change only if the resource still matches. If it has changed, the server returns 412 Precondition Failed:
sequenceDiagram
participant A as Client A
participant S as Server
A->>S: PUT /articles/42 (If-Match: "v7")
alt still "v7"
S-->>A: 200 OK (now "v8")
else changed to "v8"
S-->>A: 412 Precondition Failed
end The client then re-fetches, reapplies its change on the current version, and retries — no silent overwrite.
Idempotency keys for POST
Section titled “Idempotency keys for POST”Recall that POST is not idempotent, so a retried create can duplicate. An idempotency key fixes this: the client generates a unique key and sends it with the request; the server stores the result against that key and returns the same result for any repeat.
A common convention is an Idempotency-Key request header; the server keeps the mapping for a window (say 24 hours) so retries within that window are safe.