PostgreSQL DBA Part 20: Point-in-Time Recovery (PITR) Step by Step

PostgreSQL DBA Part 20: Point-in-Time Recovery (PITR) Step by Step
In this article
  1. What you will learn
  2. Prerequisites
  3. How it works
  4. Set up a test scenario
  5. Find the exact moment of the mistake
  6. Recover a copy of the cluster to a point in time
  7. Other recovery targets
  8. Recover the whole server in place
  9. Common mistakes and how to fix them
  10. Practice exercise
  11. Quick reference
  12. Summary and what's next

This is Part 20 of the PostgreSQL DBA series. Point-in-time recovery (PITR) lets you bring a PostgreSQL cluster back to the exact moment before a mistake, for example one second before someone ran DROP TABLE on a production table. You do it by restoring a base backup and replaying archived WAL up to a stop point you choose. By the end of this part you will be able to find the exact time of a bad transaction, recover a copy of the cluster to just before it, copy the lost data back, and run the full in-place recovery procedure from the PostgreSQL documentation.

In Part 19 we covered WAL archiving with archive_command, and in Part 18 we took base backups with pg_basebackup. This part puts the two together. Without both of them, point-in-time recovery is not possible.

What you will learn

  • How a base backup, the WAL archive and a recovery target work together
  • How to find the exact time, transaction ID and LSN of a bad change with pg_waldump
  • How to recover into a separate cluster with restore_command, recovery_target_time and recovery.signal
  • How to pause at the target, check the data, and finish recovery with pg_wal_replay_resume()
  • How to run the official in-place recovery procedure and what a new timeline means
  • The real error messages you will meet and how to fix each one

Prerequisites

  • Parts 1 to 19 of this series, especially Part 18 (pg_basebackup) and Part 19 (WAL archiving).
  • One Ubuntu server (we call it db1, 10.0.0.11) with PostgreSQL 18 from the PGDG repository and the cluster 18 main running.
  • WAL archiving turned on as in Part 19: archive_mode = on and archive_command copying files to /mnt/wal_archive.
  • Enough free disk for a second copy of the cluster. We restore into a second cluster called 18 pitr on port 5433, so the original stays untouched.
  • sudo access, and the postgres operating system user for PostgreSQL commands.

How it works

Think of a base backup as a photo of the data directory at one moment. The WAL archive is the notebook in which PostgreSQL wrote down every change after that photo was taken. Point-in-time recovery means: put the photo back, then re-apply the notebook line by line, and stop reading at the line you choose.

That stop point is called the recovery target. You can give it as a time, a named restore point, a transaction ID or a WAL position (LSN, log sequence number, which is a byte position in the WAL stream). If you give no target, PostgreSQL replays all the WAL it can find and recovers to the latest possible state.

Three things switch a cluster into this kind of recovery, which the documentation calls archive recovery: the restored base backup (with its backup_label file), an empty file named recovery.signal in the data directory, and a restore_command that tells PostgreSQL how to fetch an archived WAL file. restore_command is the reverse of archive_command: %f is replaced by the file name PostgreSQL wants and %p by the path where it must be copied.

db1 (10.0.0.11)

  /var/lib/postgresql/backups/base_2026_11_17   base backup from Part 18 (the photo)
  /mnt/wal_archive                              archived WAL from Part 19 (the notebook)
                 |
                 |  restore_command = 'cp /mnt/wal_archive/%f %p'
                 v
  cluster 18/pitr, port 5433   replays WAL, stops at the recovery target,
                               then becomes a normal read-write server
The PITR lab used in this part

When recovery reaches the target, recovery_target_action decides what happens next. The default, pause, stops replay and lets you run read-only queries so you can check you stopped at the right place. promote ends recovery and opens the server for writes. shutdown stops the server. Pausing only lets you run queries when hot_standby is on, which is the default; if it is off, pause acts like shutdown.

When recovery ends, PostgreSQL starts a new timeline. A timeline is a numbered branch of history. The original server keeps writing on timeline 1, the recovered copy writes on timeline 2, and the new WAL file names start with 00000002. This stops the two histories from overwriting each other in the archive. PostgreSQL records each branch in a small .history file.

Set up a test scenario

To practise safely, we create a small table, take a base backup, make some good changes, and then make a mistake on purpose. Run all of this on a test server, not on production.

Step 1: Create the sample data

On db1, as the postgres user, create a database and a payments table:

sudo -u postgres psql
Open psql as postgres
CREATE DATABASE shop;
\c shop
CREATE TABLE payments (
  payment_id  serial PRIMARY KEY,
  customer    text    NOT NULL,
  amount      numeric(10,2) NOT NULL,
  paid_at     timestamptz NOT NULL DEFAULT now()
);
INSERT INTO payments (customer, amount) VALUES
  ('Asha', 1500.00), ('Ravi', 899.50), ('Meena', 2400.00);
