Transactions: all or nothing
Moving 100 from account A to account B is two statements. If the server crashes between them, the money has left A and never reached B.
A transaction groups statements so they behave as one:
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 'A';
UPDATE accounts SET balance = balance + 100 WHERE id = 'B';
COMMIT;BEGINstarts it.COMMITmakes every change permanent at once. Other users see none of them before this moment, and all of them after.ROLLBACKthrows all of them away. So does a crash, or losing the connection, beforeCOMMIT.
That’s the “A” in ACIDACIDAtomic, Consistent, Isolated, Durable: the guarantees a database transaction gives.Open in glossary →: atomic, all or nothing.
Without BEGIN, each statement is its own little transaction, committed immediately. That’s called autocommit, and it’s how most tools and drivers start.
Two habits:
- Keep transactions short. While a transaction is open, the rows it changed stay locked, and others who want to change them wait.
- Never wait for something slow inside a transaction: a user clicking a button, an email being sent, an HTTP call to a payment provider. Do that before or after.
- Autocommit: every statement outside
BEGIN … COMMITis a transaction on its own; JDBC, psycopg and most drivers default to it or to an implicitBEGIN, depending on configuration. ORMs and Spring open transactions around methods. - Errors in PostgreSQL: any error puts the transaction into the aborted state; every following statement fails with “current transaction is aborted, commands ignored until end of transaction block” until
ROLLBACK. To continue after an expected error (a unique violation you want to handle), useSAVEPOINT s; … ROLLBACK TO SAVEPOINT s;. MySQL rolls back only the failed statement and keeps the transaction going, which surprises people moving the other way. - Durability:
COMMITreturns after the WALWrite-ahead logA log where the database records every change before applying it, so committed data survives crashes.Open in glossary → record is flushed;synchronous_commit = offtrades a small window of data loss for latency; synchronous replication waits for a replica too. - Long transactions hold row locks, keep old row versions alive (MVCCMVCCMulti-version concurrency control: writers create new row versions so readers never wait for them.Open in glossary → bloat, vacuum can’t clean), and with
idle in transactionsessions they also hold a pooled connection. Guard rails:idle_in_transaction_session_timeout,statement_timeout,lock_timeout, monitoringxact_startinpg_stat_activity. - DDL is transactional in PostgreSQL (a failed migration rolls back cleanly), not in MySQL.
- Boundaries: a transaction lives inside one database. Across services, use the transactional outboxTransactional outboxSaving an outgoing message in the same database transaction as the data change, and publishing it afterwards.Open in glossary → and sagas, not distributed transactions.
Predict the output
In PostgreSQL, the INSERT fails with a unique-constraint error. What happens to the UPDATE on the next line?
BEGIN;
INSERT INTO customers (email, name) VALUES ('ana@example.com', 'Ana'); -- email already exists
UPDATE products SET stock = stock - 1 WHERE id = 7;
COMMIT;After an error, PostgreSQL marks the whole transaction as failed. Every following statement is rejected with 'current transaction is aborted, commands ignored until end of transaction block', and COMMIT turns into a ROLLBACK. To recover from an expected error and continue, set a SAVEPOINT before the risky statement and ROLLBACK TO SAVEPOINT after the error. (MySQL behaves differently: it rolls back only the failed statement.)
-- place an order: all three changes or none
BEGIN;
INSERT INTO orders (customer_id, total) VALUES (42, 19.80) RETURNING id; -- say it returns 1001
INSERT INTO order_items (order_id, product_id, quantity, unit_price) VALUES (1001, 7, 2, 9.90);
UPDATE products SET stock = stock - 2 WHERE id = 7 AND stock >= 2; -- 0 rows → ROLLBACK
COMMIT;
-- continue after an expected error
BEGIN;
SAVEPOINT before_tag;
INSERT INTO tags (name) VALUES ('sql'); -- may violate UNIQUE
ROLLBACK TO SAVEPOINT before_tag; -- only if it failed
INSERT INTO lesson_tags (lesson_id, tag) VALUES (5, 'sql');
COMMIT;Money that disappears
Tap the line with the bug.
-- called by the app, autocommit is on
UPDATE accounts SET balance = balance - 100 WHERE id = 'A';
-- the app logs the transfer, then:
UPDATE accounts SET balance = balance + 100 WHERE id = 'B';Hint: With autocommit on, when does each UPDATE become permanent?
Each statement is committed on its own, immediately. If the app crashes, is redeployed or loses the connection after the first UPDATE, account A has lost 100 and account B never gets it. Nothing will ever undo the first statement.
Put both changes in one transaction:
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 'A' AND balance >= 100;
UPDATE accounts SET balance = balance + 100 WHERE id = 'B';
COMMIT;Now a crash before COMMIT undoes both. The added AND balance >= 100 makes the first UPDATE change 0 rows when there isn’t enough money; the app checks the row count and runs ROLLBACK instead of COMMIT.
Deep diveIdle in transaction: the session that held a lock for an hourInterview favorite
At 14:02 every checkout starts timing out. pg_stat_activity shows hundreds of sessions waiting on a lock, all behind one session in state idle in transaction, open since 13:05. A developer had opened a transaction in a console, run UPDATE products SET … WHERE id = 7 to fix a typo, and gone to lunch. Product 7 is the bestseller; every order that touches it waits for that row lock, then the connection pool fills up, then the whole app stops.
The same shape appears in code: a request opens a transaction, updates a row, then calls a payment API that hangs for 60 seconds. Under load, the pool is exhausted by sessions doing nothing.
How to answer:
- Find it:
SELECT pid, state, xact_start, wait_event_type, query FROM pg_stat_activity ORDER BY xact_startandpg_blocking_pids(pid)to see who blocks whom. Terminate withpg_terminate_backend(pid). - Prevent it:
idle_in_transaction_session_timeout(kill sessions idle inside a transaction after, say, 30 s),lock_timeoutfor app and migration roles,statement_timeout; autocommit or read-only defaults in consoles. - Design: no network calls inside transactions; reserve with a status (
PENDING), call the provider outside, then confirm in a second short transaction (and reconcile with an outbox or job if the confirmation is lost). - Side effects: long transactions also stop vacuum from removing dead rows anywhere in the database, so a forgotten session causes bloat even without locks.
- Statements autocommit unless inside
BEGIN … COMMIT. A crash or disconnect beforeCOMMITrolls back. - PostgreSQL: an error aborts the whole transaction; use savepoints to recover. MySQL rolls back only the statement.
- Long or idle transactions hold locks, pool connections and old row versions:
idle_in_transaction_session_timeout,lock_timeout,statement_timeout. - No network calls inside transactions; one database per transaction, outbox/sagas across services.
SET lock_timeout = '2s';
BEGIN;
SAVEPOINT s1;
UPDATE accounts SET balance = balance - 100 WHERE id = 'A' AND balance >= 100;
-- 0 rows? ROLLBACK; otherwise:
UPDATE accounts SET balance = balance + 100 WHERE id = 'B';
COMMIT;Check this part
The server crashes after the first of two UPDATEs inside BEGIN, before COMMIT. What is saved?
Why not call a payment API inside a database transaction?
In PostgreSQL, how do you continue a transaction after an expected unique violation?
What does a session left "idle in transaction" for an hour cause?