AlgoViz

ACID: atomicity and durability

medium 26 min

A transaction turns several changes into one: all of them happen or none do, and once committed they survive a crash.

Chapter mnemonic

ACID transaction guarantees

Two stamps, balanced books, a private booth, a fireproof receipt.

A committed transfer disappears after a restart. Which guarantee failed?

Durability. A committed result should survive a crash.

Video lesson · Chapter 1 of 5

A transfer has two halves and one promise

0:00 / 4:29

ACID in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

A transaction is a group of reads and writes that a database treats as one unit. It either commits, and everything in it counts, or it rolls back, and it is as if nothing happened.

ACID names four promises about transactions. Atomicity: all or nothing. Consistency: the rules of the data hold before and after. Isolation: transactions that run together do not disturb each other. Durability: what was committed stays, even after a crash.

Two of them, atomicity and durability, are about failures. Databases keep both with one idea: write down what you are going to do, on stable storage, before you do it. That record is the write-ahead log.

Why it exists

Machines stop at any moment, also between two lines of your program. If a transfer takes money from one account and the machine stops before adding it to the other, the money has vanished.

Without transactions every program would need its own repair code for every possible place to stop. With them the database does it once, and the program only says where the unit begins and ends.

A short history

  1. 1973

    IBM's Information Management System supports transactions with these properties, according to Gray and Reuter. The name ACID comes later.

  2. 1981

    Jim Gray's paper The Transaction Concept describes a transaction by atomicity, consistency and durability.

  3. 1983

    Theo Haerder and Andreas Reuter coin the word ACID, adding isolation.

  4. 1992

    C. Mohan and colleagues publish ARIES, a recovery method built on write-ahead logging with redo and undo.

Words to know

Commit
The moment after which the transaction counts and stays.
Rollback
Undo everything the transaction did.
Write-ahead log (WAL)
A file of changes that reaches disk before the data files do.
fsync
A call that asks the system to force a file to stable storage.
LSN
Log sequence number: the position of a record in the log.
Checkpoint
A mark that says from where recovery must start reading.
Constraint
A rule the database checks, such as a foreign key or balance >= 0.
Outbox
A table for messages, written in the same transaction as the data.

How it works

Step through the idea, or press Play.

Step 1 of 3

Begin. Everything from here is one unit

Understand it

Start here

Swapping stickers with a notebook

Asha and Lee want to swap stickers. Neither wants to end up with none. So they agree on a rule: write the swap in a notebook first, and tick it only when both stickers have moved.

The swap that cannot go half way
AshaLeeNotebookSwap?

The tick is the important moment. Before it, undo. After it, redo.

The idea

Four letters, four promises

  • Atomicity

    All or nothing. A failed part undoes the whole.

  • Consistency

    The rules hold before and after. Database and application share the work.

  • Isolation

    Transactions at the same time do not disturb each other. A topic of its own: isolation levels.

  • Durability

    Committed data survives a crash.

The life of a transaction

Constraints are normally checked at each statement. Deferred ones wait until the commit.

The two endings

COMMITROLLBACK
Every operation workedSomething went wrong, or you changed your mind
Changes become permanentAll changes are undone
Locks are releasedLocks are released
Others may see the changesAs if it had never started

Without it

Three disasters

DisasterWhat happenedWhat prevents it
Vanishing moneyAlice goes from 1,000to1,000 to 900, crash, Bob stays at 500.500. 100 is goneAtomicity
Phantom orderCard charged $299, stock 5 to 4, crash: no order, no emailA local transaction, plus an outbox and a repeatable charge
Double bookingTwo people see seat 14A free and both book itIsolation, or a unique constraint on the seat
The card service is another company. No transaction of your database can undo its charge, so atomicity alone does not solve the second one.

One transaction

  • BEGIN
  • Take $100 from Alice
  • Crash here: rolled back, Alice has $1,000
  • Give $100 to Bob
  • COMMIT: both or neither

Two separate statements

  • Take $100 from Alice
  • This is already committed
  • Crash here: $100 lost
  • Give $100 to Bob never runs

Atomicity

How the database can undo

A light switch is on or off, never half on. To behave like that, a database must be able to return to the old state until the moment of commit. There are three common ways.

WayHowOn failure
Undo log or rollback journalWrite the original values aside firstCopy them back
Shadow pagingChange a copy of the page, then swap one pointerThrow the copy away
Row versionsWrite a new version of the row and keep the old oneThe new version never becomes visible
SQLite's default journal is the first kind. PostgreSQL uses the third, with row versions: see concurrency control.

Durability

Log first, data later

The write path on one machine

A client sends COMMIT to one database machine. In memory, the log buffer is flushed first to the write-ahead log on disk. Changed pages in memory are written later to the data files on disk.
Step 1 happens before the client hears "committed". Step 2 may come much later.
  1. 1

    Write to the log

    A record such as: account 1, from 1000 to 900.

  2. 2

    Flush the log

    fsync makes sure it is on stable storage.

  3. 3

    Acknowledge the commit

    Only now the client hears that it worked.

  4. 4

    Update the data files later

    A background process writes the changed pages.

Why is this faster than writing the data itself? A transaction may change pages in ten different places, which means ten scattered writes. The log is one file that grows at its end, so one sequential write is enough.

One log record

