Sub topic 6
Durability: committed data survives failure
This chapter assumes you know BEGIN, COMMIT and ROLLBACK, and that you have read the chapters on atomicity and consistency. Examples use PostgreSQL. Other databases have equivalent settings under different names.
What durability promises
Durability is the "D" in ACID. Once the database tells you a transaction has committed, the changes stay committed. A process crash, an operating system crash or a power cut does not undo them.
The promise is about the acknowledgment. If COMMIT returned successfully, the data is safe. If the connection dropped before you saw the result, you do not know whether the commit happened. The database may have committed just before the failure, or just before that. Your application has to handle this uncertainty (see the retry chapter).
Durability covers some failures and not others:
| Failure | Covered by default? | What protects you |
|---|---|---|
| Database process killed | Yes | Write-ahead log (WAL) replay on restart |
| Operating system crash or power loss | Yes, if the disk honors flush requests | WAL flushed to stable storage at commit |
| Disk or server destroyed | No | Replication, backups |
| Accidental `DELETE` that was committed | No | Backups, point-in-time recovery |
| Application bug that commits bad data | No | Constraints, review, backups |
A committed transaction is durable. A committed transaction that was wrong is still committed.
Why memory is the problem
Databases keep recently used table pages in memory (PostgreSQL calls this area shared buffers). Changing a page in memory is fast. Writing it to its place in the table file is slow, because it is random I/O. If the database had to write every modified table page before acknowledging a commit, commits would be slow.
If it wrote nothing before acknowledging, a crash would lose the commit. So the database writes a small, sequential record of the change first. This is the write-ahead log, covered in detail in the next chapter. For durability you only need this rule:
- Before
COMMITreturns, the WAL records describing the transaction, including its commit record, must be flushed to stable storage. - The modified table pages can be written later, in the background.
After a crash, recovery replays the WAL and rebuilds any changes that never reached the table files.
What happens at COMMIT
The step that matters is fsync. A normal write call only hands data to the operating system, which may keep it in its cache. fsync asks the operating system to push the data to the storage device and wait until the device confirms. The commit is acknowledged only after that confirmation.
Checking and trading durability
PostgreSQL controls this with synchronous_commit. Check the current value:
SHOW synchronous_commit;
-- onYou can lower it for a single transaction when losing the last moments of data is acceptable. This example logs page views, where losing a few rows after a crash does not matter:
CREATE TABLE page_views (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
url text NOT NULL,
viewed_at timestamptz NOT NULL DEFAULT now()
);
BEGIN;
SET LOCAL synchronous_commit = off;
INSERT INTO page_views (url) VALUES ('/pricing');
COMMIT;
-- Returns without waiting for the WAL flush.SET LOCAL limits the change to the current transaction. Use it instead of changing the setting for the whole session or server. Your money-moving transactions then keep full durability.
With synchronous_commit = off, a crash can lose the most recent commits. PostgreSQL's documentation puts the window at up to about three times wal_writer_delay, which is 200 ms by default. The database does not become corrupted. Transactions are still atomic and consistent, and the recovered state is one that the transactions could have produced in order. You lose the tail of recent commits, not a random subset of them.
| `synchronous_commit` | COMMIT waits for | Risk |
|---|---|---|
| `off` | Nothing. WAL is flushed shortly after. | Recent commits can be lost on a crash |
| `local` | Local WAL flush | Commits can be lost if the primary is destroyed and a standby takes over |
| `on` (default) | Local WAL flush, plus synchronous standbys if configured | Lowest risk with standard settings |
| `remote_write` | Standby has received and written the WAL, not flushed it | A standby OS crash at the same time as the primary could lose data |
| `remote_apply` | Standby has replayed the change | Slowest, but queries on the standby see the commit |
The remote_* levels only matter when you have synchronous replication configured through synchronous_standby_names. Without it, on behaves like local.
The real cost: latency, not throughput
An fsync takes anywhere from a fraction of a millisecond on a good SSD to several milliseconds on slow storage. A client that commits one row per transaction pays that cost every time. The effect is easy to see:
-- Slow pattern: 10,000 transactions, 10,000 flushes
-- (each INSERT autocommits when run on its own)
INSERT INTO page_views (url) SELECT '/a' FROM generate_series(1, 1);
-- ...repeated 10,000 times from the client
-- Faster pattern: one transaction, one flush
BEGIN;
INSERT INTO page_views (url)
SELECT '/a' FROM generate_series(1, 10000);
COMMIT;Batching rows into one transaction removes most of the flush cost without weakening durability. PostgreSQL also uses group commit. When many sessions commit at nearly the same moment, one fsync covers all their commit records. Concurrent clients therefore get much better throughput than a single client committing in a loop.
Where durability silently fails
The database can only be as durable as the storage beneath it. Common ways the guarantee breaks:
fsync = off. This PostgreSQL setting stops the server from forcing data to disk. It exists for throwaway bulk loads. A crash can corrupt the whole cluster, not just lose recent commits.- Write caches that lie. Some disks, RAID controllers and virtual machines report a flush as complete while the data sits in volatile cache. Controllers with battery-backed or flash-backed cache, and drives with power-loss protection, make this safe. Consumer drives without them may not.
- Network and virtual file systems. Misconfigured network storage or hypervisor settings can ignore flush requests.
- Single copy of the data. One disk, one machine, one data center. Flushed data is still lost if the device is destroyed.
Surviving beyond one machine
Local flushing handles a restart. Surviving a lost server needs a second copy:
- Streaming replication sends WAL to standby servers. By default replication is asynchronous, so a failover can lose the last few commits the standby had not received.
- Synchronous replication makes
COMMITwait for at least one standby, which closes that gap at the cost of extra latency per commit. If the required standby is unavailable, commits on the primary block until it returns or you change the configuration. - Backups and point-in-time recovery keep base backups plus archived WAL, so you can restore the database to a moment before a bad commit.
Handling the unknown outcome
If the connection breaks while COMMIT is in flight, the transaction may or may not be durable. Do not blindly re-run it, or you might apply a transfer twice. Make the operation identifiable: store a unique request ID in the same transaction, protected by a unique constraint, and check for it after reconnecting.
CREATE TABLE transfers (
request_id uuid PRIMARY KEY,
from_id integer NOT NULL,
to_id integer NOT NULL,
amount numeric(12,2) NOT NULL CHECK (amount > 0)
);
BEGIN;
INSERT INTO transfers (request_id, from_id, to_id, amount)
VALUES ('6f1c1d0e-6a6b-4c47-9a53-0d3f5e8b7a11', 1, 2, 30.00);
UPDATE accounts SET balance = balance - 30 WHERE id = 1;
UPDATE accounts SET balance = balance + 30 WHERE id = 2;
COMMIT;A retry with the same request_id fails on the primary key instead of moving money twice. The application treats that failure as "already done".
Exercise
A service logs 5,000 sensor readings per second. Losing the last half second of readings after a server crash is acceptable, but the same database also stores billing records that must never be lost. How would you configure durability, and what would you not change?
Show answer
Keep the server default synchronous_commit = on and fsync = on. In the sensor-logging transactions only, run SET LOCAL synchronous_commit = off (or set it for the logging role). That removes the per-commit flush wait for the readings and risks only the most recent commits, which the requirement allows. Billing transactions keep the default and wait for the WAL flush. Do not turn fsync off, because that risks corrupting the whole database, including billing data. Batching several readings per transaction would also cut flush costs.