SELECT * FROM payments;
Sample table in the shop database
 payment_id | customer | amount  |            paid_at
------------+----------+---------+-------------------------------
          1 | Asha     | 1500.00 | 2026-11-17 12:47:45.136979+00
          2 | Ravi     |  899.50 | 2026-11-17 12:47:45.136979+00
          3 | Meena    | 2400.00 | 2026-11-17 12:47:45.136979+00
(3 rows)
Output

Three rows exist. Leave psql with \q. The server time zone is UTC here, which is why timestamps end in +00.

Step 2: Take a base backup

On db1, as the postgres user, take a plain-format base backup exactly as in Part 18:

sudo -u postgres mkdir -p /var/lib/postgresql/backups
sudo -u postgres pg_basebackup -D /var/lib/postgresql/backups/base_2026_11_17 \
  --checkpoint=fast --label=base_2026_11_17 --progress
Base backup
OptionWhat it does
-DDirectory to write the backup into. It must not exist or must be empty.
--checkpoint=fastAsk for an immediate checkpoint so the backup starts at once.
--labelA label stored in backup_label to identify the backup.
--progressShow progress while the backup runs.
waiting for checkpoint
30680/30680 kB (100%), 0/1 tablespace
30680/30680 kB (100%), 1/1 tablespace
Output (expected output)

Check that the backup history file reached the archive. It records where the backup started and stopped in the WAL:

sudo -u postgres cat /mnt/wal_archive/000000010000000000000003.00000028.backup
Read the backup history file
START WAL LOCATION: 0/3000028 (file 000000010000000000000003)
STOP WAL LOCATION: 0/3000100 (file 000000010000000000000003)
CHECKPOINT LOCATION: 0/3000060
BACKUP METHOD: streamed
BACKUP FROM: primary
START TIME: 2026-11-17 12:47:45 UTC
LABEL: base_2026_11_17
START TIMELINE: 1
STOP TIME: 2026-11-17 12:47:45 UTC
STOP TIMELINE: 1
Output (expected output)

STOP TIME is the earliest moment this backup can be recovered to. Your file name will differ; list /mnt/wal_archive to find it.

Step 3: Make good changes and a restore point

On db1, in psql as postgres connected to shop, add two payments and create a named restore point. A restore point is a named marker written into the WAL that you can later use as a recovery target. Creating one before risky work, such as a month-end cleanup or a deployment, is a cheap habit that makes recovery much easier.

INSERT INTO payments (customer, amount) VALUES ('Kiran', 3200.00), ('Fatima', 750.00);
SELECT pg_create_restore_point('before_month_end_cleanup');
INSERT INTO payments (customer, amount) VALUES ('John', 1250.00);
Changes after the backup
INSERT 0 2
 pg_create_restore_point
-------------------------
 0/40003B8
(1 row)

INSERT 0 1
Output

The function returns the WAL location of the marker. Only superusers can run pg_create_restore_point by default. Use unique names: if two restore points share a name, recovery stops at the first one.

Step 4: Make the mistake

Now drop the table, as if someone ran the command on the wrong server. Then make one more good change in a different table, so you can see what point-in-time recovery keeps and what it throws away.

SELECT now();
DROP TABLE payments;
CREATE TABLE refunds (refund_id int, amount numeric);
INSERT INTO refunds VALUES (1, 99.00);
The accident, followed by unrelated good work
              now
-------------------------------
 2026-11-17 12:48:11.504442+00
(1 row)

DROP TABLE
CREATE TABLE
INSERT 0 1
Output

In real life nobody records the time before a mistake. You usually get a rough time from the person who made it or from the application logs. Step 6 shows how to find the exact time.

Step 5: Make sure the WAL is archived

Recovery can only replay WAL that is in the archive. The current WAL file is archived only when it is full, when archive_timeout passes, or when you force a switch. On db1, as postgres, force the switch and check the archive:

sudo -u postgres psql -c "SELECT pg_switch_wal();"
sudo -u postgres ls /mnt/wal_archive
Force a WAL switch and list the archive
 pg_switch_wal
---------------
 0/4027FA8
(1 row)

000000010000000000000001
000000010000000000000002
000000010000000000000003
000000010000000000000003.00000028.backup
000000010000000000000004
Output

Segment 000000010000000000000004 holds everything from Steps 3 and 4. If pg_stat_archiver shows failures, fix archiving first (Part 19), because recovery cannot go past a missing WAL file.