FieldExampleUsed for
LSN12345Position in the log
Transaction42Who did it
TypeUPDATEAlso INSERT, DELETE, COMMIT
Table and pageaccounts, 789Where
Old value1000Undo
New value900Redo
Previous LSN12340The same transaction's record before this one
A teaching picture. Every database has its own format, and one that keeps row versions may not log old values.

What a flush costs, and group commit

C=1000tflush×g10005×1=200/s,10005×20=4000/sC = \frac{1000}{t_{\text{flush}}} \times g \qquad \frac{1000}{5} \times 1 = 200/\text{s}, \quad \frac{1000}{5} \times 20 = 4000/\text{s}
t is the flush time in milliseconds and g the number of transactions that share one flush. 5 ms is an assumption; measure your own disk.

Recovery

After the crash

Redo, then undo

This is the approach of ARIES. Redo repeats history, undo removes what never committed.

How long recovery takes

T≈log since checkpointreplay speed6 GB100 MB/s=60 sT \approx \frac{\text{log since checkpoint}}{\text{replay speed}} \qquad \frac{6\ \text{GB}}{100\ \text{MB/s}} = 60\ \text{s}
More frequent checkpoints mean less log to replay and more writing during normal work. Both figures are assumptions.

A checkpoint writes changed pages to the data files and notes how far they have caught up. Recovery starts there and not at the beginning of time. Unfinished transactions may reach back further, so undo can need older records.

Consistency

Who keeps the rules?

ConstraintRuleExample
Primary keyOne row per identifieruser_id is unique
Foreign keyThe other row must existAn order needs its user
NOT NULLA value is requiredemail is present
CHECKA condition on the rowbalance >= 0
UNIQUENo duplicatesOne account per email
TriggerYour code at a changeSet the time of the update

Taking 200fromanaccountwith200 from an account with 100 fails the CHECK, and the statement is rejected. A rule such as "the sum of all balances stays the same" spans many rows, and an ordinary CHECK cannot say that. The transaction that moves the money must keep it, at a suitable isolation level.

The database enforces

  • Primary and foreign keys
  • NOT NULL, UNIQUE, CHECK
  • Triggers and stored procedures
  • Data types

The application must

  • Express complex business rules
  • Keep rules that span many rows
  • Agree with outside services
  • Know what the data means

Code

Transactions in a program

Python
from contextlib import contextmanager@contextmanagerdef transaction(conn):    cur = conn.cursor()    try:        yield cur        conn.commit()    except Exception:        conn.rollback()        raise    finally:        cur.close()def transfer(conn, src, dst, amount):    if amount <= 0 or src == dst:        raise ValueError("bad transfer")    with transaction(conn) as cur:        cur.execute(            "UPDATE accounts SET balance = balance - %s"            " WHERE id = %s AND balance >= %s", (amount, src, amount))        if cur.rowcount != 1:            raise ValueError("insufficient funds")        cur.execute(            "UPDATE accounts SET balance = balance + %s WHERE id = %s",            (amount, dst))        if cur.rowcount != 1:            raise ValueError("no such account")        cur.execute(            "INSERT INTO transfers (src, dst, amount) VALUES (%s, %s, %s)",            (src, dst, amount))
A context manager for PostgreSQL with psycopg2. Commit at the end, rollback on any error, cursor always closed.

A savepoint marks a place inside a transaction. Rolling back to it undoes the later part only. It is useful when an optional step may fail. It is not a commit: if the transaction fails afterwards, everything goes.

Beyond one

When two systems must agree

A shop must save an order and publish a message. If it commits and then crashes, the message is missing. If it publishes first and the commit fails, the message lies.

The outbox

An order service writes an orders row and an outbox row into one database in one transaction. A relay reads the outbox row and publishes it to a message broker.
Two rows, one transaction. The relay may publish twice after a crash, so receivers ignore repeats.

The relay crashes, and nothing is lost

At least once, never zero times. Receivers remember the ids they have handled.
WayGivesCosts
OutboxThe message follows the data for certainA relay, and possible repeats
Two-phase commitAll databases or noneEveryone waits if the coordinator fails at a bad time
SagaLocal transactions with steps that undo themOthers see the states in between
The relay can follow the log itself: change data capture.

How much transaction do I need?

Trade-offs

The price of the promises

Durability is a dial

SettingReply comesCan lose
Asynchronous commitBefore the flushThe last moments before a crash
Local flushAfter the log is on this diskCommitted data if this disk dies
Synchronous standbyAfter a second machine has the logData only if both are lost
PostgreSQL's documentation says asynchronous commit can lose recent transactions without corrupting data, and that the risk window is at most three times the WAL writer delay.

Summary

The whole topic in one minute.

A transaction is all or nothing. Databases achieve that by keeping enough information to undo unfinished work, and by treating one COMMIT record as the single moment when everything counts.

Durability comes from writing the log to stable storage before answering. The data files follow later, and after a crash the log repairs them. One transaction covers one database: for two systems, use a local transaction with an outbox and steps that can be repeated safely.

  • Atomicity: all or nothing. Consistency: rules hold. Isolation: no interference. Durability: committed stays.
  • Log first, data later. The COMMIT record on disk is the moment that counts.
  • After a crash: redo what committed, undo or ignore what did not.
  • A log on one disk does not survive losing the disk.
  • Check the row count of every update.
  • One transaction covers one database. Across systems use an outbox and safe repeats.

Sources