Course contents

04. Database Fundamentals Lesson 7 of 10

ACID Properties

See atomicity, consistency, isolation and durability at work: row versions, constraints, snapshots, the WAL and fsync, crash recovery, and what durability costs.

15 minIntermediate10 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Atomicity: a transaction is marked committed or aborted in one step; aborted changes are never visible.
  • Consistency: the database enforces declared constraints; other invariants are the application’s job.
  • Isolation: transactions read committed snapshots, never another transaction’s partial work; the level sets how strict.
  • Durability: the WAL is flushed before COMMIT is acknowledged, and crash recovery replays it.
  • Durability costs latency on every commit; relaxing it or extending it to a standby are explicit trade-offs.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

ACID names four guarantees that a database transaction gives: Atomicity (all of its writes happen or none do), Consistency (it moves the data from one valid state to another), Isolation (concurrent transactions do not see each other's unfinished work) and Durability (once acknowledged, a commit survives crashes). The acronym is from 1983; each letter is implemented by a different mechanism with its own cost.

Why it exists

Applications run many operations at once on machines that crash. Without guarantees, every developer would have to reason about partial writes, interleavings and lost data in every code path. ACID moves that reasoning into the database: application code can treat a transaction as a single step that either happened completely and permanently, or not at all.

How it works

Atomicity. In Postgres every row change creates a new row version stamped with the transaction id; the commit log (pg_xact) records whether that id committed or aborted. Committing flips that status in one step, which makes all the versions visible together; aborting leaves them invisible until vacuum removes them. Engines such as InnoDB and Oracle update rows in place and keep undo logs to restore the old values on rollback.

Consistency. The database guarantees that declared constraints hold after every transaction: NOT NULL, CHECK, UNIQUE, primary and foreign keys, exclusion constraints, and anything enforced by triggers. A statement that would break one fails, and the transaction must roll back. Rules the schema does not express are the application's responsibility, which is why the "C" is often described as a property of the application using the other three letters.

Isolation. Postgres gives each statement (READ COMMITTED) or each transaction (REPEATABLE READ, SERIALIZABLE) a snapshot of committed data, and uses row locks for conflicting writes. Readers never see uncommitted changes. Weaker levels still allow some anomalies between concurrent transactions; the Isolation Levels lesson covers which.

Durability. Changes are first described in the write-ahead log (WAL). On COMMIT, Postgres flushes the WAL up to the commit record to stable storage (fsync or an equivalent) and only then answers. Changed data pages stay in shared buffers and are written to the data files later by the background writer and at checkpoints. After a crash, recovery starts from the last checkpoint and replays every WAL record after it. The rule that makes this safe: a data page may only be written once the WAL describing its change is on disk.

Group commit. A flush covers everything in the WAL buffer, so commits that arrive while one flush is in progress are made durable together by the next one. This raises commit throughput far above "one flush per commit"; it does not remove the flush latency from each commit.

When to use it

  • For any data where losing or half-applying a change is unacceptable: money, orders, inventory, permissions, anything that is the system of record.
  • Whenever invariants span several rows or tables and must hold under concurrency.
  • As the default: relational databases give ACID transactions without extra work, and turning guarantees down should be an explicit decision.

When not to

  • High-volume data where losing the last fraction of a second is acceptable (metrics, click streams, caches): relaxed durability such as synchronous_commit = off, or a store without transactions, can be cheaper.
  • Workloads spread over many services: ACID ends at the database boundary, and cross-service consistency needs sagas, outboxes and idempotency instead.
  • Globally distributed writes with very low latency requirements, where strict isolation and synchronous durability across regions cost too many round trips.

Trade-offs

Choice You gain You pay
Flush WAL on every commit (default) No acknowledged commit is lost on a crash Storage flush latency on every commit
synchronous_commit = off Commits ~as fast as memory A crash can lose the last ~3 × wal_writer_delay of commits (never consistency)
Synchronous standby Commits survive losing the whole primary A network round trip and a remote flush per commit; commits wait if no standby answers
Frequent checkpoints Shorter crash recovery More disk writes during normal operation (full-page writes, I/O spikes)
Stricter isolation Fewer anomalies More aborts and retries, or more locking

Alternatives

  • BASE systems ("basically available, soft state, eventually consistent"): many NoSQL stores trade multi-record transactions and immediate consistency for availability and partition tolerance. Several now offer single-partition or limited multi-record transactions.
  • Distributed SQL databases (Spanner, CockroachDB, YugabyteDB and similar) provide ACID transactions across nodes using consensus replication, at the cost of consensus round trips on every commit.
  • Application-level consistency: sagas, outboxes and idempotent consumers when operations span services.

Failure modes

  • Disks or controllers that lie about flushes (volatile write caches without power-loss protection): fsync returns, the data is not durable, and a power cut loses or corrupts it.
  • fsync = off in production: fast until the first crash, then potentially unrecoverable corruption.
  • Assuming "C" covers business rules that were never declared as constraints.
  • Long recovery after a crash when checkpoints are far apart and the WAL since the last one is large.
  • Commits stalling when the only synchronous standby is down.

In production

Use storage with reliable flushes and measure its flush latency (pg_test_fsync). Keep fsync and full_page_writes on. Use synchronous_commit = off only per transaction for data you can afford to lose. For synchronous replication list several standbys (synchronous_standby_names = 'ANY 1 (a, b)') so one failure does not stop commits. Tune checkpoint_timeout and max_wal_size for a recovery time you can live with, and test restores and failovers, not just backups.

Common misconceptions

  • "ACID means my data is correct." It means the database kept its promises; wrong logic commits wrong data atomically and durably.
  • "Durable means written to the table on disk." It means the log is on disk; the table catches up later.
  • "Consistency in ACID is the same as in CAP." ACID consistency is about invariants; CAP consistency is about all replicas returning the latest write (linearisability).
  • "Isolation means transactions run one at a time." Only SERIALIZABLE promises an outcome equivalent to that, and even it runs transactions concurrently.

Interview angle

Be ready to explain each letter with its mechanism (row versions or undo log, constraints, snapshots and locks, WAL and fsync) and its cost. A strong answer distinguishes ACID consistency from CAP consistency, explains why a commit waits for a flush and how group commit helps, and knows the durability knobs: what synchronous_commit = off risks, why fsync = off is different, and what a synchronous standby adds.

Model assumptions

Steps 1–6 are scripted illustrations, not simulations: the engine does not model row versions, constraints, snapshots, the WAL, checkpoints or recovery. Packets are slowed down so the order is visible; values are annotations. Steps 7–9 and the sandbox are simulated: each request is one committed write whose time inside the database is set by hand: about 6 ms (1 ms of work plus an illustrative 5 ms WAL flush on network-attached storage), about 1.2 ms with synchronous_commit = off. The model does not share flushes between commits (no group commit). The synchronous standby is the engine's synchronous replication: the primary answers once the standby, 4 ms away, has flushed the write (3 ms) and its acknowledgement has travelled the 4 ms back, so a commit takes about 11 ms longer; the primary's connection stays busy while it waits. Arrivals are random (Poisson), durations lognormal. Numbers are illustrative, not benchmarks.

The lesson as textEvery step of the simulation, written out.
  1. 1. A: all or nothing

    ACID names four guarantees a transaction gives. Atomicity first: a transaction’s writes take effect completely or not at all.

    Here the transfer updates Alice and Bob, then a fraud check says no and the API sends ROLLBACK. Postgres has already written new versions of both rows in its shared buffers, tagged with the transaction id. Rolling back does not copy anything back: the transaction is marked aborted, so those versions are never visible to anyone and vacuum removes them later.

    These first steps are scripted illustrations, slowed down; the engine does not model row versions or the log.

    Scene: Illustration: the transfer writes new row versions for Alice and Bob into shared buffers, then rolls back. The transaction is marked aborted, so the new versions are never visible.

    Key idea: Atomicity: a transaction’s changes become visible together at COMMIT, or never.

  2. 2. C: only valid states

    Consistency means a transaction moves the database from one valid state to another. The database can only enforce the rules you declare: CHECK (balance >= 0), foreign keys, UNIQUE, NOT NULL, exclusion constraints.

    Alice tries to send $600 with a balance of 500. The UPDATE violates the check, the statement fails, and the transaction can only roll back. Rules the database cannot see, such as “a customer may hold at most three cards”, are the application’s job. That makes the C partly yours: it is the one ACID letter the database cannot give you alone.

    Scene: Illustration: an UPDATE that would make Alice’s balance negative violates a check constraint; the error comes back to the Banking API and nothing changes.

    Key idea: The database enforces declared constraints; every other invariant is the application’s responsibility.

  3. 3. I: no peeking at half-done work

    Isolation is about concurrency: transactions running at the same time should not see each other’s unfinished work.

    An audit report sums all balances twice while a transfer is in flight. In Postgres every statement reads from a snapshot of committed data. The first sum runs after Alice was debited but before the commit: it still sees 700. The second runs after the commit: 700 again. It never sees 600, the total with Alice debited and Bob not yet credited.

    How strong this protection is depends on the isolation level; the next lesson shows what the weaker levels allow.

    Scene: Illustration: while the transfer updates Alice and Bob and commits, the audit report sums all balances twice. Both sums are 700; the half-done state is never visible.

    Key idea: Isolation: a transaction sees committed data only, never another transaction’s partial changes.

  4. 4. D: durable once acknowledged

    Durability: once COMMIT is acknowledged, the change survives a crash or power loss. Postgres does not write the changed table pages to disk at commit; that would mean many random writes. It appends compact WAL records (write-ahead log) describing the changes, and at commit flushes the WAL to disk (fsync) before answering.

    The changed pages stay in shared buffers in memory and reach the data files later, at a checkpoint or through the background writer. The log comes first, hence *write-ahead*: no data page may reach disk before the WAL that describes it.

    Scene: Illustration: on COMMIT, Postgres writes the WAL records to disk and waits for the flush before acknowledging. The changed pages stay in shared buffers; the data files are updated later.

    Key idea: Durability = the commit record is on stable storage before the client hears “committed”.

  5. 5. Power fails after the acknowledgement

    Right after that commit was acknowledged, the server loses power. Everything in memory is gone, including the shared buffers with Alice’s and Bob’s new balances. The data files on disk still say Alice 500, Bob 200.

    The client was told “committed”. Was it a lie? No: the WAL on disk contains the commit record and every change of the transaction. While the database is down, new requests are refused.

    Scene: Illustration: the database server loses power. Shared buffers are gone, the data files still hold the old balances, and the WAL on disk still holds the committed transfer. A request to the database is refused.

    Key idea: After a crash the data files may be stale, but the WAL holds every acknowledged commit.

  6. 6. Replay the log

    On restart Postgres runs crash recovery: it starts at the last checkpoint and replays (redoes) every WAL record after it onto the pages, then writes a checkpoint. Alice is 400 and Bob 300 again, exactly as acknowledged. Records of transactions that never committed are replayed too, but their commit status says aborted, so they stay invisible.

    The cost of recovery is the amount of WAL since the last checkpoint: more frequent checkpoints mean faster recovery but more disk writes in normal operation (checkpoint_timeout, max_wal_size).

    Scene: Illustration: after the restart Postgres reads the WAL since the last checkpoint, rebuilds the pages in memory, writes them to the data files and starts answering requests again. The committed transfer is back.

    Key idea: Crash recovery replays the WAL since the last checkpoint: every acknowledged commit comes back, nothing uncommitted does.

  7. 7. Every commit waits for the disk

    Now real traffic, simulated: 400 transfers per second, each a committed write. The work itself takes about 1 ms, but every commit then waits for its WAL flush, about 5 ms on the network-attached disk in this model. So most of each commit’s time inside the database is waiting for the disk.

    Postgres softens this with group commit: commits that arrive while a flush is in progress share the next one. The flush latency of your storage is still on the path of every commit.

    Scene: Four hundred transfers per second are committed. Each commit spends most of its time waiting for the WAL flush; nothing fails.

    Key idea: Durability has a price on every commit: the latency of flushing the log to stable storage.

  8. 8. Trade a little durability for latency

    One second in, the team sets synchronous_commit = off for these transactions. Postgres now acknowledges the commit before the WAL flush; the WAL writer flushes in the background a moment later. Commit time drops to about a millisecond and P50 falls by more than half.

    The price: if the server crashes, the most recent acknowledged commits can be lost, up to about three times wal_writer_delay (≈600 ms with the 200 ms default). The database stays consistent: you lose a short tail of transactions, never get a torn one. That is very different from fsync = off, which can corrupt the database and is never safe in production.

    It can be set per transaction, so use it only for data you can afford to lose, such as analytics events, never for the transfer itself.

    Scene: One second in, commits no longer wait for the WAL flush. Commit latency drops sharply; a crash could now lose the most recent commits.

    Key idea: synchronous_commit = off gives up the last few hundred ms of commits on a crash, but never consistency. fsync = off gives up everything.

  9. 9. Durable on one disk is not enough

    Back to synchronous_commit = on. A flushed WAL survives a power cut, but not a dead disk or a lost machine. So the team adds a synchronous standby in another zone (synchronous_standby_names): the primary streams WAL to it and acknowledges a commit only after the standby has flushed it too.

    Every commit now also waits for a round trip to the standby and its flush, about 11 ms more in this model (4 ms there, 3 ms to flush, 4 ms back), and P50 more than doubles compared with the single server. In exchange, an acknowledged commit survives losing the primary entirely. If the standby stops answering, Postgres makes commits wait, so production setups list several candidate standbys.

    Scene: A synchronous standby in another zone receives every commit before the primary acknowledges it. Commit latency rises by several milliseconds; nothing fails.

    Key idea: For durability beyond one machine, a commit must wait until another machine has it too.

  10. 10. Four guarantees, four mechanisms

    Atomicity comes from marking a transaction committed or aborted as one step (row versions or undo logs). Consistency comes from declared constraints plus your own code. Isolation comes from snapshots and locks, at a level you choose. Durability comes from flushing the WAL before acknowledging, crash recovery that replays it, and replication when one machine is not enough.

    Each has a cost, mostly latency and contention, and most databases let you dial some of it back. Know which knob you turned, and for which data.

    Scene: The Banking API commits transfers to Postgres, which flushes its WAL and waits for the synchronous standby before acknowledging each commit.

    Key idea: ACID is a bundle of mechanisms with costs, not a single switch: atomic commit, constraints, isolation, and a flushed, replicated log.