Transactions & ACID
What a transaction is, the four ACID properties and how databases implement each, commit and rollback, savepoints, and using transactions correctly from application code.
A transaction groups several operations into a single logical unit: either all of them take effect, or none do. Without transactions, a crash or a concurrent user could leave data half-updated — money debited but never credited.
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT; -- both changes become permanent together
-- or ROLLBACK; -- undo everything since BEGINACID
| Property | Promise | Implemented with |
|---|---|---|
| Atomicity | All or nothing, even if the server crashes mid-transaction | Undo information (undo logs, or MVCC versions) + WAL |
| Consistency | Each transaction moves the database from one valid state to another: constraints, foreign keys and invariants hold | Constraints and triggers in the DB, plus correct application logic |
| Isolation | Concurrent transactions don't see each other's partial work; the result is as if they ran in some order (to a configurable degree) | Locks and/or MVCC (Isolation levels) |
| Durability | Once committed, data survives crashes and power loss | WAL fsynced at commit; replication for machine failures |
How atomicity and durability work
After a crash, recovery redoes committed work from the WAL and undoes (or ignores, under MVCC) anything uncommitted. See Storage engines.
Savepoints
Partial rollback inside a transaction:
BEGIN;
INSERT INTO orders (...) VALUES (...);
SAVEPOINT before_items;
INSERT INTO order_items (...) VALUES (...); -- fails a constraint
ROLLBACK TO SAVEPOINT before_items; -- keep the order, retry the items
COMMIT;Transactions in application code
// Spring: declarative transactions
@Transactional
public void transfer(long from, long to, BigDecimal amount) {
Account a = repo.findByIdForUpdate(from); // SELECT ... FOR UPDATE
Account b = repo.findByIdForUpdate(to);
if (a.getBalance().compareTo(amount) < 0) throw new InsufficientFunds();
a.debit(amount);
b.credit(amount);
} // commit on return; rollback on RuntimeException
// Plain JDBC
conn.setAutoCommit(false);
try {
// ... statements ...
conn.commit();
} catch (SQLException e) {
conn.rollback();
throw e;
}# psycopg 3: the connection context manager commits or rolls back
with psycopg.connect(dsn) as conn:
with conn.transaction():
conn.execute("UPDATE accounts SET balance = balance - %s WHERE id = %s", (100, 1))
conn.execute("UPDATE accounts SET balance = balance + %s WHERE id = %s", (100, 2))
# SQLAlchemy
with Session(engine) as session, session.begin():
session.add(order)// node-postgres: one client for the whole transaction
const client = await pool.connect();
try {
await client.query("BEGIN");
await client.query("UPDATE accounts SET balance = balance - $1 WHERE id = $2", [100, 1]);
await client.query("UPDATE accounts SET balance = balance + $1 WHERE id = $2", [100, 2]);
await client.query("COMMIT");
} catch (e) {
await client.query("ROLLBACK");
throw e;
} finally {
client.release();
}Best practices
- Keep transactions short. Long transactions hold locks, block vacuum/purge (bloat), and increase conflicts. Never wait for user input or call slow external APIs inside one.
- Don't mix external side effects (sending email, charging a card) with a database transaction: a rollback can't unsend an email. Use the transactional outbox pattern — write an "event to send" row in the same transaction, and have a separate process deliver it.
- Retry on serialisation failures and deadlocks — they're normal under concurrency. Make the transaction body idempotent so a retry is safe.
- Know your framework's defaults: autocommit mode, transaction propagation (
@Transactionalon self-calls in Spring is silently ignored), and the default isolation level.
Beyond one database
ACID transactions are easy within a single database node. Across services or shards, you need distributed protocols (two-phase commit) or patterns like sagas with compensating actions — see Distributed transactions.
- A transaction is all-or-nothing: BEGIN … COMMIT / ROLLBACK.
- Atomicity and durability come from the WAL (+ undo); isolation from locks/MVCC; consistency from constraints plus correct logic.
- Durability depends on fsync settings and honest hardware.
- Keep transactions short, retry on conflicts, and never mix in irreversible external side effects (use an outbox).
QExplain ACID with a bank transfer example.easy
Atomicity: debit and credit both happen or neither does. Consistency: balances can't go negative and money isn't created or destroyed. Isolation: a concurrent report never sees the money missing from both accounts mid-transfer. Durability: once the transfer is confirmed, a crash won't undo it.