Schedule icon
OutputValues icon
Query icon
Log icon
If icon
SlackIncomingWebhook icon
Pause icon
Sleep icon
Fail icon
Set icon

PostgreSQL Forced Checkpoint max_wal_size Tuning Guard

Detect PostgreSQL checkpoints forced by WAL volume, raise max_wal_size behind a disk check and approval, then read the live setting back.

Categories
DataInfrastructure

A PostgreSQL checkpoint happens for one of two reasons. checkpoint_timeout fires it on a timer, which is paced over checkpoint_completion_target and cheap. Or WAL volume hits max_wal_size, which forces one immediately and flushes every dirty buffer as fast as the storage takes them. On a write heavy instance with max_wal_size set too small, almost every checkpoint is the second kind, so the instance spends its day in back to back IO storms.

The evidence is already in the server. pg_stat_bgwriter.checkpoints_req climbs far past checkpoints_timed. PostgreSQL also writes checkpoints are occurring too frequently into its own log with a hint naming max_wal_size. Both go unread, because nothing watches them.

This guard samples those counters, judges the ratio over the window since its own previous run, derives a new max_wal_size from the WAL bytes actually written in that window, refuses to raise beyond a share of the WAL volume, applies the change with ALTER SYSTEM plus pg_reload_conf() behind an approval gate, then reads the live setting back and fails the run if it did not move.

This blueprint was created by zkasuran.

Safety

  • Read-only by default. dry_run is true and auto_remediate is false, so a plain run measures, reports and changes nothing.
  • A change happens only when auto_remediate is true and dry_run is false, the disk headroom check passes, then a human resumes the Pause with approved set true. An unanswered gate reads as not approved.
  • No restart is scheduled by this flow. That is checked rather than claimed. ALTER SYSTEM writes to postgresql.auto.conf, which PostgreSQL reads after postgresql.conf. max_wal_size has setting context sighup, so pg_reload_conf() is enough for the new value to take effect. The re-read reports pending_restart, which stays false. The run fails if it is ever true.
  • What the re-verify proves is narrow, so it is worth stating. It proves the setting changed. It does not prove the checkpoint pressure is gone. pg_stat_bgwriter counters are cumulative since the last reset, so a lifetime ratio cannot improve however good the fix is. That is why this flow judges a delta instead. It keeps the previous run's counters in the namespace KV store, measures the window between them, then writes the closing counters at the end of every run. After a remediation the next window starts from post change counters, so the following run is the one that shows whether the fix worked. The lifetime ratio is still logged, labelled, never judged.
  • pg_stat_reset_shared('bgwriter') would be the other way to get a clean window. This flow does not call it. Resetting is destructive to every other consumer of those counters, including your own monitoring. The delta gives the same measurement without touching shared state.
  • Raising max_wal_size costs disk. WAL is allowed to grow further before a checkpoint, so the proposal is clamped to wal_disk_fraction of the free space on the WAL volume plus what pg_wal already holds. PostgreSQL exposes no free space function, so that number comes from the operator through wal_volume_free_mb. Left at 0 the flow refuses to raise anything. A ceiling at or below the current setting is refused with the numbers printed.
  • The trade is real and it is not hidden. Fewer checkpoints, each flushing more, means more WAL retained between them and a longer crash recovery window. max_wal_ceiling_mb is the hard cap on how far that can go.
  • A max_wal_size pinned on the postmaster command line outranks postgresql.auto.conf, so ALTER SYSTEM would write the new value while the server keeps serving the old one. The detection reads pg_settings.source, refuses the change when it says command line and names the container flag or service unit as the place to fix it.
  • The value is derived, never picked. It is the WAL bytes measured in the window, scaled to one checkpoint_timeout period, times headroom_factor. It is also never lowered, because this flow only raises.

