PREP WITH PROOF
Menu
PROGRAMMING & APIS / PRACTICAL GUIDE

HTTP If-Match and ETag: Prevent Lost Updates with Optimistic Concurrency

Prevent stale API writes with If-Match, strong ETags and atomic comparison. Understand 412 versus 428 and run a Python lab with 100 racing-writer scenarios.

THE QUICK ANSWER

Save the ETag with the document snapshot and send it in If-Match when replacing that document. The origin compares strong validators before applying the write; a stale condition normally returns 412 without changing the resource. The comparison and storage mutation must share an atomic boundary. An API that requires a condition can use 428 when it is missing.

The overwrite that a successful save can hide

Alice and Bob open the same document. Alice changes its title and saves. Bob, still editing the original copy, changes its description and sends the entire document back. If the server accepts both replacements unconditionally, Bob can erase Alice’s title even though both clients saw a successful response. The problem is an update based on an obsolete snapshot.

An editor needs a condition that travels with its saved snapshot: apply this replacement only if the server still has the version I read. The important result is that a stale write changes nothing and the client retains enough information to resolve the conflict. A successful request count alone cannot demonstrate that this contract holds.

This guide develops that write contract through an original executable model. It complements the existing ETag and HTTP 304 guide, which covers reuse of cached GET responses. Here the goal is protecting changes to shared data. The local lab exercises the comparison and mutation boundary without pretending to be a complete HTTP server.

Carry the validator from the read into the write

In a typical exchange, a GET returns document bytes and an ETag. The editor stores the body and tag together. Its later replacement sends the saved tag in If-Match. RFC 9110 requires strong comparison for this condition; a false condition normally yields 412 without applying the method. A list succeeds if any strong member matches; * checks whether a current representation exists.

The following is an illustrative exchange, not output from the local lab. Alice and Bob initially receive the same tag. After Alice’s replacement changes the current version, Bob’s saved condition no longer matches. The response tells Bob’s client to preserve the unsaved draft and begin conflict recovery rather than report a completed save.

GET /documents/42 HTTP/1.1
Host: api.example.test

HTTP/1.1 200 OK
ETag: "doc-7"
Content-Type: application/json

{"title":"Original","description":"Initial"}

PUT /documents/42 HTTP/1.1
Host: api.example.test
If-Match: "doc-7"
Content-Type: application/json
Content-Length: 48

{"title":"Alice update","description":"Initial"}

HTTP/1.1 204 No Content

# Bob subsequently submits a different replacement with the old tag:
# If-Match: "doc-7"
# Expected normal conflict path: 412 Precondition Failed.

Source: RFC 9110: If-Match and precondition evaluation ↗

Do not confuse a missing condition with a failed condition

An API can require conditional writes and use 428 Precondition Required when the caller omits the required precondition. RFC 6585 says the response should explain how to resubmit and must not be stored by a cache. This is an endpoint policy decision: the presence of ETag on reads does not automatically make every write conditional.

For this tutorial, an omitted condition returns 428 and a supplied nonmatching condition returns 412. The model always rejects a failed condition; it does not attempt the RFC’s optional recognition of an already-applied operation. These choices keep the demonstrated stale-write behavior deterministic and make the application’s expectations visible.

A generic conflict label can hide useful distinctions. Keep the response shape and client handling specific enough to separate a stale snapshot from an invalid business transition, such as trying to close an already finalized invoice. The conflict-resolution interface needs to know whether to fetch a new snapshot, correct the submitted data or stop the operation.

Case in the labResultWhat remains true
Matching strong tag204Replacement is applied; revision advances
Stale or weak tag only412Existing bytes and revision remain intact
Missing required condition428No replacement is applied
Tag list containing a current strong tag204Any matching strong member is sufficient
* for an existing document204Only existence was checked
* for an absent document412This model does not create the document

Source: RFC 6585: 428 Precondition Required ↗

Choose a condition that protects the intended assumption

A wildcard is a poor substitute for the specific version saved by an editor. In the lab, * still permits a replacement after another writer changed the document because the document continues to exist. Use that outcome to review the actual assumption: “this resource exists” is weaker than “my snapshot is still current.”

