Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 20 min · revision 3

ACID and Where a Transaction Begins and Ends

Treat ACID as four concrete promises PostgreSQL makes to your code, mark transaction boundaries in psycopg and SQLAlchemy, and recover from a failed statement with savepoints.

Contentsand lesson path

What you will learn

  • Explain atomicity, consistency, isolation and durability, and use BEGIN, COMMIT, ROLLBACK and savepoints to make multi-statement changes atomic.

Prerequisites: SQL Fundamentals

01. Why it matters

Placing an order on a reading-list service is not one write. It inserts a row into orders, one row per book into order_items, decrements stock, and appends to an audit log — four or five statements, in one HTTP request. If the process dies after the second statement, or the third one fails, you ship a book nobody paid for, or pay for a book that is not shipped.

You met BEGIN and ROLLBACK in the SQL lessons as a safety net for risky ad-hoc updates. Application code needs the same tool for a different reason: requests run concurrently, statements fail, and processes restart at the worst moment. This lesson pins down the four promises a transaction gives you, shows exactly where a transaction starts and ends in the Python drivers you already use, and teaches the one recovery move that saves a transaction after a failed statement: the savepoint. The rest of the skill builds on this: isolation levels, anomalies and locking all assume you control your boundaries precisely.

02. The four promises, in database terms

Atomicity means a transaction takes effect completely or not at all. There is no observable state where the debit exists without the credit. Consistency means every declared rule — primary keys, foreign keys, CHECK constraints — holds before the transaction and after it; a statement that would break a rule fails, and a failed statement can take the whole transaction with it. Isolation means concurrent transactions do not observe each other's half-finished work; this is the subtle one, it comes in degrees, and it occupies the rest of this skill. Durability means that once COMMIT returns success, the change survives a power cut, because the database wrote it to a write-ahead log on disk before answering (with the default settings fsync = on and synchronous_commit = on; turning either off trades that promise for speed).

Atomicity and consistency are easy to watch. To run the demos in this lesson, start the throwaway ti-pg container and the uv environment from the anomalies lab (PostgreSQL 17 on port 55436, psycopg[binary]==3.3.9; add sqlalchemy==2.1.9 for the SQLAlchemy snippet). Run the files in the order shown, because each one starts from the rows the previous one left. setup.py creates two accounts and one book:

Python · setup.py
import psycopg

DSN = "postgresql://lab:lab@localhost:55436/tilab"
with psycopg.connect(DSN) as conn:  # commits on a clean exit
    conn.execute("DROP TABLE IF EXISTS accounts, books")
    conn.execute("CREATE TABLE accounts (id int PRIMARY KEY, owner text NOT NULL,"
                 " balance int NOT NULL CHECK (balance >= 0))")
    conn.execute("INSERT INTO accounts VALUES (1, 'Ada', 100), (2, 'Grace', 50)")
    conn.execute("CREATE TABLE books (id int PRIMARY KEY, title text NOT NULL)")
    conn.execute("INSERT INTO books VALUES"
                 " (1, 'Designing Data-Intensive Applications')")
print("accounts and books ready")

This transfer moves 60 from Grace, who holds 50, to Ada, and the CHECK (balance >= 0) forbids negative balances. The function credits Ada first and debits Grace second, so the first statement succeeds and only the second one breaks the rule:

Python · transfer.py
import psycopg

DSN = "postgresql://lab:lab@localhost:55436/tilab"

def transfer(conn, src, dst, amount):
    try:
        with conn.transaction():          # BEGIN ... COMMIT
            conn.execute("UPDATE accounts"
                         " SET balance = balance + %s WHERE id = %s",
                         (amount, dst))   # credit: succeeds
            print("inside: dst now", conn.execute(
                "SELECT balance FROM accounts WHERE id = %s",
                (dst,)).fetchone()[0])
            conn.execute("UPDATE accounts"
                         " SET balance = balance - %s WHERE id = %s",
                         (amount, src))   # debit: breaks the CHECK
        return True
    except psycopg.errors.CheckViolation as err:
        print("transfer rejected:", err.diag.message_primary)
        return False                     # the credit is undone too

