PostgreSQL PITR

PostgreSQL PITR: WAL Archiving and Restore Tests

PostgreSQL PITR restores a database cluster to a chosen historical point using a physical base backup and archived write-ahead logs (WAL). For SaaS teams, it can reverse an accidental deletion or damaging migration, provided the backup and WAL sequence support the intended recovery target.

The operational requirement is tested recovery: your team must retrieve the backup, replay WAL, validate the application, and restore service within its agreed deadline. Start by understanding which pieces must remain connected.

Key takeaways

  • Keep a valid base backup and an uninterrupted WAL archive covering the recovery period.
  • Restore into an isolated instance before replacing production data or extracting one tenant.
  • Measure success through application correctness, recovery time, and actual data loss, not backup-job status.

How PostgreSQL PITR works

A technical vector illustration showing a database recovery pipeline diagram with a timeline.

A base backup provides the starting state

A physical base backup captures the PostgreSQL cluster, including its databases. WAL then supplies the changes needed to reach a consistent state and continue toward your target.

PostgreSQL’s continuous archiving documentation describes the required relationship: recovery needs a base backup plus an unbroken WAL sequence extending back to that backup’s start. Choose a target after the backup finished.

A pg_dump archive isn’t a physical base backup. It supports logical restoration, but you can’t replay WAL against it to perform cluster-level PITR.

WAL supplies the recovery history

During recovery, PostgreSQL applies WAL records until it reaches the configured stopping point. A missing required segment breaks that path.

Therefore, retention must preserve complete recovery chains. Keeping a base backup while deleting WAL it requires can leave an apparently healthy backup unusable. Protect backups, archived WAL, configuration, and encryption keys against the same failures that could affect production.

Configure WAL archiving before taking backups

For self-managed PostgreSQL, archive_command sends completed WAL segments to archive storage. A backup tool such as pgBackRest can manage transfers, retries, repositories, and retention.

The following illustrative configuration assumes a configured pgBackRest repository and a stanza named saas. A stanza identifies the PostgreSQL installation being protected.

PostgreSQL setting Illustrative configuration
WAL detail wal_level = replica
Archive activation archive_mode = on
Archive operation archive_command = 'pgbackrest --stanza=saas archive-push %p'

Here, %p becomes the WAL file’s source path. Adapt the stanza name, executable location, repository configuration, credentials, and filesystem permissions to your installation.

Changes to wal_level and archive_mode require a server restart. PostgreSQL’s WAL configuration reference documents these settings.

Test archiving before creating the first base backup. With pgBackRest configured, run pgbackrest --stanza=saas check, followed by pgbackrest --stanza=saas --type=full backup.

Monitor pg_stat_archiver, backup-tool logs, repository availability, and free space under pg_wal. Repeated archive failures can accumulate WAL until storage fills.

Also account for quiet databases. Archiving normally waits for a segment to complete, so low write volume can increase off-host protection lag. archive_timeout can force periodic segment switches, but shorter settings increase archive storage overhead.

Choose a recovery target you can defend

Use application audit records, deployment logs, and transaction evidence to identify the last acceptable business state. A timestamp target follows transaction commit timing, which can differ from an API request’s start time.

Always include a timezone offset. An ambiguous local timestamp is an avoidable incident risk.

Set one target type, such as recovery_target_time, recovery_target_lsn, or recovery_target_name. For planned risky work, pg_create_restore_point() can create a named target beforehand.

The inclusivity setting matters: recovery_target_inclusive = off excludes a transaction exactly at the target boundary. It doesn’t compensate for choosing the wrong timestamp.

Record the intended timeline when previous recoveries have created branches. Also document which legitimate changes after the target will be absent. An intentional rollback can discard more data than archive lag alone suggests.

Restore to an isolated PostgreSQL instance

The following procedure uses pgBackRest and PostgreSQL 12 or later. Physical restoration needs the same PostgreSQL major version, compatible binaries and extensions, sufficient storage, repository access, and any required decryption keys.

  1. Contain the incident and preserve evidence. Stop harmful writes and retain logs. For production cutover, establish a write fence covering APIs, workers, integrations, and scheduled jobs. Preserve the existing cluster for investigation and rollback.
  2. Prepare a separate destination. Keep PostgreSQL stopped and use an empty recovery data directory. Block customer traffic and outbound automation. Adapt tablespace paths, ownership, ports, authentication, and network settings without touching production’s data directory.
  3. Restore the selected backup and configure the target. An illustrative command is pgbackrest --stanza=saas --pg1-path=/srv/postgresql/recovery --type=time --target='2026-11-12 14:03:21+00' --target-exclusive --target-action=pause restore. Replace the path and timestamp with your recovery destination and incident target. Run it with recovery-specific pgBackRest configuration.
  4. Review the generated recovery settings before startup. The command configures archive retrieval and targeted recovery. For an isolated test, set archive_mode = off so the recovered instance won’t archive into production’s repository.
  5. Start PostgreSQL and inspect recovery logs. Confirm that it reaches the requested target. Validate the paused instance before ending recovery. With pause-at-target recovery, SELECT pg_wal_replay_resume(); lets recovery finish.

