Debugging Tail Latency Spikes in Multi-Region PostgreSQL 17 Replicas

· Daniel Lin postgresqldatabasesstoragesre

After upgrading our read-heavy analytics cluster to PostgreSQL 17, average query latency dropped by 18% thanks to the improved streaming I/O layer. Paradoxically, our p99.9 read latency spiked every 12 to 15 minutes from 11ms to over 800ms—only on replicas, never on the primary.

Correlating Checkpoints with Linux Page Cache Flushes

Checking pg_stat_bgwriter and pg_stat_checkpointer initially looked clean because checkpoint_completion_target was already set to 0.9. The real clue showed up in /proc/vmstat: every time nr_dirty crossed the kernel's default vm.dirty_background_ratio = 10 on a 128 GB RAM instance, Linux flushed ~12 GB of dirty pages in a single burst, saturating the cloud block volume's IOPS ceiling.

# Inspect dirty writeback pressure in real time
watch -n 1 "grep -E 'Dirty|Writeback' /proc/meminfo"

# Cap dirty writeback thresholds in absolute bytes instead of RAM percentage
cat <<'EOF' > /etc/sysctl.d/60-pg-dirty.conf
vm.dirty_background_bytes = 134217728
vm.dirty_bytes = 536870912
EOF
sysctl --system

Secondary Culprit: Replication Apply Lag on Bulk Deletes

We also discovered a batch retention job deleting 4 million rows in one transaction on the primary. Replaying those WAL records sequentially on the standby temporarily held exclusive buffer pins on hot index leaf pages. Breaking the retention job into 25,000-row batches with a 50ms pause between commits eliminated replication apply stalls completely.

Always express Linux dirty page limits in absolute bytes (vm.dirty_background_bytes) on hosts with more than 32 GB of RAM. Percentage-based defaults scale poorly with cloud disk throughput caps.
← Migrating High-Throughput Telemetry Pipelines to Linux io_uringZero-Downtime TLS Certificate Rotation Patterns for Edge Proxies →