`pg_basebackup` can use **replication slots** to ensure that WAL files are retained during the backup process, preventing premature removal before the backup completes. Here’s how it works:
## **Key Benefits of Using Replication Slots with pg_basebackup**
1. **Prevents WAL Deletion**: Ensures WAL segments needed for the backup aren’t removed by PostgreSQL’s normal cleanup
2. **Critical for Large Backups**: Essential when backups take a long time (hours)
3. **Supports PITR**: Required for point-in-time recovery setups
## **Using Replication Slots**
### **1. Create a Replication Slot First**
“`sql
— On the primary server
SELECT pg_create_physical_replication_slot(‘backup_slot’);
“`
### **2. Use with pg_basebackup**
“`bash
# Basic usage with slot
pg_basebackup -D /backup/directory \
-h primary-host \
-U replication_user \
-S backup_slot \
–wal-method=stream
# With additional options
pg_basebackup -D /backup/directory \
-h primary-host \
-p 5432 \

-U repl_user \
-S backup_slot \
–wal-method=stream \
–progress \
–verbose \
–write-recovery-conf
“`
### **3. Temporary Slot (PostgreSQL 14+)**
“`bash
# Creates a temporary slot automatically
pg_basebackup -D /backup/directory \
-h primary-host \
-U replication_user \
–wal-method=stream \
–create-slot
“`
## **Important Considerations**
### **Slot Management**
“`sql
— Monitor slot usage
SELECT slot_name, active, wal_status, restart_lsn
FROM pg_replication_slots;
— Delete slot when no longer needed
SELECT pg_drop_replication_slot(‘backup_slot’);
“`
### **Potential Issues**
1. **Slot Bloat**: If backup fails, the slot might retain WAL indefinitely
2. **Disk Space**: Monitor `pg_wal` directory size when using slots
3. **Cleanup**: Always drop temporary slots after failed backups
## **Best Practices**
1. **Use Temporary Slots** (PostgreSQL 14+):
“`bash
pg_basebackup –create-slot –slot=temp_backup_slot
“`
2. **Monitor During Backup**:
“`bash
watch -n 5 “psql -c ‘SELECT slot_name, active, pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS lag FROM pg_replication_slots;'”
“`
3. **Automated Cleanup Script**:
“`bash
# Drop slot if backup fails
cleanup() {
psql -h primary-host -c “SELECT pg_drop_replication_slot(‘backup_slot’);”
}
trap cleanup ERR
“`
4. **Alternative: Without Slot** (for quick backups):
“`bash
pg_basebackup –wal-method=fetch # Copies WAL files at end
“`
## **Example: Complete Backup Script**

“`bash
#!/bin/bash
BACKUP_DIR=”/backup/$(date +%Y%m%d_%H%M%S)”
SLOT_NAME=”backup_slot_$(date +%s)”
# Create temporary slot
pg_basebackup -D $BACKUP_DIR \
-h primary.example.com \
-U replicator \
–slot=$SLOT_NAME \
–create-slot \
–wal-method=stream \
–progress \
–verbose
# Backup complete, slot is automatically dropped
“`
Using replication slots with `pg_basebackup` provides reliability for backups, especially in production environments with high write activity. Always monitor disk usage and clean up orphaned slots to prevent issues.