Database storage and crash recovery
Follow a stock update from memory to storage and see how PostgreSQL recovers after an unexpected shutdown.
On this page
Data pages and memory buffers
PostgreSQL organizes table and index data into pages. When a query needs a page, PostgreSQL can use a copy already in shared buffers or load the page if needed. A changed page in memory is called dirty until it is written out.
-- Run twice and compare shared buffer hits and reads.
EXPLAIN (ANALYZE, BUFFERS)
SELECT title
FROM courses
WHERE id = 1;
Write-ahead log and checkpoints
A dirty page can still be in memory when a transaction commits. How can PostgreSQL recover the stock update if the server loses power before that page is written? PostgreSQL records page changes in write-ahead log (WAL) before the corresponding changed data pages reach durable storage. With normal durability settings, it flushes the required WAL before confirming a commit. It can write the data pages later.
-- PostgreSQL: compare these statistics before and after a write.
SELECT wal_records, wal_bytes
FROM pg_stat_wal;
SELECT num_timed, num_requested
FROM pg_stat_checkpointer;
Checkpoint- Writes dirty pages as part of establishing a recovery point. Recovery can start replaying WAL from the redo point associated with the checkpoint.
Crash recovery- If the server stops after confirming a stock update but before writing its data page, recovery can replay the logged change on startup.
When a restore is needed
WAL replay can recover after a crash when the server still has the data files and WAL it needs. Restoring a deleted record or recovering from storage loss needs another source for the data. Crash recovery brings a database with intact storage back to a consistent state. For accidental deletion or storage loss, use a tested backup and restore procedure. Point-in-time recovery requires an appropriate base backup and the archived WAL needed to reach the target time.
# Restore a custom-format backup into a separate test database.
createdb learning_restore
pg_restore --exit-on-error -d learning_restore learning_db.dump
# Verify the restored course data.
psql -d learning_restore -c "SELECT COUNT(*) FROM courses;"