Skip to content

Lesson 19 of 29Transactions and concurrency

Transactions and ACID

Group statements into all-or-nothing units, use savepoints, control autocommit in Python, and keep transactions short enough not to hurt production.

21 min read0/4 questions

The last unit treated each query on its own. Real work runs several statements together while other users do the same. A checkout endpoint inserts an order, inserts three order lines and decrements stock for each product. On the third line the process crashes, or a constraint fails, or the pod is killed by a deploy. Without a transaction you now have an order with two lines, stock that went down for products nobody paid for, and a support ticket that takes a developer an afternoon to untangle. A transaction turns those six statements into one unit that either happens completely or not at all. This lesson covers what the database actually promises, how to drive transactions from Python, and the mistakes with transaction scope that cause real outages.

All or nothing, for real

Here is that checkout written as a Python function. The basket's second line has quantity 0, which breaks the CHECK (quantity > 0) constraint on order_items part way through. Run it and compare the two attempts:

Pythoncheckout.py
import sqlite3from shopdb import connect, show def place_order(db, customer_id, basket): cur = db.execute( "INSERT INTO orders (customer_id, status, created_at) VALUES (?, 'pending', '2025-08-01')", (customer_id,), ) order_id = cur.lastrowid for product_id, qty in basket: price = db.execute("SELECT price_cents FROM products WHERE id = ?", (product_id,)).fetchone()[0] db.execute("UPDATE products SET stock = stock - ? WHERE id = ?", (qty, product_id)) db.execute("INSERT INTO order_items VALUES (?, ?, ?, ?)", (order_id, product_id, qty, price)) return order_id basket = [(3, 2), (5, 0)] # the second line has quantity 0, which breaks a CHECK # 1. No transaction: every statement commits on its own.db = connect()db.autocommit = Truetry: place_order(db, 4, basket)except sqlite3.IntegrityError as err: print("failed:", err)show(db, "SELECT count(*) AS orders, (SELECT stock FROM products WHERE id = 3) AS hub_stock FROM orders") # 2. One transaction: all or nothing.db = connect()db.autocommit = True # we send BEGIN/COMMIT/ROLLBACK ourselvesdb.execute("BEGIN")try: place_order(db, 4, basket) db.execute("COMMIT")except sqlite3.IntegrityError as err: db.execute("ROLLBACK") print("failed and rolled back:", err)show(db, "SELECT count(*) AS orders, (SELECT stock FROM products WHERE id = 3) AS hub_stock FROM orders")
Output
Press Run (⌘ Enter) to see what happens.

The first attempt leaves an 11th order in the table and two USB-C hubs missing from stock, for an order that failed. The second attempt rolls everything back: still 10 orders, still 150 hubs. The SQL is identical in Postgres:

BEGIN;
INSERT INTO orders (customer_id, status) VALUES (4, 'pending') RETURNING id;
UPDATE products SET stock = stock - 2 WHERE id = 3;
INSERT INTO order_items VALUES (11, 3, 2, 4900);
-- any error here, or a crash, or a lost connection
ROLLBACK;   -- or COMMIT; if everything worked

If the connection drops or the server crashes before COMMIT, the database rolls back on its own. You never have to clean up a half-finished transaction by hand.

What ACID actually promises

ACID is four separate guarantees. Interviewers like it when you can name the failure each one prevents, rather than reciting the acronym.

LetterPromiseThe failure it prevents
AtomicityAll statements in the transaction take effect, or none do.The half-placed order above. A transfer that debits one account and never credits the other.
ConsistencyA committed transaction moves the database from one valid state to another, as defined by its constraints.A negative balance, an order line pointing at a deleted product, two users with the same email.
IsolationConcurrent transactions do not see each other's half-finished work, to a degree you choose.Two checkouts both selling the last laptop.
DurabilityOnce COMMIT returns, the change survives a crash or power cut.A customer sees "payment confirmed" and the payment vanishes after a reboot.

Two of these need a closer look.

Consistency is partly your job. The database can only enforce the rules you declare: NOT NULL, UNIQUE, CHECK, foreign keys. If "an order's total must equal the sum of its lines" lives only in Python, the database cannot protect it, and a script that skips your code can break it. Atomicity and constraints work together: a constraint failure aborts the statement, and the transaction lets you throw away everything that came before it. That is why the rollback in the checkout restored the hub stock that had already been decremented.

Isolation is a dial, not a switch. Full isolation would mean every transaction behaves as if it ran alone, one after another. That is slow, so databases default to weaker levels that allow some anomalies. That is a big enough topic to have its own lesson, Isolation levels and anomalies.

Autocommit and implicit transactions

If you never type BEGIN, you are still using transactions. In autocommit mode, every statement is its own transaction that commits as soon as it finishes. psql works like this by default, which is why a stray UPDATE without a WHERE in a psql session is instantly permanent.

Drivers differ, and this is where real bugs come from. Many follow the Python database standard (PEP 249): the first statement silently opens a transaction, and nothing is saved until you call commit(). psycopg (the Postgres driver) behaves this way unless you turn autocommit on. Python's sqlite3 has its own history, so it now has three modes:

  • Legacy mode (still the default in Python 3.14). sqlite3 silently sends BEGIN before INSERT, UPDATE, DELETE or REPLACE, but not before SELECT. You must call commit().
  • autocommit=True (Python 3.12+). The module does nothing behind your back. Each statement commits on its own unless you send BEGIN yourself. The checkout example used this so the SQL was explicit.
  • autocommit=False (Python 3.12+). A transaction is always open, like psycopg. commit() and rollback() end it and immediately open the next one.
Pythonmodes.py
import os, sqlite3from shopdb import connect PATH = "/tmp/shop.db"for f in (PATH, PATH + "-journal", PATH + "-wal", PATH + "-shm"): if os.path.exists(f): os.remove(f)connect(PATH).close() # Legacy mode (the default): a SELECT opens nothing, DML opens a transaction silently.db = sqlite3.connect(PATH)db.execute("SELECT stock FROM products WHERE id = 1")print("after SELECT, in a transaction?", db.in_transaction)db.execute("UPDATE products SET stock = 0 WHERE id = 1")print("after UPDATE, in a transaction?", db.in_transaction)db.close() # no commit: the UPDATE is thrown away db = sqlite3.connect(PATH)print("stock after close without commit:", db.execute("SELECT stock FROM products WHERE id = 1").fetchone()[0]) # `with db:` commits on success and rolls back on an exception. It does NOT close.with db: db.execute("UPDATE products SET stock = 11 WHERE id = 1")print("still open after with-block?", db.execute("SELECT 1").fetchone() == (1,))db.close() # autocommit=False (Python 3.12+): a transaction is always open, like most drivers.db = sqlite3.connect(PATH, autocommit=False)print("autocommit=False, in a transaction straight away?", db.in_transaction)db.execute("UPDATE products SET stock = 10 WHERE id = 1")db.commit() # commits, then opens the next transactionprint("after commit, in a transaction?", db.in_transaction)db.close() print("final stock:", sqlite3.connect(PATH).execute("SELECT stock FROM products WHERE id = 1").fetchone()[0])
Output
Press Run (⌘ Enter) to see what happens.

This block uses a file in /tmp instead of memory, because an in-memory database disappears when its connection closes, and the point is to reopen it.

Three habits follow from this:

  1. Know which mode your driver is in. The classic bug is "my writes work in tests but vanish in production", where the tests share one connection that sees its own uncommitted writes and production opens a fresh one.
  2. Use a context manager for every unit of work. with conn: in sqlite3, with conn.transaction(): in psycopg, with Session.begin(): in SQLAlchemy. They commit on success and roll back on any exception, which is the behaviour you always want.
  3. Do not confuse "commit" with "close". with conn: in sqlite3 ends the transaction but keeps the connection. Close it yourself, or let a pool manage it.
Predict the outputPython

Python's sqlite3 in its default legacy mode, on a file database. What does the last line print?

db = sqlite3.connect("shop.db")
db.execute("UPDATE products SET stock = 0 WHERE id = 1")   # stock was 12
db.execute("SELECT stock FROM products WHERE id = 1")
db.close()

db = sqlite3.connect("shop.db")
print(db.execute("SELECT stock FROM products WHERE id = 1").fetchone()[0])
Need a nudge? Hints walk you through it.

Savepoints: undo part of a transaction

Sometimes you want most of a transaction to succeed even if one piece fails. A nightly import of 10,000 customers should not throw away 9,998 good rows because two had a duplicate email. A savepoint marks a point inside a transaction that you can roll back to without abandoning the whole thing:

Pythonsavepoints.py
import sqlite3from shopdb import connect, show db = connect()db.autocommit = Truerows = [ ("Ada Lovelace", "ada2@example.com"), ("No Email", "grace@example.com"), # duplicate email: UNIQUE fails ("Edsger Dijkstra", "edsger@example.com"), (None, "nobody@example.com"), # NULL name: NOT NULL fails] db.execute("BEGIN")skipped = []for i, (name, email) in enumerate(rows): db.execute("SAVEPOINT row") try: db.execute( "INSERT INTO customers (name, email, created_at) VALUES (?, ?, '2025-08-01')", (name, email), ) db.execute("RELEASE row") except sqlite3.IntegrityError as err: db.execute("ROLLBACK TO row") # undo just this row db.execute("RELEASE row") skipped.append((i, str(err)))db.execute("COMMIT") for i, why in skipped: print("skipped row", i, "->", why)show(db, "SELECT id, name, email FROM customers WHERE id > 8")
Output
Press Run (⌘ Enter) to see what happens.

SAVEPOINT name sets the mark, ROLLBACK TO name undoes everything after it and keeps the transaction open, and RELEASE name forgets the mark. The good rows commit together at the end.

This is how ORMs give you "nested transactions". A database has no real nested transactions: there is one transaction per connection. When you call SQLAlchemy's session.begin_nested() or nest Django's transaction.atomic() blocks, the ORM issues SAVEPOINT for the inner block and ROLLBACK TO if it raises. Knowing this explains a common surprise: committing the "inner" transaction does not make anything durable. Only the outermost COMMIT does.

Durability: what COMMIT waits for

When COMMIT returns, the database has written a record of your change to its write-ahead log and asked the operating system to flush it to disk with fsync. The table and index pages themselves may still be only in memory. After a crash, the database replays the log to rebuild them. How that log works, and checkpoints, are covered in How Databases Store Data. For this lesson, the important part is that durability has a price (one disk flush per commit) and some knobs that trade it away.

Pythonwal.py
import os, sqlite3from shopdb import connect PATH = "/tmp/shop.db"for f in (PATH, PATH + "-journal", PATH + "-wal", PATH + "-shm"): if os.path.exists(f): os.remove(f)db = connect(PATH) def wal_bytes(): return os.path.getsize(PATH + "-wal") if os.path.exists(PATH + "-wal") else 0 print("journal mode:", db.execute("PRAGMA journal_mode = WAL").fetchone()[0])print("synchronous:", db.execute("PRAGMA synchronous").fetchone()[0], "(2 = FULL)")print("db file bytes:", os.path.getsize(PATH), "| wal bytes:", wal_bytes())with db: db.execute("UPDATE products SET stock = stock - 1 WHERE id = 1")print("after one commit, wal bytes:", wal_bytes())db.execute("PRAGMA wal_checkpoint(TRUNCATE)")print("after a checkpoint, wal bytes:", wal_bytes())
Output
Press Run (⌘ Enter) to see what happens.

One UPDATE changed one 4 KB page, so the commit appended that page plus small headers to the -wal file. A checkpoint copied it into the main file and emptied the log.

The knobs you will meet at work:

  • Postgres synchronous_commit. The default on waits for the WAL flush. off returns before the flush, so a crash can lose the last fraction of a second of commits, though never corrupt the database. It is a reasonable per-transaction choice for data you can regenerate (analytics events), and a bad global one for orders. With synchronous replication, the same setting also controls whether a commit waits for a replica.
  • Postgres fsync = off. Never in production. A crash can corrupt the whole cluster, not just lose recent commits.
  • SQLite journal_mode and synchronous. WAL mode lets readers keep reading while one writer commits. Many apps pair it with synchronous = NORMAL, which in WAL mode cannot corrupt the database but can lose the last commits on a power cut.
  • Batching. Since each commit costs a flush, inserting 10,000 rows in 10,000 autocommit transactions is dramatically slower than one transaction. This is the first thing to check when a bulk load is slow.

Transaction scope in a web request

The usual rule is one transaction per unit of work, which in a web API is usually one per request: open it when the handler starts writing, commit before you send the response, roll back on any exception. Frameworks and ORMs set this up for you, and it is the right default.

The rule that matters more: never hold a transaction open across something slow that you do not control. That means calls to other services and anything waiting on a human.

A payment call inside a transaction
APIPostgresPayment providerBEGIN; UPDATE orders SET status = 'paying' WHERE id = 7POST /chargesother requests wait on order 7200 after 25 sbetter: short transactions on both sides

The handler opens a transaction and updates the order row. Postgres now holds a row lock on order 7 until the transaction ends.

1/5

Two related problems show up in production dashboards:

  • "idle in transaction" sessions. A connection that ran BEGIN and then stopped sending statements, usually because the code is waiting on something else or forgot to commit. It holds every lock it took, and it pins the oldest snapshot, so VACUUM cannot clean up dead row versions anywhere in the database. Tables bloat for as long as it stays open. Find these in pg_stat_activity where state = 'idle in transaction'.
  • The fix is a timeout plus better code. Set idle_in_transaction_session_timeout (for example, a few seconds to a minute for app roles) so Postgres kills such sessions. Postgres 17 added transaction_timeout, which caps the total length of any transaction. Then fix the code path that held the transaction open.

Retries and idempotency keys

Transactions make one database atomic. They cannot make your app and a client agree. If the connection dies just after you send COMMIT, you do not know whether it landed. If a client's request times out, it will retry, and the first attempt may have succeeded. Retries are unavoidable, so writes must be idempotent: doing them twice has the same effect as doing them once.

The standard tool is an idempotency key: the client generates a unique id per logical operation and sends it with every retry. A UNIQUE constraint turns "already done" into something the database checks atomically:

Pythonidempotency.py
from shopdb import connect, show db = connect()db.executescript("""CREATE TABLE payments ( id INTEGER PRIMARY KEY, idempotency_key TEXT NOT NULL UNIQUE, order_id INTEGER NOT NULL REFERENCES orders(id), amount_cents INTEGER NOT NULL);""") def record_payment(key, order_id, amount): with db: row = db.execute( """INSERT INTO payments (idempotency_key, order_id, amount_cents) VALUES (?, ?, ?) ON CONFLICT (idempotency_key) DO NOTHING RETURNING id""", (key, order_id, amount), ).fetchone() if row: return f"charged, payment {row[0]}" existing = db.execute("SELECT id FROM payments WHERE idempotency_key = ?", (key,)).fetchone() return f"duplicate, returning payment {existing[0]}" print(record_payment("a1f3-order-7", 7, 13500))print(record_payment("a1f3-order-7", 7, 13500)) # client retried after a timeoutshow(db, "SELECT * FROM payments")
Output
Press Run (⌘ Enter) to see what happens.

A "check first, then insert" version has a race: two retries arriving together both see no row and both insert. The constraint closes that gap. Payments builds the full pattern, including storing the response to replay it.

Quick check
A deploy kills the API process between two UPDATE statements of a money transfer. Which ACID property makes sure the first UPDATE does not stay applied?
Need a nudge? A hint rules out a wrong answer.
Match the pairs0/5 matched

Match each tool to the job it does.

Choose an item, then its match on the other side.
Put it in order5 steps

Put the steps of a safe 'pay for order' request in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
transaction
A group of statements that commits as one unit or rolls back as one unit.
autocommit
A mode where each statement is its own transaction and commits as soon as it finishes.
savepoint
A named mark inside a transaction that you can roll back to without abandoning the whole transaction. How ORMs implement nested transactions.
write-ahead log
The append-only log a database flushes to disk before acknowledging a commit, and replays after a crash.
synchronous_commit
A Postgres setting that decides whether COMMIT waits for the WAL flush (and, with synchronous replicas, for them).
idle in transaction
A session that opened a transaction and is not running anything. It holds locks and blocks VACUUM until it ends.
idempotency key
A client-chosen unique id for one logical operation, enforced with a UNIQUE constraint so retries do not repeat the work.