DevOps

WAL-G Stream Compression & S3 Multipart Chunks: Stopping Postgres Backup Failures on 10Mbps VPS Uploads

O
Oluwaseun AlabiTechnical Director
November 15, 202613 min read
WAL-G Stream Compression & S3 Multipart Chunks: Stopping Postgres Backup Failures on 10Mbps VPS Uploads

Naive pg_dump scripts fail over high-latency VPS network links, causing unarchived WAL files to fill up local disk space and crash PostgreSQL. Here is how to configure WAL-G for stream compression, parallel multipart S3 uploads, and zero-data-loss recovery on low-bandwidth African infrastructure.

It is 2:15 AM on a rainy Tuesday in Lagos. An undersea fiber cable segment suffers a severe latency degradation, or your local data center’s primary transit provider drops to a congested backup satellite link. Outgoing network throughput from your $40 Hetzner or DigitalOcean VPS drops from 200Mbps to 8Mbps, with round-trip ping to AWS eu-central-1 spiking from 90ms to 380ms alongside a 5% packet loss rate.

At 2:30 AM, your cron job triggers pg_dump and pipes the output into aws s3 cp. Two hours later, the single TCP stream stalls on a network socket timeout. The process dies mid-stream, leaving a half-written 0-byte upload on Object Storage. Meanwhile, your production PostgreSQL instance has been generating Write-Ahead Log (WAL) segments at 15MB per minute. Because your naive archive_command shell script failed, Postgres keeps accumulating un-archived WAL files inside /var/lib/postgresql/data/pg_wal.

By 5:00 AM, the local root partition hits 100% disk usage. Postgres throws a kernel panic: PANIC: could not write to file "pg_wal/xlogtemp.12948": No space left on device, and shuts down instantly. Your database is offline, your WAL directory is bloated, and your last complete backup is 28 hours old.

We have seen this scenario hit mid-sized African startups dozens of times. Standard tools like pg_dump and simple aws s3 cp commands assume high-bandwidth, low-jitter network paths. They break down completely when deployed on cheap VPS instances running over unstable network links. Similar to how we tuned vector logs in our guide on Tuning Vector Log Shipping for Unstable Networks: Stopping OOM Kills on 1GB VPS Nodes, database backups require an architecture built specifically for connection drops, rate-limited egress, and socket stalls.

This guide shows you how to replace fragile backup scripts with WAL-G, an open-source backup tool optimized for parallel streaming compression, multipart chunked uploads, and back-off retries. We will configure zero-data-loss WAL archiving that survives 10Mbps throttled links without crashing your database engine.


Why Naive PostgreSQL Backups Fail on Flaky Egress

To understand why Postgres crashes under bad network conditions, you need to understand how the PostgreSQL archiver process interacts with Linux disk I/O.

When archive_mode = on is configured in postgresql.conf, PostgreSQL generates 16MB WAL segment files. Once a WAL file fills up, PostgreSQL invokes the shell command specified in archive_command. If that command returns an exit code of 0, Postgres marks the segment as safely archived and removes or recycles it. If the command returns any non-zero exit code, Postgres retains the segment in pg_wal and retries the exact same command indefinitely.

+-------------------+      WAL Archiving      +----------------------+      High Latency      +-------------------+
|  PostgreSQL Core  | ---------------------> |  archive_command     | ---------------------> |  Remote S3 Bucket |
| (Generates 16MB   |    Executes Shell      | (aws s3 cp / pg_dump)|    Packet Loss Drop    | (Fails / Retries) |
|  WAL Segments)    |                        |                      |                        |                   |
+-------------------+                        +----------------------+                        +-------------------+
          |                                             |                                              |
          v                                             v                                              v
  Writes to Disk                               Shell Retries Loop                             Upload Stalls
  (pg_wal directory)                          (Consumes CPU/RAM)                              (Socket Timeout)
          |                                             |
          +---------------------------------------------+
                                  |
                                  v
                    Local Disk Reaches 100% Usage
                                  |
                                  v
                    PANIC: No space left on device