A tag also belongs to the representation and resource for which the server issued it. Keep it attached to the exact document snapshot in client state. Do not let a global “last ETag” variable drift between tabs, accounts or document identifiers. Even when two resources happen to return identical token text, the application must still select and authorize the correct target.

The model uses revision tokens rather than hashes of the body. Its A-to-B-to-A test returns to the initial bytes while retaining a new revision token, so an old editor is rejected. That is a useful application choice for detecting intervening saves. It does not imply that every valid ETag implementation must use monotonically increasing revisions or expose revision numbers to clients.

Put comparison and mutation in the same storage boundary

The central implementation question is where the condition is checked. A handler that reads the revision, releases its database transaction, and later writes the body has a gap. Two requests can both pass the earlier comparison before either write becomes visible. Merely adding If-Match parsing to that handler would leave the lost-update defect intact.

The lab holds one lock across the existence check, strong-tag comparison, replacement and revision increment. A read takes the same lock while collecting its body and tag. This makes the snapshot and compare-and-replace operations coherent within the single Document object. The test does not rely on thread scheduling order or on a particular writer winning.

For persistent storage, translate that boundary into a supported database conditional mutation or transaction. One common design updates the row only when both its identifier and expected revision match, advances the revision in the same operation, and checks the affected-row result. The exact implementation must also preserve authorization and constraints. A process-local lock does not coordinate separate worker processes or hosts.

Keep unrelated network work out of that critical section. If a successful save must emit an event or trigger a downstream operation, design how the committed change and that side effect are reconciled. This small model deliberately has no side effects, transaction log, crash recovery or distributed coordination.

Run the comparison and racing-writer lab

Save the complete example as if_match_lab.py and run python if_match_lab.py with Python 3.12. It uses immutable bytes, already-parsed Tag objects and a lock. The integer return values model application outcomes; no HTTP requests are issued. Header parsing, framework integration and response serialization remain separate responsibilities.

The exact published example passed 418 checks on Python 3.12.14, including 100 two-writer races. Each race starts two workers from the same snapshot and checks that exactly one replacement succeeds, the stored bytes belong to that winner, the revision advances once and replaying the old tag fails. A barrier aligns the starting point without assuming which worker acquires the lock first.

The earlier assertions cover sequential stale writes, weak tags, multiple tag candidates, required conditions, wildcard existence and absent documents. The absent-document case is deliberately a replacement-policy fixture, not a complete endpoint status-selection algorithm. A real handler must first perform its normal routing, authentication and other applicable request checks.

from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from threading import Barrier, Lock
import sys

@dataclass(frozen=True)
class Tag:
    opaque: str
    weak: bool = False

class Document:
    # Application model, not an HTTP handler or header parser.
    # Inputs are trusted, already-parsed tags and immutable bytes.
    def __init__(self, body=b'initial'):
        self.lock = Lock()
        self.body = body
        self.revision = 1

    def current_tag(self):
        # Called only while holding self.lock.
        return Tag(f'doc-{self.revision}')

    def read(self):
        with self.lock:
            tag = None if self.body is None else self.current_tag()
            return self.body, tag

    def replace(self, body, condition):
        # condition: None, '*', or a tuple of parsed Tag objects.
        # A missing condition is rejected by this application's policy.
        with self.lock:
            if condition is None:
                return 428
            exists = self.body is not None
            if condition == '*':
                matched = exists
            else:
                current = self.current_tag()
                matched = exists and any(
                    not tag.weak and tag.opaque == current.opaque
                    for tag in condition
                )
            if not matched:
                return 412
            # Comparison and mutation share one critical section.
            self.body = body
            self.revision += 1
            return 204

checks = 0

def check(value):
    global checks
    assert value
    checks += 1