conn = psycopg.connect(DSN, autocommit=True)  # transaction() owns BEGIN
rows = "SELECT id, owner, balance FROM accounts ORDER BY id"
print("before:", conn.execute(rows).fetchall())
transfer(conn, src=2, dst=1, amount=60)  # Grace (50) -> Ada (100)
print("after: ", conn.execute(rows).fetchall())
Expected output · PostgreSQL 17.12 (long line wrapped)
before: [(1, 'Ada', 100), (2, 'Grace', 50)]
inside: dst now 160
transfer rejected: new row for relation "accounts" violates
                   check constraint "accounts_balance_check"
after:  [(1, 'Ada', 100), (2, 'Grace', 50)]

Inside the transaction Ada briefly held 160. Then the second UPDATE failed, and the first one — already executed — vanished with it: after the rollback both balances are exactly what they were. Nothing leaked. (Had the code debited first, the very first statement would have failed and there would have been nothing to undo, so the demo would not show atomicity at all.) Notice the layering: the constraint failed the statement, and atomicity extended that failure to the whole transaction. Durability needs no code from you; the write-ahead log does the work at COMMIT time.

One boundary on the promise: consistency only covers rules the database knows about. "A transfer must reference a real account" becomes consistency when you declare a foreign key; "the warehouse must keep two copies of each bestseller" cannot be expressed as a table constraint, so it lives in your code, guarded by the locking techniques later in this skill. Atomic, durable, constrained where possible — and correct by construction everywhere else.

03. Where a transaction begins

In PostgreSQL every statement runs inside a transaction; there is no statement "outside" one. With autocommit off, the first statement opens a transaction that lasts until COMMIT or ROLLBACK; with autocommit on, every statement is its own tiny transaction. What changes between drivers is only who says BEGIN.

In psycopg (the driver behind SQLAlchemy in these lessons) the default is autocommit off: the transaction opens silently at the first execute, and conn.commit() or conn.rollback() ends it. The with conn.transaction(): block above is psycopg doing the BEGIN for you, committing on clean exit and rolling back on an exception — on a connection opened with autocommit=True, as transfer.py does. On a default connection that has already run a statement (the before: SELECT, say), psycopg is already inside its implicit transaction, so transaction() opens a SAVEPOINT instead: leaving the block releases the savepoint but commits nothing until you call conn.commit(). SQLAlchemy Core draws the boundary with a block too. This script reads Ada's balance inside the block, from a second pooled connection while the block is still open, and again after it has ended:

Python · boundaries.py
from sqlalchemy import create_engine, text

URL = "postgresql+psycopg://lab:lab@localhost:55436/tilab"
engine = create_engine(URL)
balance = text("SELECT balance FROM accounts WHERE id = 1")

with engine.begin() as conn:      # BEGIN on first statement
    conn.execute(text("UPDATE accounts"
                      " SET balance = balance + 5 WHERE id = 1"))
    print("balance inside the block:", conn.execute(balance).scalar())
    with engine.connect() as other:   # a second pooled connection
        print("other connection, before commit:",
              other.execute(balance).scalar())
# leaving the block committed; a raised exception would roll back
with engine.connect() as other:
    print("other connection, after commit:", other.execute(balance).scalar())
Expected output · PostgreSQL 17.12, SQLAlchemy 2.1.9
balance inside the block: 105
other connection, before commit: 100
other connection, after commit: 105

Everything you run on that connection inside the block shares one transaction, and nothing outside it does: the second connection still saw 100 while the block was open, and saw 105 only after the block committed. Two habits follow. First, decide the boundary by the invariant you need — the order example needs all four writes together, so the block wraps all of them. Second, end transactions as soon as the work is done: an open transaction holds locks and pins storage, which you will measure in a later lesson. The connection-pool lesson covers how pools make a forgotten boundary worse.

04. After a failed statement: abort and savepoints

A failed statement leaves the transaction aborted: PostgreSQL refuses every further statement in it, because it no longer knows a consistent state to continue from. Even COMMIT cannot save it: the server accepts the command, rolls back, and answers ROLLBACK. This is what it looks like from psql, inserting books where book 1 already exists:

