PostgreSQL uses Write-Ahead Logging (WAL) to ensure data consistency and recoverability. WAL files record every change made to the database before the actual data files are updated. By enabling WAL archiving, administrators can retain WAL files outside the database server and use them for Point-in-Time Recovery (PITR) and disaster recovery.
What is WAL in PostgreSQL?
WAL (Write-Ahead Log) is PostgreSQL’s transaction logging mechanism. Before any changes are written to the database files, they are first recorded in WAL files.
Benefits of WAL:
- Ensures data durability
- Supports crash recovery
- Enables streaming replication
- Supports Point-in-Time Recovery (PITR)
- Allows continuous backup strategies
Check Current WAL Configuration
Connect to PostgreSQL and check the current settings:
SHOW archive_mode; archive_mode-------------- offSHOW archive_command; archive_command-----------------(disabled)SHOW wal_level; wal_level----------- replica
Locate PostgreSQL Configuration File
Find the location of the PostgreSQL configuration file:
SHOW config_file;config_file----------------/var/lib/pgsql/18/data/postgresql.conf
Create an Archive Directory
Create a directory where archived WAL files will be stored.
mkdir -p /postgres_archivechown postgres:postgres /postgres_archivechmod 700 /postgres_archivels -ld /postgres_archive -- verify
Configure WAL Archiving
Edit the PostgreSQL configuration file.
vi /var/lib/pgsql/18/data/postgresql.conf-- Modify the following parameter to configure WAL:# WAL Configurationwal_level = replica# Enable Archivingarchive_mode = on# Archive Commandarchive_command = 'cp %p /postgres_archive/%f'# Replication and WAL Retentionmax_wal_senders = 10wal_keep_size = 1GB
Parameter Explanation
| Parameter | Description |
|---|---|
| wal_level | Controls the amount of information written to WAL |
| archive_mode | Enables WAL archiving |
| archive_command | Command executed when a WAL file is ready for archiving |
| max_wal_senders | Maximum replication connections |
| wal_keep_size | Retains WAL files for replication and recovery |
Restart PostgreSQL
The parameter archive_mode requires a database restart.
sudo systemctl restart postgresql
Verify Archiving Configuration
After the restart, verify the settings.
SHOW archive_mode;SHOW archive_command;SHOW wal_level;
Generate WAL Activity
Create a sample table and insert data.
CREATE TABLE wal_test ( id INT);-- insert dataINSERT INTO wal_testSELECT generate_series(1,100000);
Force a WAL Switch
To immediately archive the current WAL file, execute:
SELECT pg_switch_wal(); pg_switch_wal--------------- 0/3000000
Verify Archived WAL Files
Check the archive directory:
ls -ltr /postgres_archive000000010000000000000001000000010000000000000002000000010000000000000003
Monitor WAL Archiving Status
PostgreSQL provides statistics through the pg_stat_archiver view.
SELECT * FROM pg_stat_archiver;