Free Python developer course
Go from your first line of code to working as a Python developer: projects, testing, data, databases, web apps and APIs, all in your browser.
CRUD endpoints on SQLite, with safe concurrent updates.
Why can two valid writes still leave the wrong database state?
A read followed by a separate write can use stale information. An atomic update or a transaction makes the database apply the intended state change safely.
Two requests increment a stored value of 7
Each executes UPDATE with value = value + 1
The stored value reaches 9
Two requests increment a stored value of 7
Each executes UPDATE with value = value + 1
The stored value reaches 9
Given Two requests increment a stored value of 7 and The stored value reaches 9, write down the missing step that connects them.
Each executes UPDATE with value = value + 1
Now take Each executes UPDATE with value = value + 1 and the result above. Write an input and an implementation that could produce this trace.
Two requests increment a stored value of 7. Check that your implementation produces the result shown above.
What might happen if both handlers first read 7 and later write 8?
The final value can be 8, losing one update. The fixed version computes the increment against the database's current value.
Check this when debugging. Building UPDATE column names from request keys.
Real APIs keep their data in a database, and many users change it at once. That's where the subtle bugs live. Two people edit the same record and one change silently disappears. A PATCH lets a user set a field they shouldn't. A duplicate slips past a check. This lesson connects the REST design from Designing a REST API to the SQL from Phase 7, and adds the techniques that keep shared data correct.
The second save quietly overwrites the first admin's change
Each admin wrote back the whole record as they last saw it, so the second save erased the first change: a lost update. A version number checked on save turns it into a clear conflict instead.
This rests on Designing a REST API, where PUT was idempotent and a stale write needed a precondition, and on Databases and SQL, where values went into a query through placeholders.
Think of a library's front desk. Visitors ask the librarian for a book, and only the librarian goes into the stacks. A repository class does that job in your code, using the pattern from the design lesson. Handlers ask it for things, and all the SQL lives inside it. Each REST operation maps onto one SQL statement:
| request | repository method | SQL | success |
|---|---|---|---|
POST /campaigns | create(...) | INSERT | 201 + Location |
GET /campaigns/{id} | get(id) | SELECT ... WHERE id = ? | 200, or 404 |
PATCH /campaigns/{id} | update(id, changes) | UPDATE ... SET ... WHERE id = ? | 200, or 404 |
DELETE /campaigns/{id} | delete(id) | DELETE ... WHERE id = ? | 204, or 404 |
Handlers stay short: parse and validate, call the repository, turn the result into a response. Database rules become status codes too. A UNIQUE constraint failing on a duplicate email becomes 409 Conflict, not a 500.
UNIQUE constraint fails on a duplicate email. Which status should the API answer?409 Conflict
The request clashes with what is already stored. That is the client's to fix, so it gets a 4xx that says why.
Ada and Lin both open campaign 7, budget 500. Ada changes the name and saves. Lin, looking at an older copy, changes the budget and saves the whole record. Lin's save writes back the old name. Ada's change has vanished, and nobody got an error. That's a lost update, and with many users it happens every day.
Think of a shared recipe card with a version number in the corner. Before you write your changes on it, you check the number is still the one you read. If it's gone up, someone has changed the card, and you read it again first.
In a database, give each row a version number that goes up on every change. A client says which version it started from, and the update only applies if that's still the current one:
UPDATE campaigns SET budget = ?, version = version + 1 WHERE id = ? AND version = ?
If someone else saved in between, the version no longer matches and no rows change. The API reports a conflict, and the client reloads and tries again. It's called optimistic because it assumes conflicts are rare and only checks at save time, instead of locking the record while someone edits it.
WHERE id = 7 AND version = 3. What happens?No rows change, so the API reports a conflict
The version no longer matches, so the UPDATE finds no row to change. That's the signal of a conflict: Lin reloads the new version and tries again, and Ada's change survives.
HTTP has headers for exactly this. A GET response carries an ETag, a short tag for this version of the resource, such as "7-3". To update, the client sends it back in an If-Match header, which means "only do this if it's still that version":
ETags help reads too. A client sends If-None-Match with the ETag it has, meaning "only send it if it's changed". If nothing changed, the server answers 304 Not Modified with no body, which saves bandwidth.
No locks: each update checks the version its author read.
If-Match: "7-3", but the campaign is now at version 4. What should the API answer?412 Precondition Failed
The client's copy is out of date. 412 tells it to fetch the latest version and try again.
Write a sentence or two, then compare it with a good answer in the lesson.
A PATCH sends only the fields to change, so the UPDATE has to be built from whichever keys arrive. Values always go in placeholders. Column names can't be placeholders, because they are part of the statement itself, so they must come from your own fixed list and never straight from the request.
Picture a form where staff may change your address, but not your account balance. PATCH needs the same rule. It sends only the fields to change, such as {"budget": 750}, so the UPDATE statement has to be built from whichever keys arrive.
Values always go in placeholders, the ? marks that keep data apart from the SQL. But column names can't be placeholders, because they're part of the statement itself. So they must come from your own fixed list, an allowlist, and never straight from the request. Otherwise a client could send {"is_admin": 1}, or a key containing SQL.
The lesson runs this once, before its first cell, and every cell, drill and example starts with what it defines. A cell that changes a setup object changes it for the cells after it, until the page reloads.
import requests BASE = "https://api.gradient.test"
EDITABLE = {"name", "budget", "status"} # the allowlist
def build_update(changes):
unknown = set(changes) - EDITABLE
if unknown:
raise ValueError(f"can't change: {', '.join(sorted(unknown))}")
columns = sorted(changes) # sorted, so the SQL is predictable
assignments = ", ".join(f"{col} = ?" for col in columns)
return f"UPDATE campaigns SET {assignments} WHERE id = ?", [
changes[c] for c in columns
]
print(build_update({"budget": 750, "status": "active"}))
try:
build_update({"budget": 750, "owner_id": 1})
except ValueError as err:
print("rejected:", err)The column names in the SQL come only from EDITABLE, which you wrote; the values travel separately. Allowlisting also stops mass assignment: a client quietly setting fields such as role or price_paid that it was never meant to touch.
UPDATE campaigns SET ? = ? WHERE id = ? and pass the column name as a placeholder?Placeholders only stand for values, not names of columns or tables
The database plans the query before it sees the values, so names must be in the SQL itself. That's why they must come from an allowlist you control.
The cell builds an update the careless way, by pasting each key from the request into the statement. A client sends a key that is not a column name but a piece of SQL, and the statement does more than the client was allowed to ask.
Uses the setup above, 3 lines.
import sqlite3 db = sqlite3.connect(":memory:") db.execute("CREATE TABLE campaigns (id INTEGER PRIMARY KEY, budget REAL, owner TEXT)") db.execute("INSERT INTO campaigns VALUES (1, 500, 'ada')") def naive_update(changes): sets = ", ".join(f"{key} = ?" for key in changes) db.execute(f"UPDATE campaigns SET {sets} WHERE id = 1", list(changes.values())) naive_update({"budget": 750}) print(db.execute("SELECT budget, owner FROM campaigns").fetchone()) naive_update({"budget = 1, owner = 'mallory', id": 1}) print(db.execute("SELECT budget, owner FROM campaigns").fetchone())
The values were safe in placeholders, but the key was part of the SQL, so the second request set the budget to 1 and changed the owner to mallory. The allowlist from the cell above refuses that key before any SQL is built, because it is not one of name, budget or status.
import sqlite3 db = sqlite3.connect(":memory:") db.execute("CREATE TABLE campaigns (id INT, budget INT, version INT)") db.execute("INSERT INTO campaigns VALUES (7, 500, 3)") sql = ( "UPDATE campaigns SET budget = ?, version = version + 1 " "WHERE id = ? AND version = ?" ) first = db.execute(sql, (800, 7, 3)).rowcount second = db.execute(sql, (300, 7, 3)).rowcount print(first, second, db.execute("SELECT budget, version FROM campaigns").fetchone())
1 0 (800, 4)
The first update finds the row at version 3, changes the budget and moves the version to 4. The second still asks for version 3, matches no row, and changes nothing. Nothing was overwritten, and a rowcount of 0 tells the API to answer with a conflict.
Two clients read version 1. The first update succeeds; the second matches no rows.
Uses the setup above, 3 lines.
import sqlite3 db = sqlite3.connect(":memory:") db.execute( "CREATE TABLE campaigns (id INTEGER PRIMARY KEY, name TEXT, " "budget REAL, version INTEGER NOT NULL DEFAULT 1)" ) db.execute("INSERT INTO campaigns (name, budget) VALUES ('Spring', 500)") def update_budget(cid, budget, expected_version): cur = db.execute( "UPDATE campaigns SET budget = ?, version = version + 1 " "WHERE id = ? AND version = ?", (budget, cid, expected_version), ) return cur.rowcount == 1 ada_saw = lin_saw = 1 # both loaded version 1 print("Ada saves:", update_budget(1, 650, ada_saw)) print("Lin saves:", update_budget(1, 400, lin_saw)) print(db.execute("SELECT budget, version FROM campaigns").fetchone())
Ada's update matched (version 1) and bumped the version to 2. Lin's update still said "version 1", so it matched nothing and rowcount was 0. The API would answer 412, and Lin reloads, sees Ada's change, and decides again. Nothing is silently lost.
row = {"version": 4}
client_version = 3
print("updated" if client_version == row["version"] else "conflict")conflict
3 isn't equal to 4, so it prints conflict. Someone else changed the row since this client read it, so the update is refused.
An ETag like "cmp_9-3" names one version of a record. Write etag(record): return '"ID-VERSION"' (with the double quotes). Then write if_match_ok(header, record): True if the header is *, or if any of its comma-separated tags equals the record's current ETag; False otherwise.
Uses the setup above, 3 lines.
def etag(record): return record["id"] def if_match_ok(header, record): return True campaign = {"id": "cmp_9", "version": 3, "name": "Spring sale"} print(etag(campaign), if_match_ok('"cmp_9-2"', campaign))
created_at and updated_at in UTC as ISO 8601 text (2026-10-30T14:05:00Z). Convert to local time only when showing it to a person.deleted_at instead of removing the row, like moving a file to the trash. Mistakes can be undone and history survives. Every query then has to skip deleted rows, so it's a trade-off.Neither: no order, and the stock unchanged
A transaction is all or nothing, like a bank transfer. A crash before it commits leaves nothing behind.
When a unique constraint fails, the database raises an error. Left alone, that becomes a 500, telling the client your server broke. It didn't. They tried to use an email address that's already taken. Catch that specific error and return a 409 with a clear message. The constraint is still what keeps your data correct, since checking first and inserting after leaves a gap that two requests can slip through together.
Write db_error_to_http(message) for SQLite error messages: UNIQUE constraint failed: TABLE.COLUMN becomes (409, "COLUMN already exists"); NOT NULL constraint failed: TABLE.COLUMN becomes (422, "COLUMN is required"); FOREIGN KEY constraint failed becomes (422, "refers to something that doesn't exist"); anything else is (500, "Internal server error").
Uses the setup above, 3 lines.
def db_error_to_http(message): return 500, message print(db_error_to_http("UNIQUE constraint failed: campaigns.slug"))
Write a sentence or two, then compare it with a good answer in the lesson.
Prompts, eval sets and experiment records are edited by several people and read by running systems, so they are exactly the rows lost updates damage: two engineers tune the same prompt, and the later save silently erases the earlier fix. Give them a version and an ETag, and refuse a stale save with 412. The practice API does it for prompt templates, so you can watch it from Python.
Two editors read the same prompt. One saves. The other's save, made from the old ETag, is refused. A save with no If-Match at all is refused too.
Uses the setup above, 3 lines.
url = f"{BASE}/v1/prompts/support-reply" requests.post(f"{BASE}/v1/reset") ada = requests.get(url) lin = requests.get(url) first = requests.put(url, json={"text": "Hi, how can we help?"}, headers={"If-Match": ada.headers["ETag"]}) stale = requests.put(url, json={"text": "Hello!"}, headers={"If-Match": lin.headers["ETag"]}) bare = requests.put(url, json={"text": "Hello!"}) print(first.status_code, stale.status_code, bare.status_code) print(sorted(stale.json()))
Ada's save matched the current ETag and succeeded. Lin's carried the old one, so it was refused with 412, and the body names the current version so Lin can reload. A save with no If-Match got 428.
Three reviews recur. "Where is the version?" Any table that people or jobs both write needs one. "Why is this key pasted into the SQL?" The column names must come from an allowlist, and an ORM or a query builder does that for you. "Why is this a 500?" A unique clash is a 409, and the client should be able to branch on it. For a service that stores prompts and eval records, a version on each row and an ETag on each read means that two people tuning the same prompt never overwrite each other without being told. Goes deeper in: Project: a FastAPI service with accounts puts a database behind accounts, [[p11-experiment-tracking]] stores runs with versions, and Caches, queues and background jobs uses the same ETag idea for caches.
Write a sentence or two, then compare it with a good answer in the lesson.
Start with a short baseline or choose guided, independent, or AI-assisted practice.
What is a lost update?
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
Go from your first line of code to working as a Python developer: projects, testing, data, databases, web apps and APIs, all in your browser.
Design, test, deploy, and operate an HTTP API that another engineer can use.
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write