Skip to the workspace
Pebellslearn by building
High Level Database Concepts  ›  Lesson

Transactions and ACID

ACID 14 minA transaction groups changes so they are atomic, consistent, isolated and durable, and PostgreSQL aborts the whole transaction when any statement fails.

postgresql dba / Transactions and ACID

Explore each scene at your own pace.

01 · The rule

The rule

Transactions and ACID

A member ends a ride. Pedal must close the rental, charge the fare and mark the bike as free. If the server crashes after the charge but before the bike is freed, the member pays and the bike stays "in use" forever. A transaction makes those three changes one unit.

The rule

All or nothing, always valid, unseen until done, kept once committed.

Those four phrases are ACID:

  • Atomicity: all or nothing. Every statement in the transaction takes effect, or none does.
  • Consistency: always valid. Each transaction moves the database from one state that satisfies every constraint to another.
  • Isolation: unseen until done. Other sessions do not see half-finished work.
  • Durability: kept once committed. After COMMIT returns, the change survives a crash or power cut.
BEGIN;
UPDATE rentals SET ended_at = now(), fare = 120.00 WHERE rental_id = 9041;
INSERT INTO payments (rental_id, amount) VALUES (9041, 120.00);
UPDATE bikes SET available = true WHERE bike_id = 7;
COMMIT;

Some PostgreSQL behaviour every DBA should know:

  • Autocommit: without BEGIN, each statement is its own transaction and commits at once.
  • An error poisons the transaction. After a failed statement, PostgreSQL answers every further command with current transaction is aborted until you ROLLBACK.
  • Savepoints (SAVEPOINT s1; ... ROLLBACK TO s1;) undo part of a transaction without abandoning all of it.
  • Isolation levels: the default is READ COMMITTED, where each statement sees data committed before it began. REPEATABLE READ keeps one snapshot for the whole transaction, and SERIALIZABLE also guarantees the result matches some one-at-a-time order, at the cost of occasional retries.
  • Long transactions are expensive: they hold locks and stop old row versions being cleaned up, as the next lesson shows.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.