SQL · abort.sql, run with docker exec -i ti-pg psql -U lab -d tilab < abort.sql
BEGIN;
INSERT INTO books VALUES (2, 'The Phoenix Project');
INSERT INTO books VALUES (1, 'Designing Data-Intensive Applications');
INSERT INTO books VALUES (3, 'The Deadline');
COMMIT;
Expected output · psql's answer to each statement
BEGIN
INSERT 0 1
ERROR:  duplicate key value violates unique constraint "books_pkey"
DETAIL:  Key (id)=(1) already exists.
ERROR:  current transaction is aborted, commands ignored until end of transaction block
ROLLBACK

Sometimes you want the transaction to survive one bad row: an import should commit its good rows and skip the bad ones. That is precisely what the aborted state forbids — unless you mark a return point before the risky statement. SAVEPOINT names a position inside the transaction; ROLLBACK TO SAVEPOINT undoes work back to that name and keeps the transaction alive. psycopg exposes this as a nested transaction() block:

SQL · savepoint.sql, the statements a nested block sends (run it like abort.sql)
BEGIN;
INSERT INTO books VALUES (2, 'The Phoenix Project');      -- ok
SAVEPOINT row_3;
INSERT INTO books VALUES (1, 'Designing Data-Intensive Applications');
ROLLBACK TO SAVEPOINT row_3;   -- undo only this row
INSERT INTO books VALUES (3, 'The Deadline');             -- ok
COMMIT;                        -- 2 rows inserted, 1 skipped

After savepoint.sql the table holds books 1, 2 and 3. The Python version below imports four more rows, one of which (book 2) already exists, inside one outer transaction:

Python · import_books.py, an import loop that skips bad rows
import psycopg

DSN = "postgresql://lab:lab@localhost:55436/tilab"
rows = [(4, "Accelerate"), (2, "The Phoenix Project"),  # 2 already exists
        (5, "Team Topologies"), (6, "The Mythical Man-Month")]
imported = skipped = 0

with psycopg.connect(DSN, autocommit=True) as conn:
    with conn.transaction():                 # BEGIN ... COMMIT
        for row in rows:
            try:
                with conn.transaction():     # SAVEPOINT ... RELEASE
                    conn.execute("INSERT INTO books VALUES (%s, %s)", row)
                imported += 1
            except psycopg.errors.UniqueViolation:
                skipped += 1                 # rolled back to the savepoint
    print(f"imported {imported}, skipped {skipped}")
    print("rows now:", conn.execute("SELECT count(*) FROM books").fetchone()[0])
Expected output
imported 3, skipped 1
rows now: 6

The inner block commits nothing by itself — savepoints are marks inside the one real transaction, and only the outer COMMIT makes the import permanent. If the process dies mid-import, every row goes, good and bad alike. That is the deal: atomicity at the size of your outermost boundary, forgivable failures inside it.

05. Check your understanding

Practice check · 3 questions

Boundaries and recovery

Three situations about where transactions start and how they survive failures.

Q1. In the SQLAlchemy snippet, which statements are inside the transaction?
Q2. A script opens `conn = psycopg.connect(DSN)` with default settings and runs a SELECT. It then runs an UPDATE inside `with conn.transaction():`, the block exits cleanly, and the script ends without calling `conn.commit()`. What happens to the UPDATE?
Q3. A transfer debits account 1 and inserts a ledger row that credits `account_id = 99`, but no account 99 exists. `ledger.account_id` has no foreign key, so both statements succeed and the transaction commits. Which ACID property let you down?
Practice only: not graded, not saved, not evidence.

06. Apply it

Reuse the ti-pg container and setup.py from this lesson, then:

  1. Model a two-account transfer in one transaction, with a CHECK that forbids negative balances, and show a rejected transfer leaving both balances untouched.
  2. Add an orders flow — insert into orders and two order_items rows in one transaction — and prove that a bad second item rolls back the order row too.
  3. Feed the savepoint import loop a list of ten rows where three break constraints, and record the imported and skipped counts.

07. Review prompt

Without looking back: name the four ACID promises in your own words, each tied to something concrete (a rejected transfer, a constraint, a write-ahead log). Where does a transaction begin in psycopg with default settings, and what does engine.begin() wrap? What does the server answer to a statement sent after one has failed, and what does COMMIT do then? Finally, explain what a savepoint lets an import loop do that a plain transaction cannot.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check