Full answer
The lost update problem: user A and user B both read a record, edit, and PUT; the later write overwrites the earlier one without either noticing.
Protocol:
GET /students/7returns the body andETag: "3"(the strong validator, quoted). The version can be an integer column, a row hash, orxminin PostgreSQL.PUT /students/7must sendIf-Match: "3". No header:428 Precondition Required. Stale value:412 Precondition Failed(the client re-fetches and merges). Success returns the newETag: "4".If-None-Matchon GET enables cache validation: if the ETag matches, return304 Not Modifiedwith no body.
Atomic enforcement: comparing the header to the current value in Python is a race (check-then-act). Make the database enforce it:
- SQLAlchemy
__mapper_args__ = {"version_id_col": version}addsWHERE version = :oldto UPDATE and raisesStaleDataErrorwhen no row matches. Catch it and return 412 (or 409). - Raw SQL:
UPDATE student SET name=:n, version=version+1 WHERE id=:id AND version=:vand checkrowcount.
Design points:
- Use strong ETags for writes (weak
W/tags are not valid forIf-Matchcomparison, per RFC 9110). - A response model should not expose internal columns, but may include
versiontoo for clients that cannot read headers; the header is still the standard path. - Compare ETags exactly including quotes, and support lists (
If-Match: "3", "4") and*only if you mean it. - Document 412 and 428 in OpenAPI
responses. - PATCH with JSON Merge Patch benefits as well.
- Pessimistic locking (
SELECT FOR UPDATE) is better for short critical sections inside one transaction; optimistic locking suits user-edit flows spread over minutes.
Test with two sessions: both load, the first commits, the second must fail with 412.
python
import tempfile
from pathlib import Path
from typing import Annotated
from fastapi import FastAPI, Header, HTTPException, Response
from fastapi.testclient import TestClient
from pydantic import BaseModel
from sqlalchemy import create_engine
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column
from sqlalchemy.orm.exc import StaleDataError
class Base(DeclarativeBase):
pass
class Student(Base):
__tablename__ = "student"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str]
version: Mapped[int] = mapped_column(default=1)
__mapper_args__ = {"version_id_col": version}
engine = create_engine(f"sqlite:///{Path(tempfile.mkdtemp()) / 'db.sqlite'}")
Base.metadata.create_all(engine)
with Session(engine) as s:
s.add(Student(name="Asha"))
s.commit()
app = FastAPI()
class StudentIn(BaseModel):
name: str
@app.get("/students/{sid}")
def read(sid: int, response: Response):
with Session(engine) as db:
st = db.get(Student, sid)
response.headers["ETag"] = f'"{st.version}"'
return {"id": st.id, "name": st.name}
@app.put("/students/{sid}")
def update(sid: int, body: StudentIn, response: Response, if_match: Annotated[str | None, Header()] = None):
if if_match is None:
raise HTTPException(428, "If-Match header required")
expected = int(if_match.strip('"'))
with Session(engine) as db:
st = db.get(Student, sid)
if st.version != expected:
raise HTTPException(412, "Resource changed; fetch it again")
st.name = body.name
try:
db.commit() # UPDATE ... WHERE version = :old
except StaleDataError:
raise HTTPException(412, "Concurrent update detected")
response.headers["ETag"] = f'"{st.version}"'
return {"id": st.id, "name": st.name}
c = TestClient(app)
etag = c.get("/students/1").headers["etag"]
print("etag:", etag)
print("no header:", c.put("/students/1", json={"name": "A1"}).status_code)
ok = c.put("/students/1", json={"name": "Asha R"}, headers={"If-Match": etag})
print("fresh:", ok.status_code, ok.headers["etag"])
print("stale:", c.put("/students/1", json={"name": "Lost"}, headers={"If-Match": etag}).status_code)
# the database catches a race the Python check cannot
a, b = Session(engine), Session(engine)
sa, sb = a.get(Student, 1), b.get(Student, 1)
sa.name, sb.name = "from A", "from B"
a.commit()
try:
b.commit()
except StaleDataError:
print("second writer stopped by version_id_col")
b.rollback()
a.close()
b.close()
Standalone script. Run it with `python file.py`; it uses a temporary SQLite file and TestClient. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): etag: "1" no header: 428 fresh: 200 "2" stale: 412 second writer stopped by version_id_col
Key points
- ETag carries the version; If-Match returns it on writes
- 428 when missing, 412 when stale
- Enforce atomically with a version column, not a Python check
- Use strong ETags for If-Match; weak ones are invalid there
- If-None-Match gives cache validation with 304
Common mistakes
- Checking the version in Python only, which leaves a race window
- Using weak ETags with If-Match
- Returning 409 or silently overwriting instead of 412 and 428
- Not documenting the headers in OpenAPI
- Ignoring that PATCH needs the same protection
Follow-ups
- How do ETags help caching with If-None-Match?
- When is pessimistic locking a better fit?
- How would you use PostgreSQL xmin as a version?
Tips
- Describe 428 and 412
- Name the database enforcement
- Mention strong vs weak ETags