Transactions and Concurrency: Rollback, Lost Updates and Not Overselling
Keep data consistent when things fail or happen at the same time: use database transactions with rollback, reproduce a lost update between two threads, fix it with a lock, and prevent overselling with an atomic UPDATE.
In this lesson you will
- Group steps in a transaction
- Reproduce a lost update
- Fix it with a lock
- Prevent overselling with an atomic UPDATE
About 28 minutes
Two people, one drill
A back end rarely does one thing at a time. When a member borrows a drill, the server must record the loan and reduce the stock, two changes that must happen together or not at all. If the server crashes between them, you have a loan with no stock change, or the reverse. A transaction groups several statements into one unit: they are all applied when you commit, and none is applied if you roll back. Databases also provide isolation, so that other connections do not see the half-finished state. The acronym ACID, atomic, consistent, isolated, durable, summarises what a transaction promises.
The other danger is concurrency. A web server handles many requests at once, and two of them may read the same value, both calculate a new value from it, and both write: the second write overwrites the first, and one update is lost. This is a race condition, and it is hard to find because it appears only under unlucky timing. The cures are to let the database do the read-modify-write in one atomic statement, such as UPDATE tools SET stock = stock – 1 WHERE id = 1 AND stock > 0, or to take a lock around the critical section. The atomic statement also prevents overselling: it only succeeds if there is stock left, and the number of rows it changed tells the code whether it won.
import sqlite3, json, threading, os, tempfile
path = os.path.join(tempfile.mkdtemp(), "lib.db")
def conn(): return sqlite3.connect(path, timeout=10, isolation_level=None)
db = conn()
db.executescript("CREATE TABLE stock (tool TEXT PRIMARY KEY, left INTEGER CHECK (left >= 0)); CREATE TABLE loans (id INTEGER PRIMARY KEY, tool TEXT, member TEXT);")
db.execute("INSERT INTO stock VALUES ('drill', 5), ('ladder', 1)")
def borrow_unsafe(tool, member, fail=False):
db.execute("INSERT INTO loans (tool, member) VALUES (?, ?)", (tool, member))
if fail: raise RuntimeError("crash between the two steps")
db.execute("UPDATE stock SET left = left - 1 WHERE tool = ?", (tool,))
def borrow_tx(tool, member, fail=False):
db.execute("BEGIN")
try:
db.execute("INSERT INTO loans (tool, member) VALUES (?, ?)", (tool, member))
if fail: raise RuntimeError("crash between the two steps")
db.execute("UPDATE stock SET left = left - 1 WHERE tool = ?", (tool,))
db.execute("COMMIT")
except Exception:
db.execute("ROLLBACK"); raise
def state(): return db.execute("SELECT COUNT(*) FROM loans").fetchone()[0], db.execute("SELECT left FROM stock WHERE tool='drill'").fetchone()[0]
try: borrow_unsafe("drill", "ama", fail=True)
except RuntimeError: pass
after_unsafe = state()
db.execute("DELETE FROM loans")
try: borrow_tx("drill", "ben", fail=True)
except RuntimeError: pass
after_tx = state()
borrow_tx("drill", "chi")
after_ok = state()
print("crash without a transaction: loans, drill left =", after_unsafe)
print("crash inside a transaction : loans, drill left =", after_tx)
print("successful transaction : loans, drill left =", after_ok)
# lost update: two threads read the same value before either writes
cnt = {"v": 0}
barrier = threading.Barrier(2)
def bump_unsafe():
v = cnt["v"]; barrier.wait(); cnt["v"] = v + 1
ts = [threading.Thread(target=bump_unsafe) for _ in range(2)]
[t.start() for t in ts]; [t.join() for t in ts]
lost = cnt["v"]
cnt["v"] = 0; lock = threading.Lock()
def bump_safe():
with lock:
v = cnt["v"]; cnt["v"] = v + 1
ts = [threading.Thread(target=bump_safe) for _ in range(2000)]
[t.start() for t in ts]; [t.join() for t in ts]
print("two forced-overlap increments gave", lost, "(expected 2) | 2000 locked increments gave", cnt["v"])
# overselling: 12 members try to borrow the last ladders (stock 1) and drills (stock 4 after above)
results = []
def grab(tool, member):
c = conn()
cur = c.execute("UPDATE stock SET left = left - 1 WHERE tool = ? AND left > 0", (tool,))
results.append((tool, cur.rowcount))
c.close()
ts = [threading.Thread(target=grab, args=("ladder", "m%d" % i)) for i in range(12)] + [threading.Thread(target=grab, args=("drill", "m%d" % i)) for i in range(12)]
[t.start() for t in ts]; [t.join() for t in ts]
won = {t: sum(r for tt, r in results if tt == t) for t in ("ladder", "drill")}
left = dict(db.execute("SELECT tool, left FROM stock").fetchall())
print("12 attempts each; winners:", won, "| stock left:", left)
print("DATA " + json.dumps({"unsafe": after_unsafe, "tx": after_tx, "ok": after_ok, "lost": lost, "locked": cnt["v"], "won": won, "left": left}))
crash without a transaction: loans, drill left = (1, 5)
crash inside a transaction : loans, drill left = (0, 5)
successful transaction : loans, drill left = (1, 4)
two forced-overlap increments gave 1 (expected 2) | 2000 locked increments gave 2000
12 attempts each; winners: {'ladder': 1, 'drill': 4} | stock left: {'drill': 0, 'ladder': 0}
The first experiment simulates a crash between the two steps of a loan. Without a transaction, the loan row was already written when the crash happened, so the database ended with 1 loan and the drill stock still at 5: an inconsistent state, a loan for a drill that is still counted as on the shelf. Inside a transaction, the same crash triggered a rollback and the database returned to 0 loans and a stock of 5, as if nothing had happened. The successful transaction then recorded 1 loan and reduced the stock to 4, both changes together.
The second experiment forces the unlucky timing that normally happens only occasionally. A barrier makes two threads both read the counter, 0, before either writes, so both write 1 and the final value is 1 instead of 2: one update was lost, with no error. Wrapping the read-modify-write in a lock made 2,000 threads add exactly 2,000, as it should. In a real server the timing is not forced, so the bug shows up as a rare, unreproducible wrong total, which is why it must be designed out, not tested out.
The third experiment is the one that matters for Kofi. Twelve threads, each with its own database connection, tried to borrow the single ladder, and twelve more tried to borrow the drills, of which four were left. The conditional UPDATE only succeeds while the stock is above zero, and the number of changed rows tells each thread whether it won. The winners were 1 for the ladder and 4 for the drills, exactly the stock, and the table ends with 0 and 0 left. The CHECK constraint on the column is a second line of defence: even a buggy query could not push the stock below zero.
Independent check: the expected values come from simple arithmetic and rules rather than from the program’s own logic. A drill stock of 5 with one successful loan leaves 4, and 4 drills can be won by at most 4 of the 12 attempts, and a stock of 1 ladder by 1 of 12. The total number of winners can never exceed the stock, whatever the timing, so the assertions hold on every run, and the lost-update count is forced by the barrier, not left to chance.
Check by hand: five drills minus one successful loan is four. The two threads that both read 0 and write 1 leave the counter at 1, and 2,000 locked increments leave 2,000. Winners 1 and 4 equal the stock left before the race, and the stock ends at 0.
Reading a value, computing in Python, and writing it back is unsafe when two requests overlap. Let the database do the arithmetic in one statement, or lock explicitly.
A transaction holds locks. Do the slow work, such as network calls and emails, before or after it, never inside it.
Every program in this lesson was run while the course was written, with Python 3.13 and only its standard library (http.server, sqlite3, hashlib, hmac, unittest), with a real server on a free local port, and cross-checked with curl, openssl or a second implementation. Tools and versions change, so check the official documentation for current behaviour. SQLite allows one writer at a time, so the timing differs from servers such as PostgreSQL, which have finer locking and isolation levels. Check the documentation of the database you use.
Practice
Add a second table that records every stock change, and make both writes one transaction. Try borrowing with 50 threads and verify that the stock never goes negative. Replace the lock with an atomic database update for the counter.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What does a transaction guarantee?
- Faster queries
- Free storage
- All its changes happen or none do
- Encryption
Atomicity.
What is a lost update?
- A deleted table
- Two writers overwrite each other’s change
- A crash
- A cache miss
A race condition.
How does UPDATE … WHERE left > 0 prevent overselling?
- It locks the server
- It only changes a row while stock remains
- It sends an email
- It sorts rows
Check rowcount to see who won.
Why keep transactions short?
- They hold locks that block others
- They use more disk
- They are less secure
- They cannot commit
Do slow work outside.
What is a CHECK constraint for?
- Rejecting invalid values at the database level
- Speeding up searches
- Backups
- Joins
A last line of defence.
Summary
- Transactions make several changes atomic; rollback undoes them.
- Read-modify-write in code is a race; use atomic statements or locks.
- Check the number of changed rows to know who won.
- Constraints are the last line of defence.
Questions
What are isolation levels?
Settings that control how much concurrent transactions can see of each other, trading safety against speed. The defaults are usually fine for simple apps. Check your database documentation for the options.
Do I need transactions with a single statement?
A single statement is atomic by itself. You need a transaction when several statements must succeed together.
What is a deadlock?
Two transactions waiting for each other's locks, so neither can continue. Databases detect them and abort one, so your code should be ready to retry.
