Correctness under concurrency · core
Transactions in SQL: BEGIN, COMMIT and ROLLBACK
In SQL, a transaction is BEGIN, your statements, then COMMIT, or ROLLBACK when anything fails, so the change happens fully or not at all. Keep it short, run it on one connection, choose the isolation level it needs, and never put a slow external call inside it.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- BEGIN; ...; COMMIT; or ROLLBACK on error. Without BEGIN, each statement is its own transaction (autocommit).
- What you get: the statements succeed or fail together, constraints are checked, other sessions do not see your uncommitted rows, and after COMMIT the change survives a crash (the write-ahead log).
- In Postgres, after an error inside a transaction, every following statement fails until ROLLBACK.
- SAVEPOINT lets you roll back part of a transaction.
- Set the isolation level when the default is not enough: BEGIN ISOLATION LEVEL SERIALIZABLE (Postgres defaults to READ COMMITTED, MySQL InnoDB to REPEATABLE READ). At SERIALIZABLE, retry the whole transaction when it fails with a serialization error (SQLSTATE 40001).
- Keep transactions short: never wait for a user or call a slow external API (payment gateway) while holding a transaction open; locks and connections stay taken.
- In Node, run the whole transaction on one connection from the pool (pool.connect(), or the ORM's $transaction / db.transaction()).
- A transaction cannot include an external side effect: charge the card, then record the result idempotently; or use the outbox pattern.
The red pen
Common traps: mistake → fix
Mistake: Two queries in a row are atomic
Fix: without a transaction, a crash between them leaves half the change.
Mistake: Wrap the payment API call inside the DB transaction for safety
Fix: the external call cannot be rolled back and it holds locks for seconds.
Easy to hard
Questions interviewers ask, easy to hard
- What is a transaction? Show the SQL for a bank transfer.
- What happens if the server crashes between the debit and the credit?
- How do you run a transaction from Node with a connection pool?
- When would you raise the isolation level, and what must the code do then?
- Why should transactions be short?
Practise
Practise with these questions
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.