How it works

  1. read_baseline (io.kestra.plugin.core.output.OutputValues) reads the counters this flow stored at the end of its previous run from the namespace KV store. A missing key means a first run.
  2. detect (io.kestra.plugin.jdbc.postgresql.Query) reads pg_stat_bgwriter, pg_current_wal_lsn(), the live settings plus the size of pg_wal in one query. It returns the per window deltas, the requested share, the WAL rate, the derived need, the disk ceiling, the clamped proposal plus the exact ALTER SYSTEM statement. Every comparison is done in SQL, so one row carries the verdict.
  3. log_detect (io.kestra.plugin.core.log.Log) logs the window, both ratios, the WAL rate plus the mode.
  4. guard (io.kestra.plugin.core.flow.If) branches on the verdict. With no pressure, clean explains why and the run ends. Otherwise findings_alert posts the measurement on every detection.
  5. mode (io.kestra.plugin.core.flow.If) enters the remediation branch only when auto_remediate is true and dry_run is false. Otherwise report_only states what would change.
  6. headroom (io.kestra.plugin.core.flow.If) is the disk gate. If the proposal is not above the current setting, headroom_refused prints the reason and nothing is touched. The same happens when pg_settings.source says the value is pinned on the command line.
  7. approval_gate (io.kestra.plugin.core.flow.Pause) waits for a human. apply_setting then runs ALTER SYSTEM SET max_wal_size and reload_conf runs pg_reload_conf().
  8. reverify reads current_setting('max_wal_size') plus pending_restart back. verify_result fails the run through io.kestra.plugin.core.execution.Fail if the value is short of the proposal or a restart is pending.
  9. close_window reads the counters once more and record_baseline (io.kestra.plugin.core.kv.Set) stores them as the start of the next window.

What you get

  • A ratio you can act on. The share of checkpoints forced by WAL volume over the last window, not over the life of the server.
  • A max_wal_size derived from the WAL bytes the instance actually wrote, scaled to one checkpoint_timeout period.
  • A disk gate that refuses the change when the WAL volume cannot hold it, with the free space, the ceiling plus the current value all printed.
  • Proof that no restart is needed, read from pg_settings.pending_restart rather than asserted.
  • A real verification step. The run passes only when a second read shows the new value live.
  • A note on what a successful run does not prove.
  • Slack alerts on the findings and on any failure.

Who it's for

  • DBAs and platform engineers on write heavy PostgreSQL instances that stall in bursts, where IO spikes line up with checkpoints.
  • Teams who inherited an instance still carrying a small default max_wal_size from an old config or a container flag.
  • Anyone who has seen checkpoints are occurring too frequently in the log and wants the follow up measured, applied plus proven instead of guessed.

Why orchestrate this with Kestra

The counters are cumulative, so reading them once tells you about the whole life of the server rather than today. Measuring a window needs something that remembers the last reading, runs on a schedule, holds the state between runs then does the arithmetic the same way every time. Kestra has the KV store for the cursor, the scheduler for the sampling, an approval gate for a change that is instance wide, a re-read step that turns a hopeful fix into a verified one plus a Slack alert the moment any of it fails. A one-off script that raises max_wal_size reports success whether or not the value moved. It also has nowhere to keep the previous reading.

Tested end to end

