Transactions and rollback
Local baseline: Node.js 22.16.0. Actual local SQLite 3.49.1 via experimental node:sqlite. No third-party packages or external connections.
Try the local example
import {DatabaseSync} from 'node:sqlite';const db=new DatabaseSync(':memory:');try { db.exec('CREATE TABLE stock(id INTEGER PRIMARY KEY, qty INTEGER CHECK(qty>=0)); CREATE TABLE reservation(id INTEGER PRIMARY KEY); INSERT INTO stock VALUES(1,5); INSERT INTO reservation VALUES(1)'); function reserve(id){db.exec('BEGIN');try{db.prepare('UPDATE stock SET qty=qty-1 WHERE id=1').run();db.prepare('INSERT INTO reservation VALUES(?)').run(id);db.exec('COMMIT');}catch(error){db.exec('ROLLBACK');throw error;}} try{reserve(1);}catch{console.log('rolled back');} console.log(db.prepare('SELECT qty FROM stock').get().qty); reserve(2); console.log(db.prepare('SELECT qty FROM stock').get().qty); console.log(db.prepare('SELECT count(*) AS n FROM reservation').get().n);}finally{db.close();}Run node main.mjs in a disposable directory with the files shown. Expected standard output:
rolled back542An experimental warning is expected on stderr for this local version.
How it works
Begin, run related statements on the same connection, then commit. If a statement fails, roll back before releasing the connection. In the SQLite fixture a CHECK constraint rejects negative stock; a duplicate reservation also fails. The failure rolls back the earlier stock change. For PostgreSQL use a checked-out pg client for the whole transaction, not repeated pool.query calls. A network failure during commit can leave the outcome uncertain; reconcile with a durable request identifier before retrying. This lab does not test concurrent transactions or PostgreSQL isolation.
Common mistake
Do not split transaction statements across pooled connections. Do not retry an uncertain commit blindly or claim rollback reverses external effects like email.
Practice
Change the reservation ID to a new one and verify that the stock and reservation changes commit together.
Documentation: primary source. Candidate lookup: node-transactions-and-rollback-lookup. Prerequisite: node-connection-pooling (platform route unverified).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Transactions and rollback — knowledge check
Apply the lesson’s contracts and identify common boundary mistakes.
Why use the same checked-out client?
After the duplicate reservation fails, what is the stock?
A connection drops while COMMIT is being sent. What is safest?