When the pg_wal directory grows, it can consume a large share of a PostgreSQL server’s disk space. The files inside it are essential to database recovery and, depending on your setup, replication and point-in-time recovery. Deleting them manually may prevent PostgreSQL from starting or cause data loss. The safe way to clean up pg_wal is to find out why PostgreSQL is retaining the files, then fix that cause so PostgreSQL can remove files it no longer needs.
This guide explains what pg_wal contains, how to check what is using space, and how to resolve common causes of excessive WAL growth. The examples use PostgreSQL’s built-in SQL functions and views. Test changes in a non-production environment when possible, and take a verified backup before making significant configuration changes.
What Is the pg_wal Directory?
pg_wal is PostgreSQL’s write-ahead log directory. It contains WAL (write-ahead log) segment files that record changes made to the database. PostgreSQL writes these records before applying corresponding changes to data files. If the server stops unexpectedly, it can replay WAL records during recovery to bring the database back to a consistent state.
WAL is also used for streaming replication and point-in-time recovery. A standby server may need WAL records from the primary, while an archive-based backup process may need to copy them to separate storage. PostgreSQL therefore cannot remove a WAL segment until it is no longer required by recovery, replication, or archiving.
PostgreSQL manages WAL recycling and removal automatically. A large directory does not always indicate a problem: the server may keep segments ready for reuse, and a busy database naturally generates WAL. Persistent or rapidly increasing growth, especially when disk space is running low, deserves investigation.
Never Delete WAL Files Manually
Do not use rm, a file manager, or a script to delete files from pg_wal. Removing files that PostgreSQL still needs can cause startup failures, interrupt recovery, break replication, or make a database unusable. Renaming or moving WAL files is not a safe workaround either.
Also avoid using pg_resetwal as a cleanup tool. It is a specialized, last-resort utility for certain recovery situations, not a way to reclaim disk space. Using it incorrectly can cause data loss or leave the database in an inconsistent state. If the server will not start, get advice from a PostgreSQL administrator or a qualified support provider before attempting recovery.
Check How Much Space pg_wal Uses
First, check the size of the directory using the operating system. The exact path depends on your installation; pg_wal is normally inside the PostgreSQL data directory, but it can be a symbolic link to another location. On Linux, for example, you can use:
du -sh /path/to/data/pg_wal
Replace the example path with your actual data directory. If you are unsure where it is, connect to the database and run:
SHOW data_directory;
Then check the server’s WAL configuration and replication status. You need a database role with permission to view the relevant statistics. In PostgreSQL, run:
SELECT * FROM pg_stat_replication;
This view reports connected streaming standbys. An empty result does not rule out other causes, such as a replication slot or a failed archive command. Check the slots separately:
SELECT slot_name, slot_type, active, restart_lsn, confirmed_flush_lsn FROM pg_replication_slots;
To estimate how much WAL a slot may be holding back, use:
SELECT slot_name, pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained_wal FROM pg_replication_slots WHERE restart_lsn IS NOT NULL;
The estimate is based on the difference between the current WAL position and the slot’s restart position. It is useful for diagnosis, but it is not a direct measurement of the directory’s total size.
Find the Cause of WAL Growth
WAL accumulation usually has a reason. Look for the following common causes before changing settings or taking action:
-
A failed or slow archive process: If PostgreSQL is configured to archive WAL and the archive command repeatedly fails, required files can remain in
pg_wal. Check the PostgreSQL server log and verify that the archive destination is reachable, has enough space, and accepts files. - An inactive or lagging replication slot: A slot retains WAL so a replica or logical replication consumer can catch up. If the consumer is offline, broken, or no longer needed, the slot may retain an increasing amount of WAL.
- A standby that is behind: A disconnected or slow standby may need older WAL. Confirm that replicas are online and receiving and replaying data as expected.
- High database write activity: Bulk loads, large updates, index builds, and other write-heavy work can produce WAL quickly. A temporary increase may be expected, but the disk must have room for it.
-
Retention settings: Configuration such as
wal_keep_sizeor a replication slot’s retention behavior can increase how much WAL is kept. These settings should be reviewed in the context of replica and recovery requirements.
Check the PostgreSQL logs for archive errors, replication interruptions, disk warnings, and messages about checkpoints. Log locations vary by installation. You can also inspect important settings directly:
SHOW archive_mode;
SHOW archive_command;
SHOW wal_keep_size;
SHOW max_slot_wal_keep_size;
Some settings are available only in particular PostgreSQL versions, and a setting’s value may be -1 or another value with special meaning. Consult the documentation for your installed version before changing it.
Resolve a Stalled WAL Archive
If archiving is enabled, confirm that the configured archive command succeeds and that archived files are stored somewhere other than the active pg_wal directory. Check for full disks, incorrect permissions, unavailable network mounts, and errors in the command or its destination. Test the archiving workflow carefully rather than deleting files to make space.
Once the archive problem is fixed, PostgreSQL can archive pending WAL and eventually recycle or remove segments that are no longer required. Monitor the logs and directory size to confirm that the backlog is decreasing. Do not manually remove files from the archive destination unless your backup and recovery policy confirms they are no longer needed.
Manage Replication Slots Safely
A replication slot should be removed only when you have confirmed that no replica or logical replication consumer needs it. Dropping an active or required slot can prevent a consumer from continuing and may require it to be rebuilt or resynchronized. Before making a change, identify the slot’s owner, purpose, and last known activity.
If a slot is genuinely abandoned, a PostgreSQL administrator can remove it with the appropriate SQL function. For a confirmed unused slot, the form is:
SELECT pg_drop_replication_slot('slot_name');
Replace slot_name with the exact slot name. Do not run this command just because a slot is inactive: an offline replica may still depend on it. For a logical slot, also check the status of the application or connector that consumes its changes.
For supported PostgreSQL versions, max_slot_wal_keep_size can place a limit on WAL retained by replication slots. Setting a limit may prevent a slot from filling the disk, but it can also invalidate a lagging consumer’s ability to continue from its old position. Choose a limit based on your recovery and replication requirements, and monitor slots after changing it.
Review WAL Retention and Checkpoints
wal_keep_size specifies a minimum amount of WAL to retain for standby servers. Increasing it can help a replica tolerate a longer interruption, but it also uses more disk. Reducing it may reclaim space in some situations, but it does not override the needs of replication slots, archiving, or crash recovery. Do not treat it as a general-purpose cleanup command.
PostgreSQL also uses checkpoints to make changes durable and manage recovery. Checkpoint behavior and settings such as max_wal_size affect WAL generation and recycling, but lowering a setting blindly may cause more frequent checkpoints and affect performance. A checkpoint is not a command to erase all old WAL, and it cannot safely remove segments that are still required by another process.
Make configuration changes only after identifying the retention cause. Use the PostgreSQL documentation for your version to determine whether a setting requires a reload or restart. Afterward, monitor disk usage, database logs, replication lag, and backup status rather than assuming the change has solved the issue.
What to Do When the Disk Is Nearly Full
A nearly full disk is an urgent operational problem, but deleting WAL files manually can turn it into a database outage. First, check whether other filesystems or storage volumes have available space. If possible, add capacity or free space from unrelated, verified-to-be-unneeded files. Avoid deleting database files, backups, or archived WAL without confirming their role and retention requirements.
Next, identify whether archiving, a replication slot, a standby, or unusually heavy write activity is preventing cleanup. Correct the underlying issue, then give PostgreSQL time to manage the WAL. If the database is still running but you cannot safely resolve the cause, contact your database administrator or hosting provider before the filesystem reaches capacity.
If PostgreSQL has already stopped because the disk filled, do not remove files from pg_wal to force it to start. Preserve the database directory and logs, make storage available if possible, and follow a recovery procedure appropriate to your installation. A recent verified backup and a tested recovery plan are far safer than improvised WAL deletion.
Prevent Future pg_wal Problems
Prevention starts with monitoring. Track free disk space, the size and growth rate of pg_wal, archive failures, replication lag, and the age and retention of replication slots. Set alerts early enough to allow time for diagnosis and corrective action.
Also make sure your operational procedures cover storage capacity, backups, and replica maintenance. Test archive recovery and database restoration periodically. Review retention settings when you add or remove replicas, change backup policies, or introduce a logical replication consumer. The correct balance depends on how long replicas may be offline and how far back your recovery plan must reach.
- Keep backups and archived WAL on suitable storage with a documented retention policy.
- Alert on failed archiving, inactive slots, growing replication lag, and low disk space.
- Remove replication slots only after confirming they are no longer required.
- Size storage for normal write activity as well as maintenance operations and temporary spikes.
- Document recovery steps and test them before an emergency occurs.
Conclusion
Cleaning pg_wal safely means fixing the reason PostgreSQL is retaining WAL, not deleting files from the directory. Check disk usage, server logs, archive status, replication slots, and standby health. Then resolve the underlying issue and let PostgreSQL recycle or remove files that are no longer needed. Never use manual deletion or pg_resetwal as routine cleanup methods. With sensible monitoring, tested backups, and carefully managed replication and archiving, you can prevent WAL growth from becoming a disk-space emergency.
Disclaimer: Articles are written by Humans, AI or Both. Verify Important information.