← Back to FastAPI, page 5

fastapi-0087 · Hard senior

How do you prevent lost updates in a FastAPI REST API using ETags, If-Match and optimistic locking?

Return an ETag that identifies the current version of a resource (for example from a version column). Require clients to send it back as If-Match on PUT or PATCH. If the header is missing answer 428 Precondition Required, if it does not match answer 412 Precondition Failed, and enforce the check atomically with a version column (UPDATE ... WHERE id = ? AND version = ?) so concurrent writers cannot both win. This stops one user's edit from silently overwriting another's.

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/7 returns the body and ETag: "3" (the strong validator, quoted). The version can be an integer column, a row hash, or xmin in PostgreSQL.
  • PUT /students/7 must send If-Match: "3". No header: 428 Precondition Required. Stale value: 412 Precondition Failed (the client re-fetches and merges). Success returns the new ETag: "4".
  • If-None-Match on GET enables cache validation: if the ETag matches, return 304 Not Modified with 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} adds WHERE version = :old to UPDATE and raises StaleDataError when 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=:v and check rowcount.

Design points:

  • Use strong ETags for writes (weak W/ tags are not valid for If-Match comparison, per RFC 9110).
  • A response model should not expose internal columns, but may include version too 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