Managing Redo, WAL and Transaction Logs
All three databases write changes to the log before changing the data. The log is used for recovery and replication, so log that is still needed cannot be deleted. When log space keeps growing, it is almost always a question of "what is holding the log". Typical causes are a missing backup, a replication target that has not consumed the log, or a long-open transaction. Deleting log files directly at the OS level makes the database stop or become unrecoverable.
Oracle
Required privileges: query access to V$ views (SELECT_CATALOG_ROLE); changing log groups requires ALTER DATABASE; cleaning up archives requires SYSBACKUP or SYSDBA in RMAN.
Online redo log groups and status
SELECT l.group#, l.thread#, l.sequence#, l.bytes / 1024 / 1024 AS size_mb,
l.members, l.archived, l.status, f.member
FROM v$log l
JOIN v$logfile f ON f.group# = l.group#
ORDER BY l.thread#, l.group#;
status:CURRENT(being written now),ACTIVE(checkpoint not yet complete, still needed for recovery),INACTIVE(reusable),UNUSED(newly created, not yet used).- If every group is
CURRENTorACTIVE, the log cannot move to the next group and DML waits (Checkpoint not completein the alert log).
Log switch frequency
SELECT TRUNC(first_time, 'HH24') AS hour, thread#, COUNT(*) AS switches
FROM v$log_history
WHERE first_time > SYSDATE - 1
GROUP BY TRUNC(first_time, 'HH24'), thread#
ORDER BY hour, thread#;
- If switches occur every few minutes during busy hours, the log files are too small. Size them so that a switch happens about once every 15-20 minutes at peak.
Changing log group size
A log file's size cannot be changed, so create new larger groups and drop the small ones.
ALTER DATABASE ADD LOGFILE THREAD 1 GROUP 4 ('+DATA', '+FRA') SIZE 2G;
ALTER SYSTEM SWITCH LOGFILE;
ALTER SYSTEM CHECKPOINT;
-- after confirming the group to drop is INACTIVE
ALTER DATABASE DROP LOGFILE GROUP 1;
WARNING Do not drop a
CURRENTorACTIVEgroup, or a group not yet archived (archived = 'NO'). At least two groups must remain per thread. Without ASM or OMF, dropping a group leaves the OS file behind, so delete it separately. In Data Guard, match the standby logs (V$STANDBY_LOG) to the same size.
Archive log generation
SELECT log_mode FROM v$database; -- ARCHIVELOG / NOARCHIVELOG
SELECT TRUNC(completion_time) AS day,
ROUND(SUM(blocks * block_size) / 1024 / 1024 / 1024, 1) AS gb, COUNT(*) AS files
FROM v$archived_log
WHERE dest_id = 1 AND completion_time > SYSDATE - 7
GROUP BY TRUNC(completion_time)
ORDER BY day;
Fast Recovery Area (FRA) usage
SELECT name, ROUND(space_limit / 1024 / 1024 / 1024, 1) AS limit_gb,
ROUND(space_used / 1024 / 1024 / 1024, 1) AS used_gb,
ROUND(space_reclaimable / 1024 / 1024 / 1024, 1) AS reclaimable_gb, number_of_files
FROM v$recovery_file_dest;
SELECT file_type, percent_space_used, percent_space_reclaimable, number_of_files
FROM v$recovery_area_usage;
- When the FRA fills up, archives cannot be written and the database stops (
ORA-00257,ORA-19815in the alert log). reclaimableis space that Oracle can delete on its own because backups are complete. If this value is small while usage is high, archive logs are not being backed up.
Cleaning up archive logs (RMAN)
-- run in RMAN>
BACKUP ARCHIVELOG ALL NOT BACKED UP 1 TIMES;
DELETE ARCHIVELOG ALL BACKED UP 1 TIMES TO DEVICE TYPE DISK COMPLETED BEFORE 'SYSDATE-2';
CONFIGURE ARCHIVELOG DELETION POLICY TO APPLIED ON ALL STANDBY; -- Data Guard
In an emergency, raise the limit first to bring the database back: ALTER SYSTEM SET db_recovery_file_dest_size = 500G;
WARNING If you delete archives that have not been backed up, you cannot recover to any point after the last backup. Do not delete them with
rmat the OS level. If already deleted, runCROSSCHECK ARCHIVELOG ALL;and thenDELETE EXPIRED ARCHIVELOG ALL;to bring the RMAN records in line.
PostgreSQL
Required privileges: pg_ls_waldir() requires superuser or pg_monitor. Dropping a replication slot requires superuser or the REPLICATION attribute.
pg_wal size
SELECT COUNT(*) AS files, pg_size_pretty(SUM(size)) AS total
FROM pg_ls_waldir();
SELECT pg_current_wal_lsn() AS current_lsn,
pg_walfile_name(pg_current_wal_lsn()) AS current_file;
- Normally the size of
pg_walfluctuates aroundmax_wal_size(default 1GB). If it is far larger, check the causes below in order. - On a standby,
pg_current_wal_lsn()raises an error. Usepg_last_wal_replay_lsn()instead.
WAL generation
-- compute from the LSN difference between two points in time
SELECT pg_size_pretty(pg_wal_lsn_diff('3A/7F000000', '3A/12000000'));
-- cumulative statistics (PostgreSQL 14+)
SELECT wal_records, wal_fpi, pg_size_pretty(wal_bytes) AS wal_bytes, wal_buffers_full, stats_reset
FROM pg_stat_wal;
- A high
wal_fpi(full page image) can mean checkpoints are too frequent. The first change to a page after a checkpoint writes the whole page to WAL.
Replication slots holding WAL
A replication slot prevents WAL from being removed until the subscriber or standby has consumed it. If the consumer of a slot disappears, WAL piles up without limit.
SELECT slot_name, slot_type, database, active, wal_status,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained_wal,
pg_size_pretty(safe_wal_size) AS safe_wal_size
FROM pg_replication_slots
ORDER BY pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn) DESC;
- A slot with
active = falseand a largeretained_walis likely abandoned. wal_status(13+):reserved(normal),extended(retained beyondmax_wal_size),unreserved(may be lost soon),lost(the required WAL is already gone and the slot cannot be used).- Use
max_slot_wal_keep_size(13+, default-1, unlimited) to cap how much a slot can hold back.
SELECT pg_drop_replication_slot('old_subscriber_slot');
ALTER SYSTEM SET max_slot_wal_keep_size = '50GB';
SELECT pg_reload_conf();
WARNING If you drop a slot, the standby or logical replication subscriber that used it cannot resume and must be resynchronized from scratch. A slot with
active = truecannot be dropped, so disconnect its connection first. A slot that hitsmax_slot_wal_keep_sizebecomeslost.
Archive failures and other causes
SELECT archived_count, last_archived_wal, last_archived_time,
failed_count, last_failed_wal, last_failed_time
FROM pg_stat_archiver;
SELECT name, setting, unit FROM pg_settings
WHERE name IN ('max_wal_size', 'min_wal_size', 'wal_keep_size', 'checkpoint_timeout', 'archive_mode');
- If
archive_command(orarchive_libraryin 16+) fails, WAL is not removed until it succeeds. Iflast_failed_timeis recent, look for the error in the server log. - At least
wal_keep_size(13+;wal_keep_segmentsin 12 and earlier) is always retained. - A long-open transaction does not block WAL removal, but it can keep a logical replication slot from advancing.
max_wal_size and checkpoints
ALTER SYSTEM SET max_wal_size = '8GB';
SELECT pg_reload_conf();
-- many requested checkpoints means max_wal_size is too small
SELECT checkpoints_timed, checkpoints_req FROM pg_stat_bgwriter; -- up to 16
SELECT num_timed, num_requested FROM pg_stat_checkpointer; -- 17+
WARNING Deleting files inside
pg_waldirectly can keep the database from starting or corrupt data.pg_archivecleanupis for the archive directory, not forpg_wal. If the disk is full, first free space by other means, then fix the causes above (slots, archiving) so that PostgreSQL removes the WAL itself.
SQL Server
Required privileges: sys.dm_db_log_space_usage and sys.dm_db_log_info require VIEW DATABASE STATE (VIEW DATABASE PERFORMANCE STATE in 2022+); log backup requires BACKUP LOG; shrinking requires db_owner.
Log usage
USE sales;
SELECT total_log_size_in_bytes / 1048576 AS log_size_mb,
used_log_space_in_bytes / 1048576 AS used_mb,
ROUND(used_log_space_in_percent, 1) AS used_pct,
log_space_in_bytes_since_last_backup / 1048576 AS since_last_backup_mb
FROM sys.dm_db_log_space_usage;
DBCC SQLPERF(LOGSPACE); -- all databases at once
Why the log cannot be reused
SELECT name, recovery_model_desc, log_reuse_wait_desc
FROM sys.databases
ORDER BY name;
LOG_BACKUP: the database uses the FULL/BULK_LOGGED recovery model but no log backups are being taken. This is the most common cause.ACTIVE_TRANSACTION: a long-open transaction exists (find it withDBCC OPENTRAN;).AVAILABILITY_REPLICA: an availability group secondary replica has not yet received or applied the log.REPLICATION: transactional replication or CDC has not yet read the log.NOTHINGmeans nothing is blocking right now.CHECKPOINTis the normal state of waiting for the next checkpoint.
Long-open transactions
DBCC OPENTRAN;
SELECT st.session_id, dt.database_transaction_begin_time,
dt.database_transaction_log_bytes_used / 1048576 AS log_used_mb
FROM sys.dm_tran_database_transactions dt
JOIN sys.dm_tran_session_transactions st ON st.transaction_id = dt.transaction_id
WHERE dt.database_id = DB_ID()
ORDER BY dt.database_transaction_begin_time;
VLF count
A log file is internally divided into VLFs (virtual log files). Repeated autogrowth in small increments can produce thousands of VLFs, which slows startup, recovery, and replication.
SELECT COUNT(*) AS vlf_count,
SUM(CASE WHEN vlf_active = 1 THEN 1 ELSE 0 END) AS active_vlfs,
ROUND(AVG(vlf_size_mb), 1) AS avg_vlf_mb
FROM sys.dm_db_log_info(DB_ID()); -- 2016 SP2+
- A few hundred or fewer is appropriate. If there are many, shrink the log and then grow it back once to an appropriate size to rebuild the VLFs (see below).
Log backup and shrink
BACKUP LOG sales TO DISK = N'E:\Backup\sales_log.trn';
SELECT name, size / 128 AS size_mb FROM sys.database_files WHERE type_desc = 'LOG';
DBCC SHRINKFILE (sales_log, 1024); -- target size in MB
-- grow back to the needed size in one step, and set a fixed growth increment
ALTER DATABASE sales MODIFY FILE (NAME = sales_log, SIZE = 8GB, FILEGROWTH = 1GB);
WARNING Shrinking is a one-off measure. Do not shrink if the log will grow back to the same size. Repeated shrinking and growing increases the VLF count, and writes stall while the log file grows (log files must be zero-filled, so instant file initialization does not apply; in 2022+ only growth of 64MB or less is an exception). Do not shrink data files (
DBCC SHRINKFILEon a data file, orSHRINKDATABASE), because it causes heavy index fragmentation.
WARNING Switching the recovery model to
SIMPLEto empty the log breaks the log backup chain, so point-in-time recovery is impossible until the next full (or differential) backup. Databases in an availability group cannot be switched toSIMPLE.