Sub topic 15
Designing Transactions Well
Prerequisites and transaction boundaries
This chapter assumes you know basic SELECT, INSERT, UPDATE, and DELETE, understand primary keys and constraints, and know that several users or processes can run database statements at the same time.
A transaction should contain one logical unit of work. If the work must either happen completely or not happen at all, place it in one transaction. A bank transfer is one example: subtracting money from one account and adding it to another must be committed together.
Keep transactions short. Long transactions hold locks, keep old row versions alive under MVCC, and increase the chance of conflicts. Do database work inside the transaction, but perform slow network calls, user interaction, and file operations outside it.
A safe transaction shape
Validate input before starting when possible. Then begin the transaction, perform related changes, check important results, and commit. If any required step fails, roll back.
CREATE TABLE accounts (
id integer PRIMARY KEY,
balance numeric(12, 2) NOT NULL CHECK (balance >= 0)
);
INSERT INTO accounts (id, balance)
VALUES (1, 100.00), (2, 50.00);
BEGIN;
UPDATE accounts
SET balance = balance - 30.00
WHERE id = 1
AND balance >= 30.00;
-- The application must verify that exactly one row changed.
UPDATE accounts
SET balance = balance + 30.00
WHERE id = 2;
COMMIT;
SELECT id, balance
FROM accounts
ORDER BY id;The conditional debit prevents the balance from becoming negative. In application code, check the number of affected rows. If it is zero, the source account does not exist or has insufficient funds, so issue ROLLBACK instead of continuing.
Database constraints remain important even when application validation exists. Application checks can race with other transactions. A CHECK, UNIQUE, or foreign-key constraint is enforced by the database at the point where the change is committed.
Choose the right isolation and locks
Use the weakest isolation level that preserves the rule your operation needs. Stronger isolation can reduce concurrency and cause more retries.
| Requirement | Useful approach | Main cost |
|---|---|---|
| Independent updates | Read committed transaction | A later query can see newer committed data |
| Stable reads during one operation | Repeatable read or snapshot | More conflicts or retained row versions |
| Rule depends on a set of rows | Serializable isolation | Serialization failures and retries |
| Read a row, then modify it | `SELECT ... FOR UPDATE` | Other writers wait for the lock |
If two transactions can update the same logical object, update it with a single conditional statement or lock it before making a decision. Keep the order of locking consistent. For example, always lock accounts in ascending ID order. This reduces deadlocks.
Make retries safe
Deadlocks and serializable transactions can fail even when the SQL is correct. The application should retry the complete transaction, not only the statement that failed. Use a small limit, backoff between attempts, and a new transaction for every attempt.
Design operations to be idempotent. An idempotent operation has the same effect when repeated. A request identifier stored with a payment can prevent a client retry from creating two payments.
Review transaction design
Before shipping, identify the transaction's invariant, its expected duration, and the rows it reads and writes. Confirm that constraints protect the invariant, that failures roll back all required changes, and that metrics record duration, retries, and deadlocks.
Exercise
Why should an application retry a whole transaction after a serialization failure?
Show answer
The database rejected the transaction's overall view of concurrent changes. Retrying only one statement would not recreate a consistent transaction.