# Two editors read the same version, then submit different replacements.
doc = Document()
original, saved = doc.read()
check(doc.replace(b'Alice edit', (saved,)) == 204)
check(doc.replace(b'Bob stale edit', (saved,)) == 412)
check(doc.read()[0] == b'Alice edit')
current = doc.read()[1]
check(current != saved)
# Weak tags cannot satisfy strong comparison, even with identical opaque text.
check(doc.replace(b'weak edit', (Tag(current.opaque, weak=True),)) == 412)
check(doc.read()[0] == b'Alice edit')
# Any matching strong member is enough; an unrelated member is harmless.
check(doc.replace(b'list edit', (Tag('other'), current)) == 204)
check(doc.replace(b'no condition', None) == 428)
check(doc.read()[0] == b'list edit')
# '*' tests existence, so it does not protect a previously read version.
check(doc.replace(b'wildcard edit', '*') == 204)
check(doc.read()[0] == b'wildcard edit')
# Model an absent document separately; this lab never creates via replace.
missing = Document(body=None)
check(missing.replace(b'create?', '*') == 412)
check(missing.replace(b'create?', (Tag('doc-1'),)) == 412)
check(missing.read() == (None, None))
# Content returning to an earlier value does not reuse an old revision token.
aba = Document(b'A')
_, token_a = aba.read()
check(aba.replace(b'B', (token_a,)) == 204)
check(aba.replace(b'A', (aba.read()[1],)) == 204)
check(aba.read()[1] != token_a)
check(aba.replace(b'old editor', (token_a,)) == 412)
# Racing writers start from one snapshot. Do not assume which thread wins.
with ThreadPoolExecutor(max_workers=2) as pool:
    for n in range(100):
        race = Document()
        _, token = race.read()
        gate = Barrier(2)
        def attempt(payload):
            gate.wait(timeout=5)
            return race.replace(payload, (token,))
        payloads = (f'A-{n}'.encode(), f'B-{n}'.encode())
        jobs = [pool.submit(attempt, value) for value in payloads]
        statuses = [job.result(timeout=10) for job in jobs]
        check(sorted(statuses) == [204, 412])
        winner = statuses.index(204)
        check(race.read()[0] == payloads[winner])
        check(race.revision == 2)
        check(race.replace(b'replay', (token,)) == 412)
print(f'PASS: {checks} checks; 100 two-writer races; Python {sys.version.split()[0]}')

Recover a draft without quietly overriding another writer

After a stale-write response, preserve the attempted draft and its original base snapshot. Fetch the current authorized representation. A useful editor can then show the original, the current server version and the local draft. Differences against the common base give the user or merge logic a way to see which fields changed on each side.

If the user accepts a merged document, submit it with the tag from the newly fetched version. Another writer might save during the merge, so a second failure is possible and should preserve the draft again. Avoid a recovery shortcut that fetches a fresh tag and resubmits the unchanged stale replacement automatically: that can approve the very overwrite the condition was meant to prevent.

For an ambiguous network failure, do not infer whether the write committed solely from the missing response. The server might have applied it before the connection failed. Retrieve current state or use the endpoint’s documented operation-reconciliation mechanism. A stale validator and an idempotency key solve different problems; neither should be treated as a universal substitute for the other.

Verify the HTTP integration after the model

The model is a starting point for an integration checklist, not evidence that a deployed API behaves correctly. Through the actual serving route, verify that read responses pair the expected body with its validator, conditional writes reach the origin, rejected writes leave stored state intact and clients retain unsaved input. Include the same two-editor scenario with a real database and multiple workers.

Let a standards-aware HTTP layer parse entity-tag syntax, quoting, weak indicators and tag lists. The Python tuple in this lab is an internal representation, not a recipe to split an If-Match header on commas. Also test representation variants, access-control failures, malformed headers and missing resources according to the full endpoint contract. None of those wire-level behaviors is exercised by this in-memory test.

If the server transforms a PUT body before storing it, review RFC 9110’s restrictions on returning validators in the successful PUT response. Do not assume a token from an illustrative exchange is automatically safe to reuse for every transformed representation. Fetching the current representation is a clear recovery step when the endpoint does not provide a usable new validator.

A dependable conditional-write feature joins three decisions: which snapshot the client meant, whether storage still satisfies that condition and how the editor recovers when it does not. Preserve those distinctions in tests and user-facing save behavior. Then a rejected stale save becomes a recoverable editing event instead of a silent loss of somebody else’s work.

KEEP THESE THREE THINGS

Your next steps

  1. Pair the validator with the exact document snapshot and target resource.
  2. Use an atomic comparison and mutation; checking before a later unconditional write leaves a race.
  3. Preserve the draft on 412, fetch current state and merge deliberately.
  4. A wildcard checks existence; it does not protect the version an editor read.

Sources & official resources

Linked resources checked on 2026-11-03. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →