Sub topic 15
Designing transactions well
This chapter assumes you know BEGIN, COMMIT, ROLLBACK and SAVEPOINT. It also assumes you know the four ACID properties and the common isolation levels, and that you have seen deadlocks and serialization failures. Examples use PostgreSQL. The rules below carry over to most relational databases, though defaults differ.
Earlier chapters explained how transactions work. This one covers how to design them: what belongs inside one, how long to keep it open, and how to make the application code around it safe.
Keep each transaction small and short
A transaction holds resources until it ends. These include row locks, a snapshot that keeps old row versions from being cleaned up, and a connection. The longer it stays open, the more it blocks other work and the more likely it is to collide with another transaction.
Two rules follow from this:
- Group only the statements that must succeed or fail together. A transfer needs both the debit and the credit. It does not need the audit report you generate afterwards.
- Do slow work outside the transaction. Network calls, file uploads, sending email and waiting for a user all belong before BEGIN or after COMMIT.
The worst pattern is holding a transaction open while waiting for a person. A user opens a form, the application runs BEGIN and locks a row, and the user goes to lunch. Everyone else who needs that row waits. In PostgreSQL an open transaction also stops VACUUM from removing dead row versions created after it started, so tables bloat.
-- Bad: external call while locks are held
BEGIN;
SELECT balance FROM accounts WHERE id = 1 FOR UPDATE;
-- application calls a payment API here, which may take seconds
UPDATE accounts SET balance = balance - 20 WHERE id = 1;
COMMIT;The payment call should happen first, or be recorded as a pending row and completed by a separate step. Then the locked window covers only the database work.
A safety net helps. PostgreSQL has idle_in_transaction_session_timeout, which ends sessions that sit inside a transaction without running anything. lock_timeout and statement_timeout bound how long a statement waits or runs.
SET idle_in_transaction_session_timeout = '30s';
SET lock_timeout = '5s';Put the rules in the database
The consistency property only holds for rules the database knows about. Constraints are checked inside the transaction, so a violation stops the commit no matter which application sent the statement.
Prefer, in this order:
- Declarative constraints:
NOT NULL,CHECK,UNIQUE,PRIMARY KEY,FOREIGN KEY. - Exclusion constraints or triggers for rules that span rows.
- Application checks, as a convenience for good error messages and never as the only defence.
An application check such as "read the balance, then update if enough" is a race unless the transaction also locks or serializes. A CHECK (balance >= 0) constraint is safe under any isolation level.
CREATE TABLE accounts (
id integer PRIMARY KEY,
balance numeric(12,2) NOT NULL CHECK (balance >= 0)
);Make updates atomic in a single statement
Many read-modify-write races disappear if the modification is done by the database in one statement. This version never reads the balance into the application:
UPDATE accounts
SET balance = balance - 20
WHERE id = 1 AND balance >= 20;The application checks the affected row count. If it is 0, the account did not have enough money (or did not exist). Compare this with reading the balance, computing the new value in code, and writing it back. That sequence loses updates under READ COMMITTED unless you lock the row first.
Choose a concurrency strategy deliberately
For a read-then-write sequence, you have three main choices.
| Strategy | How it works | Good for | Cost |
|---|---|---|---|
| Single-statement update | Database computes the new value | Counters, balances, stock | Only works when the logic fits in SQL |
| Pessimistic lock (`SELECT ... FOR UPDATE`) | Lock rows before deciding | High contention, short transactions | Waiting, deadlock risk |
| Higher isolation plus retry | Run at REPEATABLE READ or SERIALIZABLE and retry on failure | Complex invariants across rows | Needs retry logic, some aborted work |
An optimistic variant uses a version column. The update succeeds only if the row is unchanged since it was read:
UPDATE documents
SET body = 'new text', version = version + 1
WHERE id = 7 AND version = 3;If zero rows are updated, someone else changed the row. The application reloads and tries again, or tells the user. This works well across several requests (such as an edit form) because no lock is held while the user thinks.
Use the lowest isolation level that protects your invariants, and know which anomalies remain. READ COMMITTED is fine for many workloads when you use constraints and atomic updates. Use SERIALIZABLE when an invariant spans several rows and is hard to enforce with a lock or constraint, as in the on-call doctors example.
Avoid deadlocks by ordering
Deadlocks happen when two transactions lock the same rows in opposite order. The database detects the cycle and aborts one transaction, but prevention is cheaper.
- Always touch rows in a consistent order, such as ascending primary key.
- Lock everything you need at the start, in that order.
- Keep transactions short so locks are held for less time.
A transfer function can sort the two account ids before locking:
BEGIN;
SELECT id FROM accounts WHERE id IN (1, 2) ORDER BY id FOR UPDATE;
UPDATE accounts SET balance = balance - 30 WHERE id = 1;
UPDATE accounts SET balance = balance + 30 WHERE id = 2;
COMMIT;The ORDER BY makes every transfer between these accounts lock account 1 first. Two opposite transfers (1 to 2 and 2 to 1) then queue instead of deadlocking.
Retry the whole transaction
Some failures are expected and recoverable. In PostgreSQL these are SQLSTATE 40001 (serializationfailure) and 40P01 (deadlockdetected). The right response is to roll back and run the whole transaction again from BEGIN, because the data it read may no longer be valid.
Rules for a correct retry loop:
- Retry the entire transaction function, including its reads and any decisions based on them.
- Cap attempts (for example 5) and add a short randomized delay so competing transactions do not collide again.
- Retry only the specific error codes. Do not retry constraint violations, which will fail every time.
- Make the transaction free of external side effects, or make those side effects idempotent. Sending an email inside a retried transaction may send it several times.
import random
import time
import psycopg
from psycopg import errors
RETRYABLE = (errors.SerializationFailure, errors.DeadlockDetected)
def transfer(conn_string, src, dst, amount, attempts=5):
for attempt in range(1, attempts + 1):
try:
with psycopg.connect(conn_string) as conn:
conn.isolation_level = psycopg.IsolationLevel.SERIALIZABLE
with conn.transaction():
cur = conn.execute(
"UPDATE accounts SET balance = balance - %s "
"WHERE id = %s AND balance >= %s",
(amount, src, amount),
)
if cur.rowcount == 0:
raise ValueError("insufficient funds")
conn.execute(
"UPDATE accounts SET balance = balance + %s WHERE id = %s",
(amount, dst),
)
return
except RETRYABLE:
if attempt == attempts:
raise
time.sleep(random.uniform(0, 0.05 * 2 ** attempt))The ValueError is not in RETRYABLE, so it propagates immediately. The with conn.transaction() block commits on normal exit and rolls back if an exception leaves it.
A subtle case: an error can occur at COMMIT time. Under SERIALIZABLE, PostgreSQL may report the failure only when you commit. Put the commit inside the code that your retry loop wraps, as the example does.
Handle uncertain commits
If the connection drops while COMMIT is in flight, you do not know whether the transaction committed. Blindly retrying could apply the change twice. Two defences:
- Give each logical operation a unique key (an idempotency key) stored with the result under a
UNIQUEconstraint. A repeat then fails the constraint instead of duplicating work. - On reconnect, check whether the operation's effect is already present before repeating it.
Know the boundaries of a transaction
A transaction protects one database. If a business operation also updates a second database, publishes a message, or calls an HTTP service, the transaction cannot undo those. Two-phase commit exists but is costly and often unavailable. Common alternatives are:
- Write the outgoing message to an "outbox" table in the same transaction as the data change. A separate process reads the table and publishes the message, retrying until it succeeds.
- Design the remote step to be idempotent so it can be repeated safely.
Checklist
- Is every statement in the transaction needed for the same all-or-nothing outcome?
- Is slow or external work outside it?
- Are invariants enforced by constraints, not only by application code?
- Can a read-modify-write be a single statement?
- Is the isolation level or locking choice documented, with the remaining anomalies understood?
- Do all code paths lock rows in the same order?
- Does the caller retry on
40001and40P01, with a cap and backoff? - Are side effects idempotent or moved out through an outbox?
- Are timeouts set so a stuck session cannot hold locks forever?
Exercise
A function reads an account balance with a plain SELECT, checks in application code that it is at least 20, then runs UPDATE accounts SET balance = balance - 20 under READ COMMITTED. Two calls run at once on a balance of 30. Name the problem and give two fixes that need no change to the isolation level.
Show answer
Both calls can read 30 and pass the check, so both subtract 20. A CHECK (balance >= 0) constraint would reject the second update, but without it the balance would end at -10, which is a lost-update style race on a check-then-act sequence. Fix 1: make the check part of the statement, UPDATE accounts SET balance = balance - 20 WHERE id = 1 AND balance >= 20, and treat a row count of 0 as insufficient funds. Fix 2: read with SELECT ... FOR UPDATE so the second call waits for the first to finish and then sees the new balance. A CHECK constraint is also worth adding as a backstop.
Exercise
Why must a retry loop restart the whole transaction after SQLSTATE 40001, and which errors should it not retry?
Show answer
After 40001 the transaction is aborted, and the values it read earlier may be out of date, so decisions based on them are no longer valid. Rerunning from BEGIN re-reads current data and re-evaluates those decisions. Errors that will fail every time, such as unique, foreign key or check constraint violations, should not be retried. Only 40001 and 40P01 (and similar transient failures) should be.