Run on Kestra 2.0.5 against PostgreSQL 16 configured through postgresql.auto.conf with max_wal_size=48MB, min_wal_size=32MB plus checkpoint_timeout=30min, with a local HTTP sink standing in for Slack. A sustained write loop forced repeated volume checkpoints while the timer fired none. Every number was confirmed with psql against pg_stat_bgwriter and pg_settings. The server also wrote checkpoints are occurring too frequently into its own log during the seed, which is the same condition read from the other side.

  • Detector can fail: the same write loop produced 22 forced checkpoints of 22 at max_wal_size=48MB, then 1 of 1 after the setting was raised to 768MB and the counters were reset. The second window is reported clean, because a one checkpoint window is below min_window_checkpoints however bad its share looks.
  • Dry run reported the proposal (48MB to 256MB, derived from 503528928 bytes of WAL in 93 seconds) and left max_wal_size at 48MB, confirmed with psql.
  • Remediate with approval moved it to 256MB, the value the disk ceiling allowed. current_setting('max_wal_size') read 256MB back, pending_restart stayed false and pg_postmaster_start_time() was identical before and after, so the server was never restarted.
  • A role with pg_monitor but not superuser had its ALTER SYSTEM rejected, the re-read found 48MB unchanged and the run failed and alerted rather than reporting success.
  • On an instance started with -c max_wal_size=48MB the write landed in postgresql.auto.conf while the live value never moved, because the command line outranks that file. The re-read caught it, which is why the detection now reads pg_settings.source and refuses that case up front.
  • The disk gate refused with wal_volume_free_mb left at 0, then refused again at a 28MB ceiling against a 48MB setting, both times printing the numbers and changing nothing.
  • Declining the approval left the setting alone.
  • An unreachable host failed the first query and fired the Slack alert.

Prerequisites

A PostgreSQL 16 or earlier server reachable over JDBC. Version 17 needs the change in How to extend. The connecting role needs to read pg_stat_bgwriter, pg_settings plus pg_ls_waldir(), which means membership of pg_monitor or superuser. To apply the change it must be a superuser or hold GRANT SET ON PARAMETER max_wal_size. It also needs EXECUTE on pg_reload_conf().

Secrets

  • POSTGRES_USERNAME: PostgreSQL user, read when use_secret_auth is true.
  • POSTGRES_PASSWORD: password for that user.
  • SLACK_WEBHOOK_URL: used by findings_alert and the errors block.
  • In Kestra OSS, provide each secret as a base64-encoded environment variable prefixed SECRET_.

Inputs

Name Type Default Description
postgres_url STRING jdbc:postgresql://localhost:5432/postgres JDBC URL for the target instance.
use_secret_auth BOOL true Read credentials from secrets. Set false only for inline test credentials.
min_window_checkpoints INT 20 Minimum checkpoints in the window before the ratio is judged.
max_requested_share FLOAT 0.5 Share of window checkpoints that may be forced by WAL volume.
headroom_factor FLOAT 2.0 Multiple of the measured WAL per checkpoint_timeout period to propose.
max_wal_ceiling_mb INT 4096 Hard cap in MB on the proposal.
wal_volume_free_mb INT 0 Free space in MB on the filesystem holding pg_wal. 0 refuses any raise.
wal_disk_fraction FLOAT 0.25 Largest share of the WAL volume max_wal_size may claim.
dry_run BOOL true Report without changing anything.
auto_remediate BOOL false Apply behind the approval gate when dry_run is false.

Quick start

  1. Set POSTGRES_USERNAME, POSTGRES_PASSWORD plus SLACK_WEBHOOK_URL as namespace secrets.
  2. Import this flow.
  3. Run it once against a write heavy instance. The first run records a baseline and judges nothing, which is expected.
  4. Enable the hourly trigger so the sampling runs on its own. From the second run on, each run reports the ratio for the window since the last one.
  5. To apply a proposal, set wal_volume_free_mb from your monitoring, run with dry_run false and auto_remediate true, then resume the paused execution with approved true.

How to extend

  • On PostgreSQL 17 and later these counters moved to pg_stat_checkpointer as num_requested and num_timed. Point the two reads at that view and the rest of the flow is unchanged.
  • Add checkpoint_write_time plus buffers_checkpoint to the baseline to report the IO each checkpoint actually flushed, not just how many there were.
  • Raise checkpoint_timeout in the same gated step for an instance that can afford an even longer recovery window, since the derived need scales with it.
  • Point the flow at each instance in turn from a parent flow. The KV key is derived from the URL, so every instance keeps its own window.
  • Fail the run as soon as pressure is detected, for a read-only check with no remediation.
  • Feed wal_volume_free_mb from a node exporter query ahead of the run instead of an input, so the disk gate reads live free space.

Links

See How

New to Kestra?

Use blueprints to kickstart your first workflows.