Skip to content
Visual explainer 2h to learn 3 steps

ACID & transaction basics

Group statements into transactions and use savepoints and rollbacks.

By Invicly Tech, , in SQL & PostgreSQL. About 11 minutes to read.

Topic 21 of 30

In short

A transaction groups several statements into one all-or-nothing unit. Either every change is committed together or none are, so a transfer can never take money from one account without adding it to the other.

Explained simply

Many real actions need several changes at once. Moving money means taking it from one account and adding it to another. Placing an order means saving the order, its lines and lowering the stock. If the server crashes halfway, you must not end up with only half of it done.

A transaction is a box around those changes. You open it with BEGIN, make your changes, and close it with COMMIT to keep everything or ROLLBACK to throw everything away. Until you commit, other users do not see your changes.

ACID is a short name for the four promises a transaction gives you. Atomic: all or nothing. Consistent: rules like constraints still hold at the end. Isolated: other people's work running at the same time does not mix into yours. Durable: once COMMIT says yes, the data survives a crash or power cut.

A savepoint is a bookmark inside a transaction. If one step fails, you can go back to the bookmark and try something else, without losing the work done before it.

Press Play on a diagram to walk through it one step at a time.

CycleTransaction lifecycle
  1. 1
    BEGIN

    Open a transaction

  2. 2
    Run statements

    Changes are visible only to this session

  3. 3
    SAVEPOINT (optional)

    Mark a point you can roll back to

  4. 4
    COMMIT or ROLLBACK

    Make all changes durable, or discard them

  5. 5
    Next transaction

    The session is ready to BEGIN again

  6. Back to step 1
MapACID
ACID guarantees
  • Atomicity
    • All or nothing
  • Consistency
    • Constraints hold after commit
  • Isolation
    • Concurrent work does not interfere
  • Durability
    • Committed data survives a crash (WAL)
SequenceAn error inside a transaction
App
Postgres
  1. 1BEGIN; INSERT order
    App to Postgres: BEGIN; INSERT order
  2. 2INSERT line with bad product_id
    App to Postgres: INSERT line with bad product_id
  3. 3ERROR: violates foreign key
    Postgres to App: ERROR: violates foreign key
  4. 4UPDATE stock ...
    App to Postgres: UPDATE stock ...
  5. 5ERROR: current transaction is aborted
    Postgres to App: ERROR: current transaction is aborted
  6. 6ROLLBACK
    App to Postgres: ROLLBACK
  7. 7Nothing was saved, not even the order
    Postgres to App: Nothing was saved, not even the order

In depth

Autocommit, drivers and the aborted state

If you never type BEGIN, Postgres wraps every single statement in its own transaction and commits it at once. That is autocommit, and it is how psql behaves by default.

Drivers differ, so check yours. Python's psycopg is not in autocommit mode by default: it opens a transaction at your first statement, and nothing is saved until you call conn.commit() or leave a with conn.transaction() block. JDBC starts with autocommit on. ORMs usually manage transactions per request or per unit of work.

If any statement inside a transaction fails, the whole transaction becomes aborted. Every later statement returns "current transaction is aborted, commands ignored until end of transaction block" until you send ROLLBACK. That is a feature: Postgres refuses to let you commit half a job by accident. In psql, \set ON_ERROR_ROLLBACK interactive makes typing mistakes less painful by using a hidden savepoint before each statement.

  • psql: autocommit on by default
  • psycopg: transaction opens implicitly; you must commit
  • After an error, only ROLLBACK (or ROLLBACK TO SAVEPOINT) works
  • SELECT now() returns the same time for the whole transaction

How COMMIT becomes durable: the write-ahead log

Postgres does not rewrite table files on every change. It changes pages in memory (shared_buffers) and first records each change in the write-ahead log (WAL), a sequential journal on disk. On COMMIT it writes a commit record and flushes the WAL to durable storage (fsync) before telling you "COMMIT". The changed table pages are written later, in bulk, by the background writer and at checkpoints.

If the server crashes, recovery starts from the last checkpoint and replays the WAL, so every committed change comes back and uncommitted ones are ignored. That is durability, and it is also why Postgres can recover without a long repair step.

You can trade a little durability for speed with synchronous_commit = off, per transaction if you like. COMMIT then returns before the flush; a crash can lose the last fraction of a second of commits, but the database never becomes corrupt. It suits things like analytics events, never payments.

FlowWhat happens on COMMIT
  1. 1
    Change pages in memory

    shared_buffers holds the dirty pages

  2. 2
    Append WAL records

    A journal entry for every change

  3. 3
    Write commit record

    Marks the transaction as committed

  4. 4
    Flush WAL to disk

    fsync; then COMMIT returns to the app

  5. 5
    Pages written later

    Background writer and checkpoints

Atomicity and consistency in practice

Rollback in Postgres is cheap. Changes are not undone row by row; the transaction is simply marked as aborted in the commit log (pg_xact), and the row versions it created become invisible and are later cleaned up by vacuum. So a rollback of a million-row insert is instant, although the space is reclaimed later.

Consistency means the data obeys your rules after every commit. Postgres checks constraints at the end of each statement. Some changes need a moment of inconsistency, such as swapping two rows' positions under a UNIQUE constraint, or inserting two rows that reference each other. For those, declare the constraint DEFERRABLE and run SET CONSTRAINTS ALL DEFERRED inside the transaction; the check then happens at COMMIT.

Note that the C in ACID only covers rules the database knows. A business rule kept only in app code is consistent only if every writer follows it, which is why constraints matter.

  • ROLLBACK just marks the transaction aborted
  • Constraints are checked per statement by default
  • DEFERRABLE + SET CONSTRAINTS ALL DEFERRED checks at COMMIT
  • Most DDL is transactional and can be rolled back too

