codekingpro/portable-devtools
115k
1<?xml version="1.0" encoding="UTF-8" standalone="no"?>2<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>26.3. Continuous Archiving and Point-in-Time Recovery (PITR)</title><link rel="stylesheet" type="text/css" href="stylesheet.css" /><link rev="made" href="pgsql-docs@lists.postgresql.org" /><meta name="generator" content="DocBook XSL Stylesheets Vsnapshot" /><link rel="prev" href="backup-file.html" title="26.2. File System Level Backup" /><link rel="next" href="high-availability.html" title="Chapter 27. High Availability, Load Balancing, and Replication" /></head><body id="docContent" class="container-fluid col-10"><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="5" align="center">26.3. Continuous Archiving and Point-in-Time Recovery (PITR)</th></tr><tr><td width="10%" align="left"><a accesskey="p" href="backup-file.html" title="26.2. File System Level Backup">Prev</a> </td><td width="10%" align="left"><a accesskey="u" href="backup.html" title="Chapter 26. Backup and Restore">Up</a></td><th width="60%" align="center">Chapter 26. Backup and Restore</th><td width="10%" align="right"><a accesskey="h" href="index.html" title="PostgreSQL 16.3 Documentation">Home</a></td><td width="10%" align="right"> <a accesskey="n" href="high-availability.html" title="Chapter 27. High Availability, Load Balancing, and Replication">Next</a></td></tr></table><hr /></div><div class="sect1" id="CONTINUOUS-ARCHIVING"><div class="titlepage"><div><div><h2 class="title" style="clear: both">26.3. Continuous Archiving and Point-in-Time Recovery (PITR) <a href="#CONTINUOUS-ARCHIVING" class="id_link">#</a></h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="sect2"><a href="continuous-archiving.html#BACKUP-ARCHIVING-WAL">26.3.1. Setting Up WAL Archiving</a></span></dt><dt><span class="sect2"><a href="continuous-archiving.html#BACKUP-BASE-BACKUP">26.3.2. Making a Base Backup</a></span></dt><dt><span class="sect2"><a href="continuous-archiving.html#BACKUP-LOWLEVEL-BASE-BACKUP">26.3.3. Making a Base Backup Using the Low Level API</a></span></dt><dt><span class="sect2"><a href="continuous-archiving.html#BACKUP-PITR-RECOVERY">26.3.4. Recovering Using a Continuous Archive Backup</a></span></dt><dt><span class="sect2"><a href="continuous-archiving.html#BACKUP-TIMELINES">26.3.5. Timelines</a></span></dt><dt><span class="sect2"><a href="continuous-archiving.html#BACKUP-TIPS">26.3.6. Tips and Examples</a></span></dt><dt><span class="sect2"><a href="continuous-archiving.html#CONTINUOUS-ARCHIVING-CAVEATS">26.3.7. Caveats</a></span></dt></dl></div><a id="id-1.6.13.7.2" class="indexterm"></a><a id="id-1.6.13.7.3" class="indexterm"></a><a id="id-1.6.13.7.4" class="indexterm"></a><p>3 At all times, <span class="productname">PostgreSQL</span> maintains a4 <em class="firstterm">write ahead log</em> (WAL) in the <code class="filename">pg_wal/</code>5 subdirectory of the cluster's data directory. The log records6 every change made to the database's data files. This log exists7 primarily for crash-safety purposes: if the system crashes, the8 database can be restored to consistency by <span class="quote">“<span class="quote">replaying</span>”</span> the9 log entries made since the last checkpoint. However, the existence10 of the log makes it possible to use a third strategy for backing up11 databases: we can combine a file-system-level backup with backup of12 the WAL files. If recovery is needed, we restore the file system backup and13 then replay from the backed-up WAL files to bring the system to a14 current state. This approach is more complex to administer than15 either of the previous approaches, but it has some significant16 benefits:17 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>18 We do not need a perfectly consistent file system backup as the starting point.19 Any internal inconsistency in the backup will be corrected by log20 replay (this is not significantly different from what happens during21 crash recovery). So we do not need a file system snapshot capability,22 just <span class="application">tar</span> or a similar archiving tool.23 </p></li><li class="listitem"><p>24 Since we can combine an indefinitely long sequence of WAL files25 for replay, continuous backup can be achieved simply by continuing to archive26 the WAL files. This is particularly valuable for large databases, where27 it might not be convenient to take a full backup frequently.28 </p></li><li class="listitem"><p>29 It is not necessary to replay the WAL entries all the30 way to the end. We could stop the replay at any point and have a31 consistent snapshot of the database as it was at that time. Thus,32 this technique supports <em class="firstterm">point-in-time recovery</em>: it is33 possible to restore the database to its state at any time since your base34 backup was taken.35 </p></li><li class="listitem"><p>36 If we continuously feed the series of WAL files to another37 machine that has been loaded with the same base backup file, we38 have a <em class="firstterm">warm standby</em> system: at any point we can bring up39 the second machine and it will have a nearly-current copy of the40 database.41 </p></li></ul></div><p>42 </p><div class="note"><h3 class="title">Note</h3><p>43 <span class="application">pg_dump</span> and44 <span class="application">pg_dumpall</span> do not produce file-system-level45 backups and cannot be used as part of a continuous-archiving solution.46 Such dumps are <span class="emphasis"><em>logical</em></span> and do not contain enough47 information to be used by WAL replay.48 </p></div><p>49 As with the plain file-system-backup technique, this method can only50 support restoration of an entire database cluster, not a subset.51 Also, it requires a lot of archival storage: the base backup might be bulky,52 and a busy system will generate many megabytes of WAL traffic that53 have to be archived. Still, it is the preferred backup technique in54 many situations where high reliability is needed.55 </p><p>56 To recover successfully using continuous archiving (also called57 <span class="quote">“<span class="quote">online backup</span>”</span> by many database vendors), you need a continuous58 sequence of archived WAL files that extends back at least as far as the59 start time of your backup. So to get started, you should set up and test60 your procedure for archiving WAL files <span class="emphasis"><em>before</em></span> you take your61 first base backup. Accordingly, we first discuss the mechanics of62 archiving WAL files.63 </p><div class="sect2" id="BACKUP-ARCHIVING-WAL"><div class="titlepage"><div><div><h3 class="title">26.3.1. Setting Up WAL Archiving <a href="#BACKUP-ARCHIVING-WAL" class="id_link">#</a></h3></div></div></div><p>64 In an abstract sense, a running <span class="productname">PostgreSQL</span> system65 produces an indefinitely long sequence of WAL records. The system66 physically divides this sequence into WAL <em class="firstterm">segment67 files</em>, which are normally 16MB apiece (although the segment size68 can be altered during <span class="application">initdb</span>). The segment69 files are given numeric names that reflect their position in the70 abstract WAL sequence. When not using WAL archiving, the system71 normally creates just a few segment files and then72 <span class="quote">“<span class="quote">recycles</span>”</span> them by renaming no-longer-needed segment files73 to higher segment numbers. It's assumed that segment files whose74 contents precede the last checkpoint are no longer of75 interest and can be recycled.76 </p><p>77 When archiving WAL data, we need to capture the contents of each segment78 file once it is filled, and save that data somewhere before the segment79 file is recycled for reuse. Depending on the application and the80 available hardware, there could be many different ways of <span class="quote">“<span class="quote">saving81 the data somewhere</span>”</span>: we could copy the segment files to an NFS-mounted82 directory on another machine, write them onto a tape drive (ensuring that83 you have a way of identifying the original name of each file), or batch84 them together and burn them onto CDs, or something else entirely. To85 provide the database administrator with flexibility,86 <span class="productname">PostgreSQL</span> tries not to make any assumptions about how87 the archiving will be done. Instead, <span class="productname">PostgreSQL</span> lets88 the administrator specify a shell command or an archive library to be executed to copy a89 completed segment file to wherever it needs to go. This could be as simple90 as a shell command that uses <code class="literal">cp</code>, or it could invoke a91 complex C function — it's all up to you.92 </p><p>93 To enable WAL archiving, set the <a class="xref" href="runtime-config-wal.html#GUC-WAL-LEVEL">wal_level</a>94 configuration parameter to <code class="literal">replica</code> or higher,95 <a class="xref" href="runtime-config-wal.html#GUC-ARCHIVE-MODE">archive_mode</a> to <code class="literal">on</code>,96 specify the shell command to use in the <a class="xref" href="runtime-config-wal.html#GUC-ARCHIVE-COMMAND">archive_command</a> configuration parameter97 or specify the library to use in the <a class="xref" href="runtime-config-wal.html#GUC-ARCHIVE-LIBRARY">archive_library</a> configuration parameter. In practice98 these settings will always be placed in the99 <code class="filename">postgresql.conf</code> file.100 </p><p>101 In <code class="varname">archive_command</code>,102 <code class="literal">%p</code> is replaced by the path name of the file to103 archive, while <code class="literal">%f</code> is replaced by only the file name.104 (The path name is relative to the current working directory,105 i.e., the cluster's data directory.)106 Use <code class="literal">%%</code> if you need to embed an actual <code class="literal">%</code>107 character in the command. The simplest useful command is something108 like:109</p><pre class="programlisting">110archive_command = 'test ! -f /mnt/server/archivedir/%f && cp %p /mnt/server/archivedir/%f' # Unix111archive_command = 'copy "%p" "C:\\server\\archivedir\\%f"' # Windows112</pre><p>113 which will copy archivable WAL segments to the directory114 <code class="filename">/mnt/server/archivedir</code>. (This is an example, not a115 recommendation, and might not work on all platforms.) After the116 <code class="literal">%p</code> and <code class="literal">%f</code> parameters have been replaced,117 the actual command executed might look like this:118</p><pre class="programlisting">119test ! -f /mnt/server/archivedir/00000001000000A900000065 && cp pg_wal/00000001000000A900000065 /mnt/server/archivedir/00000001000000A900000065120</pre><p>121 A similar command will be generated for each new file to be archived.122 </p><p>123 The archive command will be executed under the ownership of the same124 user that the <span class="productname">PostgreSQL</span> server is running as. Since125 the series of WAL files being archived contains effectively everything126 in your database, you will want to be sure that the archived data is127 protected from prying eyes; for example, archive into a directory that128 does not have group or world read access.129 </p><p>130 It is important that the archive command return zero exit status if and131 only if it succeeds. Upon getting a zero result,132 <span class="productname">PostgreSQL</span> will assume that the file has been133 successfully archived, and will remove or recycle it. However, a nonzero134 status tells <span class="productname">PostgreSQL</span> that the file was not archived;135 it will try again periodically until it succeeds.136 </p><p>137 Another way to archive is to use a custom archive module as the138 <code class="varname">archive_library</code>. Since such modules are written in139 <code class="literal">C</code>, creating your own may require considerably more effort140 than writing a shell command. However, archive modules can be more141 performant than archiving via shell, and they will have access to many142 useful server resources. For more information about archive modules, see143 <a class="xref" href="archive-modules.html" title="Chapter 51. Archive Modules">Chapter 51</a>.144 </p><p>145 When the archive command is terminated by a signal (other than146 <span class="systemitem">SIGTERM</span> that is used as part of a server147 shutdown) or an error by the shell with an exit status greater than148 125 (such as command not found), or if the archive function emits an149 <code class="literal">ERROR</code> or <code class="literal">FATAL</code>, the archiver process150 aborts and gets restarted by the postmaster. In such cases, the failure is151 not reported in <a class="xref" href="monitoring-stats.html#PG-STAT-ARCHIVER-VIEW" title="Table 28.22. pg_stat_archiver View">pg_stat_archiver</a>.152 </p><p>153 Archive commands and libraries should generally be designed to refuse to overwrite154 any pre-existing archive file. This is an important safety feature to155 preserve the integrity of your archive in case of administrator error156 (such as sending the output of two different servers to the same archive157 directory). It is advisable to test your proposed archive library to ensure158 that it does not overwrite an existing file.159 </p><p>160 In rare cases, <span class="productname">PostgreSQL</span> may attempt to161 re-archive a WAL file that was previously archived. For example, if the162 system crashes before the server makes a durable record of archival163 success, the server will attempt to archive the file again after164 restarting (provided archiving is still enabled). When an archive command or library165 encounters a pre-existing file, it should return a zero status or <code class="literal">true</code>, respectively,166 if the WAL file has identical contents to the pre-existing archive and the167 pre-existing archive is fully persisted to storage. If a pre-existing168 file contains different contents than the WAL file being archived, the169 archive command or library <span class="emphasis"><em>must</em></span> return a nonzero status or170 <code class="literal">false</code>, respectively.171 </p><p>172 The example command above for Unix avoids overwriting a pre-existing archive173 by including a separate174 <code class="command">test</code> step. On some Unix platforms, <code class="command">cp</code> has175 switches such as <code class="option">-i</code> that can be used to do the same thing176 less verbosely, but you should not rely on these without verifying that177 the right exit status is returned. (In particular, GNU <code class="command">cp</code>178 will return status zero when <code class="option">-i</code> is used and the target file179 already exists, which is <span class="emphasis"><em>not</em></span> the desired behavior.)180 </p><p>181 While designing your archiving setup, consider what will happen if182 the archive command or library fails repeatedly because some aspect requires183 operator intervention or the archive runs out of space. For example, this184 could occur if you write to tape without an autochanger; when the tape185 fills, nothing further can be archived until the tape is swapped.186 You should ensure that any error condition or request to a human operator187 is reported appropriately so that the situation can be188 resolved reasonably quickly. The <code class="filename">pg_wal/</code> directory will189 continue to fill with WAL segment files until the situation is resolved.190 (If the file system containing <code class="filename">pg_wal/</code> fills up,191 <span class="productname">PostgreSQL</span> will do a PANIC shutdown. No committed192 transactions will be lost, but the database will remain offline until193 you free some space.)194 </p><p>195 The speed of the archive command or library is unimportant as long as it can keep up196 with the average rate at which your server generates WAL data. Normal197 operation continues even if the archiving process falls a little behind.198 If archiving falls significantly behind, this will increase the amount of199 data that would be lost in the event of a disaster. It will also mean that200 the <code class="filename">pg_wal/</code> directory will contain large numbers of201 not-yet-archived segment files, which could eventually exceed available202 disk space. You are advised to monitor the archiving process to ensure that203 it is working as you intend.204 </p><p>205 In writing your archive command or library, you should assume that the file names to206 be archived can be up to 64 characters long and can contain any207 combination of ASCII letters, digits, and dots. It is not necessary to208 preserve the original relative path (<code class="literal">%p</code>) but it is necessary to209 preserve the file name (<code class="literal">%f</code>).210 </p><p>211 Note that although WAL archiving will allow you to restore any212 modifications made to the data in your <span class="productname">PostgreSQL</span> database,213 it will not restore changes made to configuration files (that is,214 <code class="filename">postgresql.conf</code>, <code class="filename">pg_hba.conf</code> and215 <code class="filename">pg_ident.conf</code>), since those are edited manually rather216 than through SQL operations.217 You might wish to keep the configuration files in a location that will218 be backed up by your regular file system backup procedures. See219 <a class="xref" href="runtime-config-file-locations.html" title="20.2. File Locations">Section 20.2</a> for how to relocate the220 configuration files.221 </p><p>222 The archive command or function is only invoked on completed WAL segments. Hence,223 if your server generates only little WAL traffic (or has slack periods224 where it does so), there could be a long delay between the completion225 of a transaction and its safe recording in archive storage. To put226 a limit on how old unarchived data can be, you can set227 <a class="xref" href="runtime-config-wal.html#GUC-ARCHIVE-TIMEOUT">archive_timeout</a> to force the server to switch228 to a new WAL segment file at least that often. Note that archived229 files that are archived early due to a forced switch are still the same230 length as completely full files. It is therefore unwise to set a very231 short <code class="varname">archive_timeout</code> — it will bloat your archive232 storage. <code class="varname">archive_timeout</code> settings of a minute or so are233 usually reasonable.234 </p><p>235 Also, you can force a segment switch manually with236 <code class="function">pg_switch_wal</code> if you want to ensure that a237 just-finished transaction is archived as soon as possible. Other utility238 functions related to WAL management are listed in <a class="xref" href="functions-admin.html#FUNCTIONS-ADMIN-BACKUP-TABLE" title="Table 9.91. Backup Control Functions">Table 9.91</a>.239 </p><p>240 When <code class="varname">wal_level</code> is <code class="literal">minimal</code> some SQL commands241 are optimized to avoid WAL logging, as described in <a class="xref" href="populate.html#POPULATE-PITR" title="14.4.7. Disable WAL Archival and Streaming Replication">Section 14.4.7</a>. If archiving or streaming replication were242 turned on during execution of one of these statements, WAL would not243 contain enough information for archive recovery. (Crash recovery is244 unaffected.) For this reason, <code class="varname">wal_level</code> can only be changed at245 server start. However, <code class="varname">archive_command</code> and <code class="varname">archive_library</code> can be changed with a246 configuration file reload. If you are archiving via shell and wish to247 temporarily stop archiving,248 one way to do it is to set <code class="varname">archive_command</code> to the empty249 string (<code class="literal">''</code>).250 This will cause WAL files to accumulate in <code class="filename">pg_wal/</code> until a251 working <code class="varname">archive_command</code> is re-established.252 </p></div><div class="sect2" id="BACKUP-BASE-BACKUP"><div class="titlepage"><div><div><h3 class="title">26.3.2. Making a Base Backup <a href="#BACKUP-BASE-BACKUP" class="id_link">#</a></h3></div></div></div><p>253 The easiest way to perform a base backup is to use the254 <a class="xref" href="app-pgbasebackup.html" title="pg_basebackup"><span class="refentrytitle"><span class="application">pg_basebackup</span></span></a> tool. It can create255 a base backup either as regular files or as a tar archive. If more256 flexibility than <a class="xref" href="app-pgbasebackup.html" title="pg_basebackup"><span class="refentrytitle"><span class="application">pg_basebackup</span></span></a> can provide is257 required, you can also make a base backup using the low level API258 (see <a class="xref" href="continuous-archiving.html#BACKUP-LOWLEVEL-BASE-BACKUP" title="26.3.3. Making a Base Backup Using the Low Level API">Section 26.3.3</a>).259 </p><p>260 It is not necessary to be concerned about the amount of time it takes261 to make a base backup. However, if you normally run the262 server with <code class="varname">full_page_writes</code> disabled, you might notice a drop263 in performance while the backup runs since <code class="varname">full_page_writes</code> is264 effectively forced on during backup mode.265 </p><p>266 To make use of the backup, you will need to keep all the WAL267 segment files generated during and after the file system backup.268 To aid you in doing this, the base backup process269 creates a <em class="firstterm">backup history file</em> that is immediately270 stored into the WAL archive area. This file is named after the first271 WAL segment file that you need for the file system backup.272 For example, if the starting WAL file is273 <code class="literal">0000000100001234000055CD</code> the backup history file will be274 named something like275 <code class="literal">0000000100001234000055CD.007C9330.backup</code>. (The second276 part of the file name stands for an exact position within the WAL277 file, and can ordinarily be ignored.) Once you have safely archived278 the file system backup and the WAL segment files used during the279 backup (as specified in the backup history file), all archived WAL280 segments with names numerically less are no longer needed to recover281 the file system backup and can be deleted. However, you should282 consider keeping several backup sets to be absolutely certain that283 you can recover your data.284 </p><p>285 The backup history file is just a small text file. It contains the286 label string you gave to <a class="xref" href="app-pgbasebackup.html" title="pg_basebackup"><span class="refentrytitle"><span class="application">pg_basebackup</span></span></a>, as well as287 the starting and ending times and WAL segments of the backup.288 If you used the label to identify the associated dump file,289 then the archived history file is enough to tell you which dump file to290 restore.291 </p><p>292 Since you have to keep around all the archived WAL files back to your293 last base backup, the interval between base backups should usually be294 chosen based on how much storage you want to expend on archived WAL295 files. You should also consider how long you are prepared to spend296 recovering, if recovery should be necessary — the system will have to297 replay all those WAL segments, and that could take awhile if it has298 been a long time since the last base backup.299 </p></div><div class="sect2" id="BACKUP-LOWLEVEL-BASE-BACKUP"><div class="titlepage"><div><div><h3 class="title">26.3.3. Making a Base Backup Using the Low Level API <a href="#BACKUP-LOWLEVEL-BASE-BACKUP" class="id_link">#</a></h3></div></div></div><p>300 The procedure for making a base backup using the low level301 APIs contains a few more steps than302 the <a class="xref" href="app-pgbasebackup.html" title="pg_basebackup"><span class="refentrytitle"><span class="application">pg_basebackup</span></span></a> method, but is relatively303 simple. It is very important that these steps are executed in304 sequence, and that the success of a step is verified before305 proceeding to the next step.306 </p><p>307 Multiple backups are able to be run concurrently (both those308 started using this backup API and those started using309 <a class="xref" href="app-pgbasebackup.html" title="pg_basebackup"><span class="refentrytitle"><span class="application">pg_basebackup</span></span></a>).310 </p><p>311 </p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>312 Ensure that WAL archiving is enabled and working.313 </p></li><li class="listitem"><p>314 Connect to the server (it does not matter which database) as a user with315 rights to run <code class="function">pg_backup_start</code> (superuser,316 or a user who has been granted <code class="literal">EXECUTE</code> on the317 function) and issue the command:318</p><pre class="programlisting">319SELECT pg_backup_start(label => 'label', fast => false);320</pre><p>321 where <code class="literal">label</code> is any string you want to use to uniquely322 identify this backup operation. The connection323 calling <code class="function">pg_backup_start</code> must be maintained until the end of324 the backup, or the backup will be automatically aborted.325 </p><p>326 Online backups are always started at the beginning of a checkpoint.327 By default, <code class="function">pg_backup_start</code> will wait for the next328 regularly scheduled checkpoint to complete, which may take a long time (see the329 configuration parameters <a class="xref" href="runtime-config-wal.html#GUC-CHECKPOINT-TIMEOUT">checkpoint_timeout</a> and330 <a class="xref" href="runtime-config-wal.html#GUC-CHECKPOINT-COMPLETION-TARGET">checkpoint_completion_target</a>). This is331 usually preferable as it minimizes the impact on the running system. If you332 want to start the backup as soon as possible, pass <code class="literal">true</code> as333 the second parameter to <code class="function">pg_backup_start</code> and it will334 request an immediate checkpoint, which will finish as fast as possible using335 as much I/O as possible.336 </p></li><li class="listitem"><p>337 Perform the backup, using any convenient file-system-backup tool338 such as <span class="application">tar</span> or <span class="application">cpio</span> (not339 <span class="application">pg_dump</span> or340 <span class="application">pg_dumpall</span>). It is neither341 necessary nor desirable to stop normal operation of the database342 while you do this. See343 <a class="xref" href="continuous-archiving.html#BACKUP-LOWLEVEL-BASE-BACKUP-DATA" title="26.3.3.1. Backing Up the Data Directory">Section 26.3.3.1</a> for things to344 consider during this backup.345 </p></li><li class="listitem"><p>346 In the same connection as before, issue the command:347</p><pre class="programlisting">348SELECT * FROM pg_backup_stop(wait_for_archive => true);349</pre><p>350 This terminates backup mode. On a primary, it also performs an automatic351 switch to the next WAL segment. On a standby, it is not possible to352 automatically switch WAL segments, so you may wish to run353 <code class="function">pg_switch_wal</code> on the primary to perform a manual354 switch. The reason for the switch is to arrange for355 the last WAL segment file written during the backup interval to be356 ready to archive.357 </p><p>358 <code class="function">pg_backup_stop</code> will return one row with three359 values. The second of these fields should be written to a file named360 <code class="filename">backup_label</code> in the root directory of the backup. The361 third field should be written to a file named362 <code class="filename">tablespace_map</code> unless the field is empty. These files are363 vital to the backup working and must be written byte for byte without364 modification, which may require opening the file in binary mode.365 </p></li><li class="listitem"><p>366 Once the WAL segment files active during the backup are archived, you are367 done. The file identified by <code class="function">pg_backup_stop</code>'s first return368 value is the last segment that is required to form a complete set of369 backup files. On a primary, if <code class="varname">archive_mode</code> is enabled and the370 <code class="literal">wait_for_archive</code> parameter is <code class="literal">true</code>,371 <code class="function">pg_backup_stop</code> does not return until the last segment has372 been archived.373 On a standby, <code class="varname">archive_mode</code> must be <code class="literal">always</code> in order374 for <code class="function">pg_backup_stop</code> to wait.375 Archiving of these files happens automatically since you have376 already configured <code class="varname">archive_command</code> or <code class="varname">archive_library</code>.377 In most cases this happens quickly, but you are advised to monitor your378 archive system to ensure there are no delays.379 If the archive process has fallen behind because of failures of the380 archive command or library, it will keep retrying381 until the archive succeeds and the backup is complete.382 If you wish to place a time limit on the execution of383 <code class="function">pg_backup_stop</code>, set an appropriate384 <code class="varname">statement_timeout</code> value, but make note that if385 <code class="function">pg_backup_stop</code> terminates because of this your backup386 may not be valid.387 </p><p>388 If the backup process monitors and ensures that all WAL segment files389 required for the backup are successfully archived then the390 <code class="literal">wait_for_archive</code> parameter (which defaults to true) can be set391 to false to have392 <code class="function">pg_backup_stop</code> return as soon as the stop backup record is393 written to the WAL. By default, <code class="function">pg_backup_stop</code> will wait394 until all WAL has been archived, which can take some time. This option395 must be used with caution: if WAL archiving is not monitored correctly396 then the backup might not include all of the WAL files and will397 therefore be incomplete and not able to be restored.398 </p></li></ol></div><p>399 </p><div class="sect3" id="BACKUP-LOWLEVEL-BASE-BACKUP-DATA"><div class="titlepage"><div><div><h4 class="title">26.3.3.1. Backing Up the Data Directory <a href="#BACKUP-LOWLEVEL-BASE-BACKUP-DATA" class="id_link">#</a></h4></div></div></div><p>400 Some file system backup tools emit warnings or errors401 if the files they are trying to copy change while the copy proceeds.402 When taking a base backup of an active database, this situation is normal403 and not an error. However, you need to ensure that you can distinguish404 complaints of this sort from real errors. For example, some versions405 of <span class="application">rsync</span> return a separate exit code for406 <span class="quote">“<span class="quote">vanished source files</span>”</span>, and you can write a driver script to407 accept this exit code as a non-error case. Also, some versions of408 GNU <span class="application">tar</span> return an error code indistinguishable from409 a fatal error if a file was truncated while <span class="application">tar</span> was410 copying it. Fortunately, GNU <span class="application">tar</span> versions 1.16 and411 later exit with 1 if a file was changed during the backup,412 and 2 for other errors. With GNU <span class="application">tar</span> version 1.23 and413 later, you can use the warning options <code class="literal">--warning=no-file-changed414 --warning=no-file-removed</code> to hide the related warning messages.415 </p><p>416 Be certain that your backup includes all of the files under417 the database cluster directory (e.g., <code class="filename">/usr/local/pgsql/data</code>).418 If you are using tablespaces that do not reside underneath this directory,419 be careful to include them as well (and be sure that your backup420 archives symbolic links as links, otherwise the restore will corrupt421 your tablespaces).422 </p><p>423 You should, however, omit from the backup the files within the424 cluster's <code class="filename">pg_wal/</code> subdirectory. This425 slight adjustment is worthwhile because it reduces the risk426 of mistakes when restoring. This is easy to arrange if427 <code class="filename">pg_wal/</code> is a symbolic link pointing to someplace outside428 the cluster directory, which is a common setup anyway for performance429 reasons. You might also want to exclude <code class="filename">postmaster.pid</code>430 and <code class="filename">postmaster.opts</code>, which record information431 about the running <span class="application">postmaster</span>, not about the432 <span class="application">postmaster</span> which will eventually use this backup.433 (These files can confuse <span class="application">pg_ctl</span>.)434 </p><p>435 It is often a good idea to also omit from the backup the files436 within the cluster's <code class="filename">pg_replslot/</code> directory, so that437 replication slots that exist on the primary do not become part of the438 backup. Otherwise, the subsequent use of the backup to create a standby439 may result in indefinite retention of WAL files on the standby, and440 possibly bloat on the primary if hot standby feedback is enabled, because441 the clients that are using those replication slots will still be connecting442 to and updating the slots on the primary, not the standby. Even if the443 backup is only intended for use in creating a new primary, copying the444 replication slots isn't expected to be particularly useful, since the445 contents of those slots will likely be badly out of date by the time446 the new primary comes on line.447 </p><p>448 The contents of the directories <code class="filename">pg_dynshmem/</code>,449 <code class="filename">pg_notify/</code>, <code class="filename">pg_serial/</code>,450 <code class="filename">pg_snapshots/</code>, <code class="filename">pg_stat_tmp/</code>,451 and <code class="filename">pg_subtrans/</code> (but not the directories themselves) can be452 omitted from the backup as they will be initialized on postmaster startup.453 </p><p>454 Any file or directory beginning with <code class="filename">pgsql_tmp</code> can be455 omitted from the backup. These files are removed on postmaster start and456 the directories will be recreated as needed.457 </p><p>458 <code class="filename">pg_internal.init</code> files can be omitted from the459 backup whenever a file of that name is found. These files contain460 relation cache data that is always rebuilt when recovering.461 </p><p>462 The backup label463 file includes the label string you gave to <code class="function">pg_backup_start</code>,464 as well as the time at which <code class="function">pg_backup_start</code> was run, and465 the name of the starting WAL file. In case of confusion it is therefore466 possible to look inside a backup file and determine exactly which467 backup session the dump file came from. The tablespace map file includes468 the symbolic link names as they exist in the directory469 <code class="filename">pg_tblspc/</code> and the full path of each symbolic link.470 These files are not merely for your information; their presence and471 contents are critical to the proper operation of the system's recovery472 process.473 </p><p>474 It is also possible to make a backup while the server is475 stopped. In this case, you obviously cannot use476 <code class="function">pg_backup_start</code> or <code class="function">pg_backup_stop</code>, and477 you will therefore be left to your own devices to keep track of which478 backup is which and how far back the associated WAL files go.479 It is generally better to follow the continuous archiving procedure above.480 </p></div></div><div class="sect2" id="BACKUP-PITR-RECOVERY"><div class="titlepage"><div><div><h3 class="title">26.3.4. Recovering Using a Continuous Archive Backup <a href="#BACKUP-PITR-RECOVERY" class="id_link">#</a></h3></div></div></div><p>481 Okay, the worst has happened and you need to recover from your backup.482 Here is the procedure:483 </p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>484 Stop the server, if it's running.485 </p></li><li class="listitem"><p>486 If you have the space to do so,487 copy the whole cluster data directory and any tablespaces to a temporary488 location in case you need them later. Note that this precaution will489 require that you have enough free space on your system to hold two490 copies of your existing database. If you do not have enough space,491 you should at least save the contents of the cluster's <code class="filename">pg_wal</code>492 subdirectory, as it might contain WAL files which493 were not archived before the system went down.494 </p></li><li class="listitem"><p>495 Remove all existing files and subdirectories under the cluster data496 directory and under the root directories of any tablespaces you are using.497 </p></li><li class="listitem"><p>498 Restore the database files from your file system backup. Be sure that they499 are restored with the right ownership (the database system user, not500 <code class="literal">root</code>!) and with the right permissions. If you are using501 tablespaces,502 you should verify that the symbolic links in <code class="filename">pg_tblspc/</code>503 were correctly restored.504 </p></li><li class="listitem"><p>505 Remove any files present in <code class="filename">pg_wal/</code>; these came from the506 file system backup and are therefore probably obsolete rather than current.507 If you didn't archive <code class="filename">pg_wal/</code> at all, then recreate508 it with proper permissions,509 being careful to ensure that you re-establish it as a symbolic link510 if you had it set up that way before.511 </p></li><li class="listitem"><p>512 If you have unarchived WAL segment files that you saved in step 2,513 copy them into <code class="filename">pg_wal/</code>. (It is best to copy them,514 not move them, so you still have the unmodified files if a515 problem occurs and you have to start over.)516 </p></li><li class="listitem"><p>517 Set recovery configuration settings in518 <code class="filename">postgresql.conf</code> (see <a class="xref" href="runtime-config-wal.html#RUNTIME-CONFIG-WAL-ARCHIVE-RECOVERY" title="20.5.5. Archive Recovery">Section 20.5.5</a>) and create a file519 <code class="filename">recovery.signal</code> in the cluster520 data directory. You might521 also want to temporarily modify <code class="filename">pg_hba.conf</code> to prevent522 ordinary users from connecting until you are sure the recovery was successful.523 </p></li><li class="listitem"><p>524 Start the server. The server will go into recovery mode and525 proceed to read through the archived WAL files it needs. Should the526 recovery be terminated because of an external error, the server can527 simply be restarted and it will continue recovery. Upon completion528 of the recovery process, the server will remove529 <code class="filename">recovery.signal</code> (to prevent530 accidentally re-entering recovery mode later) and then531 commence normal database operations.532 </p></li><li class="listitem"><p>533 Inspect the contents of the database to ensure you have recovered to534 the desired state. If not, return to step 1. If all is well,535 allow your users to connect by restoring <code class="filename">pg_hba.conf</code> to normal.536 </p></li></ol></div><p>537 </p><p>538 The key part of all this is to set up a recovery configuration that539 describes how you want to recover and how far the recovery should540 run. The one thing that you absolutely must specify is the <code class="varname">restore_command</code>,541 which tells <span class="productname">PostgreSQL</span> how to retrieve archived542 WAL file segments. Like the <code class="varname">archive_command</code>, this is543 a shell command string. It can contain <code class="literal">%f</code>, which is544 replaced by the name of the desired WAL file, and <code class="literal">%p</code>,545 which is replaced by the path name to copy the WAL file to.546 (The path name is relative to the current working directory,547 i.e., the cluster's data directory.)548 Write <code class="literal">%%</code> if you need to embed an actual <code class="literal">%</code>549 character in the command. The simplest useful command is550 something like:551</p><pre class="programlisting">552restore_command = 'cp /mnt/server/archivedir/%f %p'553</pre><p>554 which will copy previously archived WAL segments from the directory555 <code class="filename">/mnt/server/archivedir</code>. Of course, you can use something556 much more complicated, perhaps even a shell script that requests the557 operator to mount an appropriate tape.558 </p><p>559 It is important that the command return nonzero exit status on failure.560 The command <span class="emphasis"><em>will</em></span> be called requesting files that are not561 present in the archive; it must return nonzero when so asked. This is not562 an error condition. An exception is that if the command was terminated by563 a signal (other than <span class="systemitem">SIGTERM</span>, which is used as564 part of a database server shutdown) or an error by the shell (such as565 command not found), then recovery will abort and the server will not start566 up.567 </p><p>568 Not all of the requested files will be WAL segment569 files; you should also expect requests for files with a suffix of570 <code class="literal">.history</code>. Also be aware that571 the base name of the <code class="literal">%p</code> path will be different from572 <code class="literal">%f</code>; do not expect them to be interchangeable.573 </p><p>574 WAL segments that cannot be found in the archive will be sought in575 <code class="filename">pg_wal/</code>; this allows use of recent un-archived segments.576 However, segments that are available from the archive will be used in577 preference to files in <code class="filename">pg_wal/</code>.578 </p><p>579 Normally, recovery will proceed through all available WAL segments,580 thereby restoring the database to the current point in time (or as581 close as possible given the available WAL segments). Therefore, a normal582 recovery will end with a <span class="quote">“<span class="quote">file not found</span>”</span> message, the exact text583 of the error message depending upon your choice of584 <code class="varname">restore_command</code>. You may also see an error message585 at the start of recovery for a file named something like586 <code class="filename">00000001.history</code>. This is also normal and does not587 indicate a problem in simple recovery situations; see588 <a class="xref" href="continuous-archiving.html#BACKUP-TIMELINES" title="26.3.5. Timelines">Section 26.3.5</a> for discussion.589 </p><p>590 If you want to recover to some previous point in time (say, right before591 the junior DBA dropped your main transaction table), just specify the592 required <a class="link" href="runtime-config-wal.html#RUNTIME-CONFIG-WAL-RECOVERY-TARGET" title="20.5.6. Recovery Target">stopping point</a>. You can specify593 the stop point, known as the <span class="quote">“<span class="quote">recovery target</span>”</span>, either by594 date/time, named restore point or by completion of a specific transaction595 ID. As of this writing only the date/time and named restore point options596 are very usable, since there are no tools to help you identify with any597 accuracy which transaction ID to use.598 </p><div class="note"><h3 class="title">Note</h3><p>599 The stop point must be after the ending time of the base backup, i.e.,600 the end time of <code class="function">pg_backup_stop</code>. You cannot use a base backup601 to recover to a time when that backup was in progress. (To602 recover to such a time, you must go back to your previous base backup603 and roll forward from there.)604 </p></div><p>605 If recovery finds corrupted WAL data, recovery will606 halt at that point and the server will not start. In such a case the607 recovery process could be re-run from the beginning, specifying a608 <span class="quote">“<span class="quote">recovery target</span>”</span> before the point of corruption so that recovery609 can complete normally.610 If recovery fails for an external reason, such as a system crash or611 if the WAL archive has become inaccessible, then the recovery can simply612 be restarted and it will restart almost from where it failed.613 Recovery restart works much like checkpointing in normal operation:614 the server periodically forces all its state to disk, and then updates615 the <code class="filename">pg_control</code> file to indicate that the already-processed616 WAL data need not be scanned again.617 </p></div><div class="sect2" id="BACKUP-TIMELINES"><div class="titlepage"><div><div><h3 class="title">26.3.5. Timelines <a href="#BACKUP-TIMELINES" class="id_link">#</a></h3></div></div></div><a id="id-1.6.13.7.13.2" class="indexterm"></a><p>618 The ability to restore the database to a previous point in time creates619 some complexities that are akin to science-fiction stories about time620 travel and parallel universes. For example, in the original history of the database,621 suppose you dropped a critical table at 5:15PM on Tuesday evening, but622 didn't realize your mistake until Wednesday noon.623 Unfazed, you get out your backup, restore to the point-in-time 5:14PM624 Tuesday evening, and are up and running. In <span class="emphasis"><em>this</em></span> history of625 the database universe, you never dropped the table. But suppose626 you later realize this wasn't such a great idea, and would like627 to return to sometime Wednesday morning in the original history.628 You won't be able629 to if, while your database was up-and-running, it overwrote some of the630 WAL segment files that led up to the time you now wish you631 could get back to. Thus, to avoid this, you need to distinguish the series of632 WAL records generated after you've done a point-in-time recovery from633 those that were generated in the original database history.634 </p><p>635 To deal with this problem, <span class="productname">PostgreSQL</span> has a notion636 of <em class="firstterm">timelines</em>. Whenever an archive recovery completes,637 a new timeline is created to identify the series of WAL records638 generated after that recovery. The timeline639 ID number is part of WAL segment file names so a new timeline does640 not overwrite the WAL data generated by previous timelines.641 For example, in the WAL file name642 <code class="filename">0000000100001234000055CD</code>, the leading643 <code class="literal">00000001</code> is the timeline ID in hexadecimal. (Note that644 in other contexts, such as server log messages, timeline IDs are645 usually printed in decimal.)646 </p><p>647 It is648 in fact possible to archive many different timelines. While that might649 seem like a useless feature, it's often a lifesaver. Consider the650 situation where you aren't quite sure what point-in-time to recover to,651 and so have to do several point-in-time recoveries by trial and error652 until you find the best place to branch off from the old history. Without653 timelines this process would soon generate an unmanageable mess. With654 timelines, you can recover to <span class="emphasis"><em>any</em></span> prior state, including655 states in timeline branches that you abandoned earlier.656 </p><p>657 Every time a new timeline is created, <span class="productname">PostgreSQL</span> creates658 a <span class="quote">“<span class="quote">timeline history</span>”</span> file that shows which timeline it branched659 off from and when. These history files are necessary to allow the system660 to pick the right WAL segment files when recovering from an archive that661 contains multiple timelines. Therefore, they are archived into the WAL662 archive area just like WAL segment files. The history files are just663 small text files, so it's cheap and appropriate to keep them around664 indefinitely (unlike the segment files which are large). You can, if665 you like, add comments to a history file to record your own notes about666 how and why this particular timeline was created. Such comments will be667 especially valuable when you have a thicket of different timelines as668 a result of experimentation.669 </p><p>670 The default behavior of recovery is to recover to the latest timeline found671 in the archive. If you wish to recover to the timeline that was current672 when the base backup was taken or into a specific child timeline (that673 is, you want to return to some state that was itself generated after a674 recovery attempt), you need to specify <code class="literal">current</code> or the675 target timeline ID in <a class="xref" href="runtime-config-wal.html#GUC-RECOVERY-TARGET-TIMELINE">recovery_target_timeline</a>. You676 cannot recover into timelines that branched off earlier than the base backup.677 </p></div><div class="sect2" id="BACKUP-TIPS"><div class="titlepage"><div><div><h3 class="title">26.3.6. Tips and Examples <a href="#BACKUP-TIPS" class="id_link">#</a></h3></div></div></div><p>678 Some tips for configuring continuous archiving are given here.679 </p><div class="sect3" id="BACKUP-STANDALONE"><div class="titlepage"><div><div><h4 class="title">26.3.6.1. Standalone Hot Backups <a href="#BACKUP-STANDALONE" class="id_link">#</a></h4></div></div></div><p>680 It is possible to use <span class="productname">PostgreSQL</span>'s backup facilities to681 produce standalone hot backups. These are backups that cannot be used682 for point-in-time recovery, yet are typically much faster to backup and683 restore than <span class="application">pg_dump</span> dumps. (They are also much larger684 than <span class="application">pg_dump</span> dumps, so in some cases the speed advantage685 might be negated.)686 </p><p>687 As with base backups, the easiest way to produce a standalone688 hot backup is to use the <a class="xref" href="app-pgbasebackup.html" title="pg_basebackup"><span class="refentrytitle"><span class="application">pg_basebackup</span></span></a>689 tool. If you include the <code class="literal">-X</code> parameter when calling690 it, all the write-ahead log required to use the backup will be691 included in the backup automatically, and no special action is692 required to restore the backup.693 </p></div><div class="sect3" id="COMPRESSED-ARCHIVE-LOGS"><div class="titlepage"><div><div><h4 class="title">26.3.6.2. Compressed Archive Logs <a href="#COMPRESSED-ARCHIVE-LOGS" class="id_link">#</a></h4></div></div></div><p>694 If archive storage size is a concern, you can use695 <span class="application">gzip</span> to compress the archive files:696</p><pre class="programlisting">697archive_command = 'gzip < %p > /mnt/server/archivedir/%f.gz'698</pre><p>699 You will then need to use <span class="application">gunzip</span> during recovery:700</p><pre class="programlisting">701restore_command = 'gunzip < /mnt/server/archivedir/%f.gz > %p'702</pre><p>703 </p></div><div class="sect3" id="BACKUP-SCRIPTS"><div class="titlepage"><div><div><h4 class="title">26.3.6.3. <code class="varname">archive_command</code> Scripts <a href="#BACKUP-SCRIPTS" class="id_link">#</a></h4></div></div></div><p>704 Many people choose to use scripts to define their705 <code class="varname">archive_command</code>, so that their706 <code class="filename">postgresql.conf</code> entry looks very simple:707</p><pre class="programlisting">708archive_command = 'local_backup_script.sh "%p" "%f"'709</pre><p>710 Using a separate script file is advisable any time you want to use711 more than a single command in the archiving process.712 This allows all complexity to be managed within the script, which713 can be written in a popular scripting language such as714 <span class="application">bash</span> or <span class="application">perl</span>.715 </p><p>716 Examples of requirements that might be solved within a script include:717 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>718 Copying data to secure off-site data storage719 </p></li><li class="listitem"><p>720 Batching WAL files so that they are transferred every three hours,721 rather than one at a time722 </p></li><li class="listitem"><p>723 Interfacing with other backup and recovery software724 </p></li><li class="listitem"><p>725 Interfacing with monitoring software to report errors726 </p></li></ul></div><p>727 </p><div class="tip"><h3 class="title">Tip</h3><p>728 When using an <code class="varname">archive_command</code> script, it's desirable729 to enable <a class="xref" href="runtime-config-logging.html#GUC-LOGGING-COLLECTOR">logging_collector</a>.730 Any messages written to <span class="systemitem">stderr</span> from the script will then731 appear in the database server log, allowing complex configurations to732 be diagnosed easily if they fail.733 </p></div></div></div><div class="sect2" id="CONTINUOUS-ARCHIVING-CAVEATS"><div class="titlepage"><div><div><h3 class="title">26.3.7. Caveats <a href="#CONTINUOUS-ARCHIVING-CAVEATS" class="id_link">#</a></h3></div></div></div><p>734 At this writing, there are several limitations of the continuous archiving735 technique. These will probably be fixed in future releases:736 737 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>738 If a <a class="link" href="sql-createdatabase.html" title="CREATE DATABASE"><code class="command">CREATE DATABASE</code></a>739 command is executed while a base backup is being taken, and then740 the template database that the <code class="command">CREATE DATABASE</code> copied741 is modified while the base backup is still in progress, it is742 possible that recovery will cause those modifications to be743 propagated into the created database as well. This is of course744 undesirable. To avoid this risk, it is best not to modify any745 template databases while taking a base backup.746 </p></li><li class="listitem"><p>747 <a class="link" href="sql-createtablespace.html" title="CREATE TABLESPACE"><code class="command">CREATE TABLESPACE</code></a>748 commands are WAL-logged with the literal absolute path, and will749 therefore be replayed as tablespace creations with the same750 absolute path. This might be undesirable if the WAL is being751 replayed on a different machine. It can be dangerous even if the752 WAL is being replayed on the same machine, but into a new data753 directory: the replay will still overwrite the contents of the754 original tablespace. To avoid potential gotchas of this sort,755 the best practice is to take a new base backup after creating or756 dropping tablespaces.757 </p></li></ul></div><p>758 </p><p>759 It should also be noted that the default <acronym class="acronym">WAL</acronym>760 format is fairly bulky since it includes many disk page snapshots.761 These page snapshots are designed to support crash recovery, since762 we might need to fix partially-written disk pages. Depending on763 your system hardware and software, the risk of partial writes might764 be small enough to ignore, in which case you can significantly765 reduce the total volume of archived WAL files by turning off page766 snapshots using the <a class="xref" href="runtime-config-wal.html#GUC-FULL-PAGE-WRITES">full_page_writes</a>767 parameter. (Read the notes and warnings in <a class="xref" href="wal.html" title="Chapter 30. Reliability and the Write-Ahead Log">Chapter 30</a>768 before you do so.) Turning off page snapshots does not prevent769 use of the WAL for PITR operations. An area for future770 development is to compress archived WAL data by removing771 unnecessary page copies even when <code class="varname">full_page_writes</code> is772 on. In the meantime, administrators might wish to reduce the number773 of page snapshots included in WAL by increasing the checkpoint774 interval parameters as much as feasible.775 </p></div></div><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="backup-file.html" title="26.2. File System Level Backup">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="backup.html" title="Chapter 26. Backup and Restore">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="high-availability.html" title="Chapter 27. High Availability, Load Balancing, and Replication">Next</a></td></tr><tr><td width="40%" align="left" valign="top">26.2. File System Level Backup </td><td width="20%" align="center"><a accesskey="h" href="index.html" title="PostgreSQL 16.3 Documentation">Home</a></td><td width="40%" align="right" valign="top"> Chapter 27. High Availability, Load Balancing, and Replication</td></tr></table></div></body></html>