When using naive scripts like aws s3 cp %p s3://my-bucket/wal/%f, three specific engineering failures occur over poor connections:

  1. Lack of Exponential Backoff with Jitter: If the S3 upload fails due to a network reset, aws s3 cp exits with code 1. Postgres immediately re-executes the command. If the network is down for 30 minutes, thousands of subprocesses get spawned and killed, saturating CPU cycles and generating local log disk noise.
  2. Monolithic TCP Transfers: pg_dump writes a single continuous stream. If the network drops at 99% of a 50GB file, the entire byte payload is lost. There is no block-level resume capability.
  3. Uncompressed WAL Payload Size: Standard 16MB WAL files contain significant zero-padding and repetitive transaction headers. Pushing uncompressed bytes over a 10Mbps pipe wastes 60-70% of available network capacity.

WAL-G solves this by acting as an inline archive manager written in Go. It handles block-level delta backups, LZ4/ZSTD stream compression, parallel multipart chunk uploads, and configurable network retry logic with exponential jitter.


Step 1: Installing and Configuring WAL-G

Download the compiled WAL-G binary on your target Ubuntu/Debian database host. Avoid compiling from source on production nodes to keep build toolchains off your database instances.

# Fetch latest WAL-G binary (v3.0.0 or higher recommended)
curl -L -o /tmp/wal-g.tar.gz https://github.com/wal-g/wal-g/releases/download/v3.0.0/wal-g-pg-ubuntu-20.04-amd64.tar.gz
tar -zxvf /tmp/wal-g.tar.gz -C /usr/local/bin/
chown root:root /usr/local/bin/wal-g
chmod 755 /usr/local/bin/wal-g

Create a dedicated environment file for WAL-G at /etc/wal-g/wal-g.env. Restrict file permissions to 0600 so database credentials are protected from non-root users, keeping compliance standards tight as discussed in Why Storing Raw BVNs in PostgreSQL Is an NDPR Liability: Building a Zero-Leakage HMAC Blind Index.

# /etc/wal-g/wal-g.env
WALG_S3_PREFIX=s3://neobot-db-backups-production/postgres-main
AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
AWS_REGION=eu-central-1

# Network & Compression Optimization for Low Bandwidth
WALG_COMPRESSION_METHOD=zstd
WALG_ZSTD_LEVEL=3
WALG_UPLOAD_CONCURRENCY=2
WALG_UPLOAD_DISK_CONCURRENCY=2
WALG_SLOT_SIZE=16

# Retries and Timeouts
WALG_NETWORK_TIMEOUT=30s
WALG_RETRY_COUNT=10

Why these specific parameter values?

  • WALG_COMPRESSION_METHOD=zstd: Zstandard achieves a 4x-6x compression ratio on WAL data compared to 2.5x with LZ4, with negligible CPU overhead at level 3. A 16MB WAL segment shrinks to ~3MB before hit testing the egress interface.
  • WALG_UPLOAD_CONCURRENCY=2: Do not set this to high numbers (like 8 or 16) on low-cost VPS instances. High concurrency saturates small TCP window sizes, triggers buffer bloat, and causes packet dropping on 10Mbps links.
  • WALG_SLOT_SIZE=16: Sets the multipart upload chunk size to 16MB. If an S3 request drops, WAL-G re-transmits only that 16MB chunk rather than restarting the multi-gigabyte payload.

Step 2: Hardening postgresql.conf Against Network Outages

When configuring PostgreSQL for remote WAL shipping over unstable networks, you must tune PostgreSQL's internal WAL storage buffers. This ensures that if the internet connection goes completely dead for up to 6 hours, PostgreSQL stores WAL files locally without filling up the disk or failing transactions.

Edit your /etc/postgresql/16/main/postgresql.conf file:

# Enable WAL Archiving
wal_level = replica
archive_mode = on
archive_command = 'env $(cat /etc/wal-g/wal-g.env | xargs) wal-g wal-push %p'
archive_timeout = 300

# Protect disk from filling up during multi-hour internet outages
max_wal_size = 32GB
min_wal_size = 2GB
wal_keep_size = 4GB

# Prevent archiving from stalling checkpoint process
checkpoint_completion_target = 0.9

Execute a configuration reload without restarting the database daemon:

SELECT pg_reload_conf();

Check the official PostgreSQL Documentation on Continuous Archiving for detailed interactions between archive_timeout and checkpoint frequency.

Creating the Archive Wrapper Script

Running env $(cat ...) inside archive_command works, but writing a binary wrapper prevents process allocation bugs if configuration files are modified. Create /usr/local/bin/wal-g-archive.sh:

#!/usr/bin/env bashtxt
set -a
source /etc/wal-g/wal-g.env
set +a

# Execute WAL push with strict timeout handling
/usr/local/bin/wal-g wal-push "$1"
EXIT_CODE=$?

if [ $EXIT_CODE -ne 0 ]; then ...
  # Log failure details locally for Prometheus scrapers
  echo "$(date -u) - WAL push failed for $1 with exit code $EXIT_CODE" >> /var/log/postgresql/wal-g-failures.log
fi

exit $EXIT_CODE

Update permissions:

chmod 750 /usr/local/bin/wal-g-archive.sh
chown postgres:postgres /usr/local/bin/wal-g-archive.sh

Now update postgresql.conf to use the shell wrapper:

archive_command = '/usr/local/bin/wal-g-archive.sh %p'

Step 3: Pushing Base Backups with Rate Limiting

Continuous WAL archiving handles point-in-time recovery (PITR), but you still require regular full system base backups. Running a full database base backup over a shared 10Mbps link can choke production network traffic if left unmetered.

WAL-G handles full base backups via backup-push. We will configure a crontab job that executes base backups off-peak while enforcing disk and network rate limits.

Create /usr/local/bin/wal-g-basebackup.sh:

#!/usr/bin/env bash
set -euo pipefail

# Export environment variables
set -a
source /etc/wal-g/wal-g.env
set +a

# Acquire lockfile to prevent overlapping backups
LOCKFILE="/tmp/wal-g-basebackup.lock"
exec 200>"$LOCKFILE"
flock -n 200 || { echo "Backup already in progress. Exiting."; exit 1; }

echo "[$(date)] Starting WAL-G Base Backup..."

# Push full backup with delta support enabled
# Deltas download previous backup manifests and only upload modified blocks
/usr/local/bin/wal-g backup-push /var/lib/postgresql/16/main

# Retain only the last 4 full base backups on S3 to control cloud storage costs
/usr/local/bin/wal-g delete retain FULL 4 --confirm

echo "[$(date)] Base Backup Complete."

Test the backup manually while monitoring egress network bandwidth:

sudo -u postgres /usr/local/bin/wal-g-basebackup.sh

You can track performance directly using native tools or Linux network utilities like iftop or nload.


Step 4: Observability, Disk Alerts, and Auto-Recovery

If an ISP outage outlasts your max_wal_size storage capacity, PostgreSQL will eventually stop archiving and accumulate files until disk exhaustion occurs. You must instrument automated alerting using pg_stat_archiver before disk usage breaks critical thresholds.

Run this monitoring query inside your database instance:

SELECT 
    archived_count,
    failed_count,
    last_archived_wal,
    last_archived_time,
    last_failed_wal,
    last_failed_time,
    NOW() - last_archived_time AS archiving_delay
FROM pg_stat_archiver;

Prometheus Alertmanager Rules

If you run Prometheus, configure these alert definitions to trigger warnings on Slack or PagerDuty long before the host runs out of storage space:

groups:
  - name: postgres_archiving_alerts
    rules:
      - alert: PostgresWALArchivingStalled
        expr: (time() - pg_stat_archiver_last_archive_timestamp_seconds) > 1800
        for: 5m
        labels:
          severity: critical
        annotations:
          summary: 

Neobot Engineering Standard

Every system deployed by Neobot Tech incorporates enterprise baseline practices. We continuously audit our database topologies, REST API query paths, and frontend modular bundles to prevent latency spikes and ensure top-tier security posture.

Tags:#PostgreSQL#DevOps#WAL-G#Infrastructure#Database Backups#S3

Discussion

Comments Coming Soon

We are currently migrating our discussion engine to a new real-time database schema. Check back shortly to join the conversation.