Savepoints and keeping transactions short

SAVEPOINT name marks a point. ROLLBACK TO SAVEPOINT name undoes everything after it and clears the aborted state, so the transaction can continue. RELEASE SAVEPOINT name forgets the bookmark but keeps the work. ORMs use savepoints for nested transactions: Django's nested atomic() blocks and SQLAlchemy's begin_nested() both create them.

Typical use: importing 1,000 rows where a few may be bad. Put a savepoint before each row; on error, roll back to it, log the row and continue. Use them in moderation: each savepoint starts a subtransaction, and a transaction with thousands of them can slow down the whole server.

The most important habit is to keep transactions short. An open transaction holds its locks and stops vacuum from removing old row versions. Never wait for a user, an HTTP call or an email inside one. The setting idle_in_transaction_session_timeout ends sessions that sit idle inside a transaction for too long.

Learn it in 3 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Use BEGIN, COMMIT and ROLLBACK~40m
  2. 2
    Explain each ACID property~40m
  3. 3
    Use savepoints for partial rollback~40m

Key points

  • Without BEGIN, each statement is its own auto-committed transaction.
  • An error inside a transaction aborts it; you must ROLLBACK before continuing.
  • ROLLBACK TO SAVEPOINT undoes part of the work and keeps the rest.
  • COMMIT returns only after the change is safely written to the WAL.

Key terms

Tap a card to flip it. 0/5 known

Examples

sql
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;

SAVEPOINT before_fee;
INSERT INTO fees (account_id, amount) VALUES (1, 2.50);
-- fee rule was wrong: undo just the fee
ROLLBACK TO SAVEPOINT before_fee;

COMMIT;  -- the transfer is saved, the fee is not

Placing an order as one transaction in Python

An order must save the order row, its line and reduce stock, or do nothing. Step 1: open a transaction block with psycopg's conn.transaction(). Step 2: decrease stock only if enough is left; the WHERE stock >= 2 check and the update happen in one statement. Step 3: if no row was updated, raise an error, which rolls everything back. Step 4: on leaving the block without an error, psycopg commits.

python
import psycopg

with psycopg.connect("dbname=shop") as conn:
    with conn.transaction():
        order_id = conn.execute(
            "INSERT INTO orders (customer_id) VALUES (%s) RETURNING id", (7,)
        ).fetchone()[0]
        conn.execute(
            "INSERT INTO order_items (order_id, product_id, qty) VALUES (%s, %s, %s)",
            (order_id, 42, 2))
        cur = conn.execute(
            "UPDATE products SET stock = stock - 2 WHERE id = 42 AND stock >= 2")
        if cur.rowcount == 0:
            raise ValueError("out of stock")  # rolls back all three statements

Importing rows and skipping the bad ones

A CSV import has 3 rows and one breaks a CHECK. Without savepoints, the error aborts the whole transaction. Step 1: set a savepoint before each risky insert. Step 2: when an insert fails, roll back to that savepoint, which clears the error. Step 3: carry on and commit; the good rows are saved and the bad one is skipped. In app code you would loop and log each failure.

sql
BEGIN;
SAVEPOINT r1;
INSERT INTO products (sku, price) VALUES ('A1', 9.99);
RELEASE SAVEPOINT r1;

SAVEPOINT r2;
INSERT INTO products (sku, price) VALUES ('A2', -5);  -- ERROR: check constraint
ROLLBACK TO SAVEPOINT r2;                            -- transaction is usable again

SAVEPOINT r3;
INSERT INTO products (sku, price) VALUES ('A3', 4.50);
RELEASE SAVEPOINT r3;
COMMIT;  -- A1 and A3 saved

Quick reference

  • BEGIN; ... COMMIT; or ROLLBACK; to discard everything since BEGIN
  • SAVEPOINT s; ROLLBACK TO SAVEPOINT s; RELEASE SAVEPOINT s;
  • After any error the transaction is aborted until ROLLBACK
  • \set ON_ERROR_ROLLBACK interactive psql keeps your transaction alive after typos
  • SET LOCAL synchronous_commit = off; faster commit, may lose the last moments on crash
  • now() is the transaction start time; clock_timestamp() is the real current time
  • idle_in_transaction_session_timeout ends sessions left idle inside a transaction

Common mistakes

  • Forgetting BEGIN, so the first UPDATE commits on its own.
  • Leaving transactions open while waiting on users or network calls.
  • Ignoring the "current transaction is aborted" error and continuing.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1An INSERT fails inside a transaction. You run another SELECT. What happens?

Question 2

2When does COMMIT return success in PostgreSQL with default settings?

Question 3

3Which ACID property does a CHECK (balance >= 0) constraint mainly support?

Question 4

4Why is a long-running idle transaction harmful?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    In psql, start a transaction, delete all rows from a test table, check the count, then roll back and check again.

  2. Exercise 2medium

    Transfer 50 from account 1 to account 2 so that it fails completely if account 1 would go below zero.

  3. Exercise 3hard

    Two rows in a playlist must swap their position values, and (playlist_id, position) is UNIQUE. Make the swap possible in one transaction.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Do I need BEGIN for a single statement?
No. A single statement is always atomic on its own, because Postgres wraps it in its own transaction. Use BEGIN when several statements must succeed or fail together.
Is COMMIT slow?
Each COMMIT waits for a disk flush of the WAL, often well under a millisecond on SSDs. Thousands of tiny transactions add up, so batch many small writes into one transaction.
Can I roll back a CREATE TABLE or ALTER TABLE?
Yes, in PostgreSQL most DDL is transactional. A few commands, such as CREATE INDEX CONCURRENTLY and CREATE DATABASE, cannot run inside a transaction block.

Go deeper

ShareXLinkedInWhatsApp