The generated configuration connects these pieces:

Component Purpose
restore_command Retrieves requested WAL, commonly through pgbackrest --stanza=saas archive-get %f "%p"
recovery.signal Triggers archive recovery at startup
recovery_target_time Selects the stopping timestamp
recovery_target_inclusive = off Excludes the exact target boundary
recovery_target_action = pause Leaves recovery paused for inspection

Here, %f is the requested archive filename and %p is its destination path.

Don’t substitute standby.signal, which requests standby mode. Recovery settings belong in PostgreSQL configuration; older tutorials using recovery.conf describe the pre-12 mechanism.

Validate restored data and application behavior

An isometric illustration showing two separated database network clusters in cloud environments.

Prove the recovered business state

First, establish that the unwanted transaction is absent and expected earlier transactions remain. Compare identifiers, relationships, and financial or subscription totals. Matching row counts alone can conceal incorrect records.

Then exercise the application against the recovered instance. Test authentication, tenant authorization, invoice access, and an important write workflow after recovery ends. Use compatible application code because historical schemas may not support the latest release.

Keep payment calls, customer emails, and outbound webhooks disabled. Database recovery doesn’t rewind external systems or restore externally stored files. Reconcile object-storage versions, billing state, caches, and search indexes separately.

Respect tenant recovery boundaries

Physical PostgreSQL PITR restores the cluster. It doesn’t select one SaaS customer.

For a tenant incident, recover the cluster separately, then extract the intended database, schema, or tenant-filtered rows. Keep that recovered source read-only during extraction.

Before replacement, pause the tenant’s writers and preserve its current state. Handle related records together, then test access using the restricted application role and normal connection-pooling path.

Restoring the shared production cluster to fix one tenant also rolls back unrelated tenants’ legitimate changes.

For shared tables, tenant-filtered extraction and controlled replacement are usually safer than a cluster-wide production rollback.

Schedule repeatable restore tests

We recommend scheduling a restore job after each new full-backup cycle and repeating it after backup configuration, encryption-key, extension, or PostgreSQL-version changes. This is an operating recommendation, not a PostgreSQL-required interval.

Automate environment creation, backup selection, target selection, restoration, validation, and cleanup. Retain a machine-readable result plus logs and timestamps. Exercise older retained backups too, because success with the newest backup doesn’t prove the advertised historical recovery window.

Keep drill infrastructure separate from production credentials and endpoints. A test should fail clearly when required WAL or keys are unavailable.

Use this concise completion checklist:

  • The chosen backup and WAL chain reached the requested target without missing required files.
  • Business-data checks and restricted-role application tests passed without triggering external actions.
  • Timings, recoverable transaction boundaries, failures, and cleanup results are recorded.

A backup verification utility adds useful checks, but it doesn’t replace starting PostgreSQL and validating the recovered application.

Measure recovery against RTO and RPO

RTO includes more than WAL replay

The recovery time objective is the deadline for returning the affected service to usable operation.

Measure incident declaration, investigation, target selection, provisioning, download, WAL replay, validation, and cutover. Record each stage separately so the team can identify what prevents it meeting the deadline.

A database accepting connections doesn’t establish service recovery. Connection pools may still point at the old instance, and application checks may still fail.

RPO follows the recoverable transaction boundary

The recovery point objective is the acceptable amount of lost data, expressed as time.

During drills, compare the interruption point with the latest committed transaction you can recover. Backup frequency alone doesn’t establish that gap because archive delay, upload failures, and missing WAL also matter.

For an intentional rollback, separately record legitimate post-target changes requiring reconciliation. This distinguishes protection lag from deliberate historical recovery.

Managed PostgreSQL uses provider-specific procedures

Self-managed PostgreSQL exposes the filesystem, archive commands, and recovery configuration directly. Your team owns repository protection, retention, monitoring, and restoration.

Managed services usually expose PITR through a console or API instead. Amazon RDS for PostgreSQL, for example, restores to a new DB instance while leaving the source intact. The filesystem procedure above isn’t its customer-facing workflow.

The application work remains: isolate the destination, select a target, validate data, reconcile external systems, and switch endpoints. Include provisioning and connection-pool turnover in the drill’s elapsed time.

Frequently asked questions

Can PostgreSQL PITR recover one table?

PITR recovers the physical cluster. To recover one table, restore separately and extract it afterward. Include dependent objects and related data in the recovery plan.

Is a successful backup enough?

No. Backup completion doesn’t prove that archived WAL, credentials, extensions, and application dependencies will work during restoration. A successful drill demonstrates the complete path.

Make recovery a tested operating procedure

Reliable PostgreSQL PITR combines a valid base backup, continuous WAL archiving, a defensible target, and an isolated restoration. Application validation determines whether that restored state is usable.

Keep the restore procedure executable and its results measurable. Recovery is complete when the intended data works, tenant isolation holds, and service returns within the agreed deadline.

About the author

The SAAS Podium

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *