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.
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:
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 workedIf 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.
| Letter | Promise | The failure it prevents |
|---|---|---|
| Atomicity | All 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. |
| Consistency | A 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. |
| Isolation | Concurrent transactions do not see each other's half-finished work, to a degree you choose. | Two checkouts both selling the last laptop. |
| Durability | Once 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).
sqlite3silently sendsBEGINbeforeINSERT,UPDATE,DELETEorREPLACE, but not beforeSELECT. You must callcommit(). autocommit=True(Python 3.12+). The module does nothing behind your back. Each statement commits on its own unless you sendBEGINyourself. The checkout example used this so the SQL was explicit.autocommit=False(Python 3.12+). A transaction is always open, like psycopg.commit()androllback()end it and immediately open the next one.
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:
- 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.
- Use a context manager for every unit of work.
with conn:insqlite3,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. - Do not confuse "commit" with "close".
with conn:insqlite3ends the transaction but keeps the connection. Close it yourself, or let a pool manage it.
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])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:
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.
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 defaultonwaits for the WAL flush.offreturns 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_modeandsynchronous. WAL mode lets readers keep reading while one writer commits. Many apps pair it withsynchronous = 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.
The handler opens a transaction and updates the order row. Postgres now holds a row lock on order 7 until the transaction ends.
Two related problems show up in production dashboards:
- "idle in transaction" sessions. A connection that ran
BEGINand 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 inpg_stat_activitywherestate = '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 addedtransaction_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:
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.
Match each tool to the job it does.
Put the steps of a safe 'pay for order' request in order.
- Tap the steps below in the right order.
- 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.