Transactions in applications
Overview
A business operation may require several SQL statements to succeed together. Begin, execute, commit or roll back on the same connection. Treat a failed invariant as an error even when the database statement returns successfully. A transfer must not create or destroy money.
First example
BEGIN;UPDATE ai_account SET cents=cents-500 WHERE id=1 AND cents>=500;UPDATE ai_account SET cents=cents+500 WHERE id=2;SELECT SUM(cents) FROM ai_account;ROLLBACK;SELECT cents FROM ai_account ORDER BY id;Observed SQLite result (rows in JSON):
[ [ 10000 ], [ 20000 ], [ 0 ]]How it works
Use a conditional debit WHERE cents >= amount and inspect affected rows before crediting. Roll back on exceptions; a pool must not receive an unfinished transaction. Optimistic locking uses a version predicate and increments the version; zero affected rows indicate a missing or stale record or another failed predicate. Idempotency requires a unique request key and a check that repeated input matches the original; do not repeat external effects inside a retryable transaction.
Practical example
BEGIN;UPDATE ai_account SET cents=cents+1,version=version+1 WHERE id=1 AND version=99;SELECT changes();ROLLBACK;Observed SQLite result (rows in JSON):
[ [ 0 ]]Practice and mistakes
Practice: transfer 500 cents and reject an overdraft, then simulate a stale version. Hint: inspect rowcount before commit. Check total 30000 cents remains unchanged and stale update affects zero rows. Mistake: debit on one pooled connection and credit on another.
PostgreSQL 17 example — NOT RUN
BEGIN;SELECT 1 AS operation;ROLLBACK;Expected result, not executed: "Read-only transaction skeleton; actual application must use one connection."
Application transaction boundary
TypeScript node-postgres (illustrative, NOT RUN; pool is initialized). Use a single leased client, discard it if rollback fails.
const client = await pool.connect();let discard = false;try { await client.query('BEGIN'); const debit = await client.query('UPDATE ai_account SET cents=cents-$1 WHERE id=$2 AND cents >= $1', [500, 1]); if (debit.rowCount !== 1) throw new Error('Debit rejected'); const credit = await client.query('UPDATE ai_account SET cents=cents+$1 WHERE id=$2', [500, 2]); if (credit.rowCount !== 1) throw new Error('Credit rejected'); await client.query('COMMIT');} catch (error) { try { await client.query('ROLLBACK'); } catch { discard = true; } throw error;} finally { client.release(discard); }A failed COMMIT response can mean an unknown outcome; reconcile using an idempotency key before replaying.