Prevent lost updates with HTTP If-Match
Use a strong ETag, a conditional SQLite update, and a 412 response to protect a saved change when two clients edit the same record.
In this article
One preference is open on two devices
A notification digest is scheduled for 09:00. The user opens its settings on a laptop and a phone, and both devices read version 7. The laptop saves 11:00. The phone still displays the original form. If the phone can save 15:00 using only the record ID, its request can silently erase the newer decision. Both devices report success even though the user never saw the conflict. This is a lost update. The service needs to know which representation the client saw when preparing the request. These writes can be hours apart. A forgotten browser tab or a mobile request buffered during a connection interruption can produce the same sequence. The rule for this setting is to preserve an accepted change until the difference has been reviewed.
Carry a strong ETag from the read to the write
The GET response includes JSON and ETag: "7". The client preserves the quotes and sends the value as If-Match: "7" with its update. RFC 9110 defines strong comparison for If-Match. Weak validators have the W/ prefix and do not match under strong comparison. Each version in this example maps to exactly one deterministic JSON representation. Every change that affects it advances the version. If language, content coding, or a field selection gives one resource version several byte representations, the strong tags need to account for that variation. A version column alone does not establish this property. Treat the tag as opaque in client code. A general HTTP implementation supports the specification’s list and wildcard forms according to their semantics.
Compare and update in a single SQL statement
A SELECT followed by an unconditional UPDATE leaves an opening for another writer between the two statements. Put the record ID and expected version in the UPDATE predicate. SQLite changes the hour and increments the version in that same statement. RETURNING supplies the values from the affected row. A missing row means the version was stale in this fixture because the record is preloaded and cannot be deleted by another test. A real endpoint checks authentication, authorization, and payload validity before evaluating HTTP preconditions. Avoid revealing the existence or version of records callers cannot see. Keep related writes and durable outbox items in the same database transaction, and report success after it commits. Administrative writers must advance the version whenever they change the representation.
import sqlite3
from contextlib import closing
with closing(sqlite3.connect(":memory:")) as db:
db.executescript("""
CREATE TABLE preferences (
id INTEGER PRIMARY KEY,
digest_hour INTEGER NOT NULL CHECK (digest_hour BETWEEN 0 AND 23),
version INTEGER NOT NULL
);
INSERT INTO preferences VALUES (42, 9, 7);
""")
def read():
return db.execute(
"SELECT digest_hour, version FROM preferences WHERE id = 42"
).fetchone()
def write(hour, expected):
with db:
return db.execute(
"""
UPDATE preferences
SET digest_hour = ?, version = version + 1
WHERE id = 42 AND version = ?
RETURNING digest_hour, version
""",
(hour, expected),
).fetchone()
alice = read()
bob = read()
assert alice == bob == (9, 7)
assert write(11, alice[1]) == (11, 8)
assert write(15, bob[1]) is None
assert read() == (11, 8)
assert write(15, read()[1]) == (15, 9)
print("11:00 v8 -> stale update rejected -> 15:00 v9")
Let a 412 keep the draft visible
The laptop sends "7", succeeds, and leaves version 8. The phone’s stale tag fails with 412 Precondition Failed. It can fetch the latest value, display the stored 11:00 alongside the draft 15:00, and let the user choose whether to submit against "8". Automatically fetching a new tag and replaying the old body would bring back the lost update. A service that requires a conditional header can respond with 428 Precondition Required when that header is absent. An invalid hour still receives its own validation response. RFC 9110 also restricts when a successful PUT response can include a validator after transforming the representation. In this flow a fresh GET supplies the saved representation and its tag, including any values normalized by the service.
Read the SQLite fixture’s expected result
The in-memory Python fixture starts with the hour 9 and version 7. Both readers see those values. The first write returns hour 11 and version 8. The stale UPDATE returns no row, and the next read proves the hour is still 11. The reviewed retry against version 8 applies 15:00 and leaves version 9. The fixture isolates the persistence behavior without opening a network port. At the HTTP layer, send two concurrent updates carrying the same starting tag. Either may win. Assert that one succeeds, the other receives 412, the version increments once, and the stored value came from the successful request. Add separate cases for a missing header, a malformed validator, and an unauthorized caller. Each should leave the stored values untouched.
Treat timeouts and side effects as separate cases
A timeout may mean the transaction committed and the response was lost. If an old tag now returns 412, read the current representation and compare it with the user’s intent before attempting another write. Seeing the intended hour does not always identify which request saved it. Email delivery and other work outside the database can use a durable operation ID and delivery state to avoid duplicates. A conditional request guards the resource from updates based on an obsolete representation. It does not identify an operation across separate systems. Track 412 and 428 responses by endpoint. A request identifier and, where appropriate, an observed version can explain the sequence without logging private preferences or authorization headers. An interface that retains the draft completes the recovery path.
Reader discussion
Which alternative architecture would you try for the same problem?
No comments yet. Be the first to contribute.
Write a comment