Find the exact moment of the mistake

Step 6: Read the archived WAL with pg_waldump

pg_waldump prints WAL records in a human-readable form. On db1, as postgres, list the commit records in the segment that holds the accident:

sudo -u postgres /usr/lib/postgresql/18/bin/pg_waldump \
  --path=/mnt/wal_archive --rmgr=Transaction 000000010000000000000004
List transaction commits in one WAL segment
OptionWhat it does
--pathDirectory to search for WAL segment files.
--rmgr=TransactionOnly show records from the Transaction resource manager (commits and aborts). Use --rmgr=list to see all names.
000000010000000000000004The start segment. It also sets the timeline to read (1 here).
rmgr: Transaction len (rec/tot):     34/    34, tx:        733, lsn: 0/04000328, prev 0/040002E8, desc: COMMIT 2026-11-17 12:47:56.427598 UTC
rmgr: Transaction len (rec/tot):     34/    34, tx:        734, lsn: 0/04000448, prev 0/04000408, desc: COMMIT 2026-11-17 12:48:01.468474 UTC
rmgr: Transaction len (rec/tot):   1829/  1829, tx:        735, lsn: 0/04010980, prev 0/04010948, desc: COMMIT 2026-11-17 12:48:11.505894 UTC; rels: base/16384/16386 base/1638...
rmgr: Transaction len (rec/tot):   1093/  1093, tx:        736, lsn: 0/04027AE0, prev 0/04027A98, desc: COMMIT 2026-11-17 12:48:16.568649 UTC; inval msgs: catcache 80 ...
rmgr: Transaction len (rec/tot):     34/    34, tx:        737, lsn: 0/04027F68, prev 0/04027F28, desc: COMMIT 2026-11-17 12:48:16.570048 UTC
Output (long lines cut)

Transaction 735 is the DROP TABLE. Its commit record lists rels:, the data files that were removed, and it committed at 12:48:11.505894 UTC. Transactions 733 and 734 are the good inserts. 736 and 737 are the refunds work. The base/16384/16386 path is database 16384, file 16386; on the recovered copy you can confirm it is the payments table with SELECT relname FROM pg_class WHERE relfilenode = 16386;.

Write down three values: the commit time 2026-11-17 12:48:11.505894+00, the transaction ID 735 and the commit LSN 0/04010980. Any of them can be used as the target. Run pg_waldump on archived files, not on the live pg_wal directory, because the documentation warns it can give wrong results while the server is running.

Recover a copy of the cluster to a point in time

The safest first move is to recover into a separate cluster. Production keeps running, the damaged data stays untouched, and you can try again with a different target as many times as you need.

Step 7: Create an empty cluster for the recovery

On db1, with sudo, create a new cluster called pitr on port 5433:

sudo pg_createcluster 18 pitr --port 5433
pg_lsclusters
Create the target cluster
Ver Cluster Port Status Owner    Data directory              Log file
18  main    5432 online postgres /var/lib/postgresql/18/main /var/log/postgresql/postgresql-18-main.log
18  pitr    5433 down   postgres /var/lib/postgresql/18/pitr /var/log/postgresql/postgresql-18-pitr.log
Output (expected output)

The new cluster has its own configuration in /etc/postgresql/18/pitr/. Its postgresql.conf has archive_mode off, which is what we want: the recovered copy must not write its own WAL into the production archive.

Step 8: Restore the base backup and empty pg_wal

On db1, as the postgres user, replace the new cluster's files with the base backup, then delete the WAL files that came with the backup:

sudo -u postgres bash -c 'rm -rf /var/lib/postgresql/18/pitr/*'
sudo -u postgres cp -a /var/lib/postgresql/backups/base_2026_11_17/. /var/lib/postgresql/18/pitr/
sudo -u postgres bash -c 'rm -f /var/lib/postgresql/18/pitr/pg_wal/0000*'
sudo -u postgres ls -la /var/lib/postgresql/18/pitr/pg_wal/
Restore the backup files
Command or optionWhat it does
rm -rf .../pitr/*Empties the new cluster's data directory but keeps the directory and its 700 permissions.
cp -aArchive copy: keeps ownership, permissions and timestamps, which PostgreSQL checks at start.
rm -f .../pg_wal/0000*Removes WAL files copied with the backup. The documentation says they are probably obsolete; PostgreSQL will fetch what it needs from the archive.
total 12
drwx------  3 postgres postgres 4096 Nov 17 12:48 .
drwx------ 19 postgres postgres 4096 Nov 17 12:47 ..
drwx------  2 postgres postgres 4096 Nov 17 12:47 archive_status
Output (expected output)

Only the empty archive_status folder remains in pg_wal. The data directory is owned by postgres with drwx------, which is correct.

Step 9: Set the recovery target and create recovery.signal

On db1, as postgres, put the recovery settings in a separate file in the cluster's conf.d folder. Ubuntu's postgresql.conf includes every .conf file in that folder, so you can remove the settings later by deleting one file.

sudo -u postgres tee /etc/postgresql/18/pitr/conf.d/pitr.conf <<'EOF'
restore_command = 'cp /mnt/wal_archive/%f %p'
recovery_target_time = '2026-11-17 12:48:11.505894+00'
recovery_target_inclusive = off
recovery_target_action = 'pause'
EOF
sudo -u postgres touch /var/lib/postgresql/18/pitr/recovery.signal
Recovery settings and the signal file
SettingDefaultWhat it does
restore_commandemptyShell command that copies archived WAL file %f to path %p. Required for archive recovery. Must return non-zero when a file does not exist.
recovery_target_timeemptyReplay up to this time stamp. Use a numeric UTC offset or a full zone name, never an abbreviation like IST.
recovery_target_inclusiveonon stops just after the target, off stops just before it. Applies to time, xid and LSN targets.
recovery_target_actionpauseWhat to do at the target: pause, promote or shutdown.
recovery_target_timelinelatestWhich timeline to follow. latest follows the newest timeline found in the archive.

We use the exact commit time of transaction 735 with recovery_target_inclusive = off, so recovery stops just before that commit and the DROP TABLE never happens. With the default on, the drop would be replayed. For people in India, '2026-11-17 18:18:11.505894+05:30' means the same moment.

The recovery target settings can only be set at server start, so they take effect only when the cluster starts. recovery.signal is an empty file; its presence is what tells PostgreSQL to perform archive recovery instead of a normal start.

Step 10: Start the cluster and read the log

On db1, with sudo, start the cluster and read its log:

sudo pg_ctlcluster 18 pitr start
pg_lsclusters
sudo grep -v '^cp: cannot' /var/log/postgresql/postgresql-18-pitr.log
Start recovery
Ver Cluster Port Status          Owner    Data directory              Log file
18  main    5432 online          postgres /var/lib/postgresql/18/main /var/log/postgresql/postgresql-18-main.log
18  pitr    5433 online,recovery postgres /var/lib/postgresql/18/pitr /var/log/postgresql/postgresql-18-pitr.log

LOG:  database system was interrupted; last known up at 2026-11-17 12:47:45 UTC
LOG:  starting point-in-time recovery to 2026-11-17 12:48:11.505894+00
LOG:  starting backup recovery with redo LSN 0/3000028, checkpoint LSN 0/3000060, on timeline ID 1
LOG:  restored log file "000000010000000000000003" from archive
LOG:  redo starts at 0/3000028
LOG:  restored log file "000000010000000000000004" from archive
LOG:  completed backup recovery with redo LSN 0/3000028 and end LSN 0/3000100
LOG:  consistent recovery state reached at 0/3000100
LOG:  database system is ready to accept read-only connections
LOG:  recovery stopping before commit of transaction 735, time 2026-11-17 12:48:11.505894+00
LOG:  pausing at the end of recovery
HINT:  Execute pg_wal_replay_resume() to promote.
Output (expected output), log timestamps and PIDs removed

Read the log from top to bottom. PostgreSQL fetched segments 3 and 4 from the archive, reached a consistent state at the end of the backup, and stopped before the commit of transaction 735, the DROP TABLE. The status online,recovery means it is up but still in recovery and read-only.

The grep -v hides lines like cp: cannot stat ... 00000002.history: No such file or directory. These are normal: PostgreSQL asks restore_command for files that may not exist, such as the history file of a newer timeline, and a non-zero exit simply means the file is not there.

Step 11: Check the data while recovery is paused

On db1, as postgres, connect to port 5433 and check where replay stopped:

sudo -u postgres psql -p 5433 -d shop -c "SELECT pg_is_in_recovery(), pg_get_wal_replay_pause_state(), pg_last_wal_replay_lsn(), pg_last_xact_replay_timestamp();"
Check the recovery state
 pg_is_in_recovery | pg_get_wal_replay_pause_state | pg_last_wal_replay_lsn | pg_last_xact_replay_timestamp
-------------------+-------------------------------+------------------------+-------------------------------
 t                 | paused                        | 0/4010980              | 2026-11-17 12:48:01.468474+00
(1 row)
Output

Recovery is paused at LSN 0/4010980, the commit LSN of the drop. The last replayed transaction is the John insert at 12:48:01. Now check that the table exists and that the later refunds table does not:

sudo -u postgres psql -p 5433 -d shop -c "SELECT to_regclass('payments') AS payments_table, to_regclass('refunds') AS refunds_table;"
Check which tables exist at this point
 payments_table | refunds_table
----------------+---------------
 payments       |
(1 row)
Output

If the check shows you stopped in the wrong place, do not resume. Stop the cluster, repeat Step 8 to restore the backup again, set a different target in Step 9 and start again. Once a recovery ends and a new timeline starts, you cannot continue replaying from that copy.

Step 12: End recovery and verify

On db1, as postgres, end recovery. pg_wal_replay_resume() lifts the pause, and because the target has been reached, recovery finishes and the server becomes read-write:

sudo -u postgres psql -p 5433 -c "SELECT pg_wal_replay_resume();"
sudo -u postgres psql -p 5433 -d shop -c "SELECT pg_is_in_recovery();" \
  -c "SELECT payment_id, customer, amount FROM payments ORDER BY payment_id;"
Finish recovery and read the table
 pg_is_in_recovery
-------------------
 f
(1 row)

 payment_id | customer | amount
------------+----------+---------
          1 | Asha     | 1500.00
          2 | Ravi     |  899.50
          3 | Meena    | 2400.00
          4 | Kiran    | 3200.00
          5 | Fatima   |  750.00
          6 | John     | 1250.00
(6 rows)
Output

All six payments are back, including the three made after the base backup. The log shows recovery finishing on a new timeline:

LOG:  redo done at 0/4010980 system usage: CPU: user: 0.00 s, system: 0.01 s, elapsed: 143.58 s
LOG:  last completed transaction was at log time 2026-11-17 12:48:01.468474+00
LOG:  selected new timeline ID: 2
LOG:  archive recovery complete
LOG:  checkpoint starting: end-of-recovery immediate wait
LOG:  database system is ready to accept connections
Output (expected output), from /var/log/postgresql/postgresql-18-pitr.log

PostgreSQL removed recovery.signal and renamed backup_label to backup_label.old, so the cluster will not enter recovery again on its next start.

Step 13: Copy the recovered table back to production

The production cluster (port 5432) still has the refunds work done after the accident, so we do not want to rewind all of it. Copy only the lost table across. On db1, as postgres, dump payments from the recovered copy and restore it into production:

sudo -u postgres pg_dump -p 5433 -d shop -t payments -Fc -f /var/lib/postgresql/backups/payments_recovered.dump
sudo -u postgres pg_restore -p 5432 -d shop -v /var/lib/postgresql/backups/payments_recovered.dump
Move the recovered table into production
OptionWhat it does
-pPort of the server to connect to (5433 is the recovered copy, 5432 is production).
-dDatabase to connect to.
-t paymentspg_dump: dump only this table (with its sequence, indexes and constraints).
-Fcpg_dump: custom format, which pg_restore can read.
-fpg_dump: output file.
-vpg_restore: verbose, print each object as it is created.
pg_restore: connecting to database for restore
pg_restore: creating TABLE "public.payments"
pg_restore: creating SEQUENCE "public.payments_payment_id_seq"
pg_restore: creating SEQUENCE OWNED BY "public.payments_payment_id_seq"
pg_restore: creating DEFAULT "public.payments payment_id"
pg_restore: processing data for table "public.payments"
pg_restore: executing SEQUENCE SET payments_payment_id_seq
pg_restore: creating CONSTRAINT "public.payments payments_pkey"
Output (expected output)

Verify on production that both the recovered table and the later work are there:

sudo -u postgres psql -d shop -c "SELECT count(*), sum(amount) FROM payments;" -c "SELECT * FROM refunds;"
Check production
 count |   sum
-------+---------
     6 | 9999.50
(1 row)

 refund_id | amount
-----------+--------
         1 |  99.00
(1 row)
Output

The dump includes the table's indexes, constraints and grants. If other tables had foreign keys pointing to payments, the original DROP TABLE ... CASCADE removed those constraints, so recreate them. Also note that the sequence may jump ahead after recovery, because PostgreSQL logs sequence values in batches. Gaps in payment_id are normal. For more on dump and restore options, see Part 17.

Other recovery targets

A time is the most common target, but you have four other choices. Use only one: setting two of them is an error.

SettingExampleWhen to use it
recovery_target_name'before_month_end_cleanup'You created a restore point with pg_create_restore_point() before risky work.
recovery_target_xid'735'You know the transaction ID from pg_waldump. Use with recovery_target_inclusive = off to stop before it.
recovery_target_lsn'0/4010980'You know the exact WAL position, for example from pg_waldump.
recovery_target_time'2026-11-17 12:48:11+00'You know when the mistake happened.
recovery_target'immediate'Stop as soon as the backup is consistent, that is at the end of the base backup.

With recovery_target_name = 'before_month_end_cleanup' and recovery_target_action = 'promote', the same lab gives this log:

LOG:  starting point-in-time recovery to "before_month_end_cleanup"
...
LOG:  recovery stopping at restore point "before_month_end_cleanup", time 2026-11-17 12:47:56.428779+00
LOG:  redo done at 0/4000350 system usage: CPU: user: 0.00 s, system: 0.00 s, elapsed: 0.03 s
LOG:  last completed transaction was at log time 2026-11-17 12:47:56.427598+00
LOG:  selected new timeline ID: 2
LOG:  archive recovery complete
Output (expected output)

This time the table has five rows: John's payment was made after the restore point, so it is not replayed. That is the trade-off of every point-in-time recovery: everything after the target is lost on the recovered copy.

Recover the whole server in place

Sometimes you must rewind the production cluster itself, for example when a bad deployment damaged many tables. The documentation gives a fixed procedure for this. It is the same as Steps 8 to 12, with extra steps to protect the current files. Everything written after the target, on every database in the cluster, is lost.

Step 14: Stop the server and move the data directory aside

On db1, with sudo, stop the cluster and move its data directory to a new name. Moving keeps a full copy without needing extra disk space. If you use tablespaces (Part 9), save their directories too.

sudo systemctl stop postgresql@18-main
sudo -u postgres mv /var/lib/postgresql/18/main /var/lib/postgresql/18/main.damaged
Stop and keep the old files

Check with pg_lsclusters: 18 main shows down.

Step 15: Save WAL that was never archived

The last WAL file may hold changes that were not archived yet. The documentation says to save pg_wal. On db1, as postgres, copy it and find the newest WAL file with pg_controldata:

sudo -u postgres mkdir -p /var/lib/postgresql/pg_wal_saved
sudo -u postgres cp -a /var/lib/postgresql/18/main.damaged/pg_wal/. /var/lib/postgresql/pg_wal_saved/
sudo -u postgres /usr/lib/postgresql/18/bin/pg_controldata /var/lib/postgresql/18/main.damaged | grep -E "cluster state|REDO WAL file"
Save pg_wal
Database cluster state:               shut down
Latest checkpoint's REDO WAL file:    000000010000000000000009
Output (expected output)

Segment 000000010000000000000009 is the current one and is not in the archive yet. Higher-numbered files in pg_wal are usually old segments recycled for reuse; they are harmless.

Step 16: Restore the backup and the unarchived WAL

On db1, as postgres, create an empty data directory, copy the base backup in, empty its pg_wal and copy in the saved current segment. The documentation recommends copying, not moving, so the saved files stay unchanged if you need to start again.

sudo -u postgres install -d -m 700 /var/lib/postgresql/18/main
sudo -u postgres cp -a /var/lib/postgresql/backups/base_2026_11_17/. /var/lib/postgresql/18/main/
sudo -u postgres bash -c 'rm -f /var/lib/postgresql/18/main/pg_wal/0000*'
sudo -u postgres cp /var/lib/postgresql/pg_wal_saved/000000010000000000000009 /var/lib/postgresql/18/main/pg_wal/
Restore files into the original location

install -d -m 700 creates the directory owned by postgres with the 700 permissions PostgreSQL requires.

Step 17: Configure recovery and keep users out

On db1, write the same recovery settings as Step 9 into the main cluster's conf.d folder, this time with promote. Then follow the documentation's advice to block normal users during recovery with a temporary pg_hba.conf that only allows the local postgres user.

sudo -u postgres tee /etc/postgresql/18/main/conf.d/pitr.conf <<'EOF'
restore_command = 'cp /mnt/wal_archive/%f %p'
recovery_target_time = '2026-11-17 12:48:11.505894+00'
recovery_target_inclusive = off
recovery_target_action = 'promote'
EOF
sudo cp -p /etc/postgresql/18/main/pg_hba.conf /etc/postgresql/18/main/pg_hba.conf.normal
echo "local   all   postgres   peer" | sudo -u postgres tee /etc/postgresql/18/main/pg_hba.conf
sudo -u postgres touch /var/lib/postgresql/18/main/recovery.signal
Recovery settings, locked-down pg_hba.conf, recovery.signal

cp -p keeps the owner (postgres) and permissions on the saved copy, so you can put it back later without a permission error.

Step 18: Start, verify and check the new timeline

sudo systemctl start postgresql@18-main
sudo -u postgres psql -d shop -c "SELECT pg_is_in_recovery(), count(*) AS payments FROM payments;" \
  -c "SELECT timeline_id, redo_wal_file FROM pg_control_checkpoint();"
sudo -u postgres cat /mnt/wal_archive/00000002.history
Verify the in-place recovery
 pg_is_in_recovery | payments
-------------------+----------
 f                 |        6
(1 row)

 timeline_id |      redo_wal_file
-------------+--------------------------
           2 | 000000020000000000000004

1	0/4010980	before 2026-11-17 12:48:11.505894+00
Output (expected output)

The cluster is out of recovery, payments has six rows, and the server now runs on timeline 2. Because this cluster has archiving on, it archived 00000002.history, which says timeline 2 branched from timeline 1 at LSN 0/4010980, just before the target. The refunds table no longer exists on this server: it was created after the target. If you need it, it is still in main.damaged.

The same log messages as Step 10 and Step 12 appear in /var/log/postgresql/postgresql-18-main.log, without the pause.

Step 19: Clean up

On db1, remove the recovery settings, put back the normal pg_hba.conf and reload. The recovery target settings have no effect without recovery.signal, but because they can only change at server start, pg_settings keeps showing them until the next restart. Restart at a convenient time so the next person who looks is not confused.

sudo rm /etc/postgresql/18/main/conf.d/pitr.conf
sudo mv /etc/postgresql/18/main/pg_hba.conf.normal /etc/postgresql/18/main/pg_hba.conf
sudo systemctl reload postgresql@18-main
sudo -u postgres psql -c "SELECT count(*) AS hba_rules FROM pg_hba_file_rules WHERE error IS NULL;"
sudo systemctl restart postgresql@18-main
Remove temporary settings
 hba_rules
-----------
         7
(1 row)
Output (expected output)

Seven rules loaded without errors, so normal connections work again. When you are sure the recovered data is correct, take a new base backup (Part 18): older backups are on timeline 1, and a fresh one gives you a clean starting point on timeline 2. Remove the lab cluster with sudo pg_dropcluster 18 pitr --stop and delete main.damaged and pg_wal_saved only after everyone agrees nothing more is needed from them.

Common mistakes and how to fix them

FATAL: must specify restore_command when standby mode is not enabled

You created recovery.signal but no restore_command is set, often because the settings file is in the wrong cluster's folder. Check /etc/postgresql/18//conf.d/ and start again.

FATAL: multiple recovery targets specified

FATAL:  multiple recovery targets specified
DETAIL:  At most one of recovery_target, recovery_target_lsn, recovery_target_name, recovery_target_time, recovery_target_xid may be set.
Output (expected output)

You set two targets, for example a time and a restore point name. Keep one and comment out the other.

FATAL: recovery ended before configured recovery target was reached

The target is later than the last WAL in the archive. Either the time is wrong (often a time zone mix-up: 18:00+05:30 is 12:30 UTC) or the needed WAL was never archived. Check pg_stat_archiver on the source server, force pg_switch_wal(), and confirm the segment is in the archive. Then restore the backup again and restart.

invalid value for parameter "recovery_target_time"

Time zone abbreviations such as IST are not accepted. Write '2026-11-17 18:18:11+05:30' or a full zone name such as '2026-11-17 18:18:11 Asia/Kolkata'.

FATAL: could not locate required checkpoint record

FATAL:  could not locate required checkpoint record
HINT:  If you are restoring from a backup, touch "/var/lib/postgresql/18/pitr/recovery.signal" and add required recovery options.
	If you are not restoring from a backup, try removing the file "/var/lib/postgresql/18/pitr/backup_label".
	Be careful: removing "/var/lib/postgresql/18/pitr/backup_label" will result in a corrupt cluster if restoring from a backup.
Output (expected output)

You forgot recovery.signal. Create it as the hint says. Never delete backup_label from a restored backup: the server would start but the data would be corrupt.

Recovery stops much earlier than the time you asked for

If the target time is before the base backup's STOP TIME, PostgreSQL does not complain. In our test, a target of 12:40 stopped at the first commit after the backup became consistent (12:47:56). Always compare your target with the backup history file, and use an older backup if you need an earlier point.

A query on the paused server never returns

You paused inside the transaction you are trying to skip, so the startup process still holds its locks (see the warning in Step 11). Check catalog-only facts, end recovery, or choose a target a little earlier.

The recovered copy writes into the production archive

If the recovery cluster has archive_mode = on with the same archive_command (for example because you restored a postgresql.conf copy, or settings came in through postgresql.auto.conf), it archives a new timeline into the production archive. Later recoveries that use the default recovery_target_timeline = 'latest' may then follow that test timeline. Keep archiving off on test copies, check SHOW archive_mode; on port 5433, or set recovery_target_timeline = 'current' when you recover.

Practice exercise

  1. In your lab, take a new base backup into /var/lib/postgresql/backups/base_exercise (Step 2). Then on production insert two more rows into payments, create a restore point named before_exercise, run DELETE FROM payments; and SELECT pg_switch_wal();.
  2. Recover a copy to the restore point using recovery_target_name and recovery_target_action = 'promote', and confirm all rows are present on port 5433.

Quick reference

# 1. (Before any accident) create a restore point before risky work (psql as postgres)
SELECT pg_create_restore_point('before_month_end_cleanup');

# 2. Make sure the latest WAL is archived
sudo -u postgres psql -c "SELECT pg_switch_wal();"
sudo -u postgres ls /mnt/wal_archive

# 3. Find the exact commit time, xid and LSN of the bad transaction
sudo -u postgres /usr/lib/postgresql/18/bin/pg_waldump --path=/mnt/wal_archive --rmgr=Transaction 000000010000000000000004

# 4. Create a separate cluster for the recovery
sudo pg_createcluster 18 pitr --port 5433

# 5. Restore the base backup and empty pg_wal (check the path first)
sudo -u postgres bash -c 'rm -rf /var/lib/postgresql/18/pitr/*'
sudo -u postgres cp -a /var/lib/postgresql/backups/base_2026_11_17/. /var/lib/postgresql/18/pitr/
sudo -u postgres bash -c 'rm -f /var/lib/postgresql/18/pitr/pg_wal/0000*'

# 6. Recovery settings and recovery.signal
sudo -u postgres tee /etc/postgresql/18/pitr/conf.d/pitr.conf <<'EOF'
restore_command = 'cp /mnt/wal_archive/%f %p'
recovery_target_time = '2026-11-17 12:48:11.505894+00'
recovery_target_inclusive = off
recovery_target_action = 'pause'
EOF
sudo -u postgres touch /var/lib/postgresql/18/pitr/recovery.signal

# 7. Start and read the log
sudo pg_ctlcluster 18 pitr start
sudo grep -v '^cp: cannot' /var/log/postgresql/postgresql-18-pitr.log

# 8. Check while paused, then end recovery
sudo -u postgres psql -p 5433 -c "SELECT pg_is_in_recovery(), pg_get_wal_replay_pause_state(), pg_last_xact_replay_timestamp();"
sudo -u postgres psql -p 5433 -c "SELECT pg_wal_replay_resume();"

# 9. Copy the lost table back to production
sudo -u postgres pg_dump -p 5433 -d shop -t payments -Fc -f /var/lib/postgresql/backups/payments_recovered.dump
sudo -u postgres pg_restore -p 5432 -d shop -v /var/lib/postgresql/backups/payments_recovered.dump

# 10. In-place recovery outline: stop, move aside, save pg_wal, restore, settings, lock out users, start
sudo systemctl stop postgresql@18-main
sudo -u postgres mv /var/lib/postgresql/18/main /var/lib/postgresql/18/main.damaged
sudo -u postgres /usr/lib/postgresql/18/bin/pg_controldata /var/lib/postgresql/18/main.damaged | grep "REDO WAL file"
sudo systemctl start postgresql@18-main
sudo -u postgres psql -c "SELECT timeline_id FROM pg_control_checkpoint();"

# 11. Clean up the lab cluster
sudo pg_dropcluster 18 pitr --stop
Point-in-time recovery commands in order

Summary and what's next

  • Point-in-time recovery = base backup + archived WAL + a recovery target
  • Find the exact commit time, xid or LSN of the mistake with pg_waldump on the archive
  • Recover into a separate cluster first: restore the backup, empty pg_wal, set restore_command and a target, create recovery.signal
  • Use recovery_target_inclusive = off to stop just before the bad transaction
  • Check the data while paused, then finish with pg_wal_replay_resume()
  • Copy only the lost objects back to production with pg_dump and pg_restore
  • For in-place recovery, keep the old data directory and unarchived WAL, and lock users out with pg_hba.conf
  • Every recovery starts a new timeline; take a fresh base backup afterwards
  • Create named restore points before risky changes

In Part 21 we move from hand-made scripts to production backups with pgBackRest.

PT Ganesh

An experienced PostgreSQL DBA/SQL developer with years of expertise in designing and implementing robust database solutions. Proficient in writing complex queries, developing stored procedures, and conducting performance tuning to deliver highly efficient data-driven applications that meet business requirements.

Home
SQL
PLSQL
Interview Q&A