]> begriffs open source - ai-pg/blob - full-docs/src/sgml/html/continuous-archiving.html
PG 18 docs from https://ftp.postgresql.org/pub/source/v18.0/postgresql-18.0-docs...
[ai-pg] / full-docs / src / sgml / html / continuous-archiving.html
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>25.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="25.2. File System Level Backup" /><link rel="next" href="high-availability.html" title="Chapter 26. 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">25.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="25.2. File System Level Backup">Prev</a> </td><td width="10%" align="left"><a accesskey="u" href="backup.html" title="Chapter 25. Backup and Restore">Up</a></td><th width="60%" align="center">Chapter 25. Backup and Restore</th><td width="10%" align="right"><a accesskey="h" href="index.html" title="PostgreSQL 18.0 Documentation">Home</a></td><td width="10%" align="right"> <a accesskey="n" href="high-availability.html" title="Chapter 26. 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">25.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">25.3.1. Setting Up WAL Archiving</a></span></dt><dt><span class="sect2"><a href="continuous-archiving.html#BACKUP-BASE-BACKUP">25.3.2. Making a Base Backup</a></span></dt><dt><span class="sect2"><a href="continuous-archiving.html#BACKUP-INCREMENTAL-BACKUP">25.3.3. Making an Incremental Backup</a></span></dt><dt><span class="sect2"><a href="continuous-archiving.html#BACKUP-LOWLEVEL-BASE-BACKUP">25.3.4. Making a Base Backup Using the Low Level API</a></span></dt><dt><span class="sect2"><a href="continuous-archiving.html#BACKUP-PITR-RECOVERY">25.3.5. Recovering Using a Continuous Archive Backup</a></span></dt><dt><span class="sect2"><a href="continuous-archiving.html#BACKUP-TIMELINES">25.3.6. Timelines</a></span></dt><dt><span class="sect2"><a href="continuous-archiving.html#BACKUP-TIPS">25.3.7. Tips and Examples</a></span></dt><dt><span class="sect2"><a href="continuous-archiving.html#CONTINUOUS-ARCHIVING-CAVEATS">25.3.8. Caveats</a></span></dt></dl></div><a id="id-1.6.12.7.2" class="indexterm"></a><a id="id-1.6.12.7.3" class="indexterm"></a><a id="id-1.6.12.7.4" class="indexterm"></a><p>
3    At all times, <span class="productname">PostgreSQL</span> maintains a
4    <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 records
6    every change made to the database's data files.  This log exists
7    primarily for crash-safety purposes: if the system crashes, the
8    database can be restored to consistency by <span class="quote">“<span class="quote">replaying</span>”</span> the
9    log entries made since the last checkpoint.  However, the existence
10    of the log makes it possible to use a third strategy for backing up
11    databases: we can combine a file-system-level backup with backup of
12    the WAL files.  If recovery is needed, we restore the file system backup and
13    then replay from the backed-up WAL files to bring the system to a
14    current state.  This approach is more complex to administer than
15    either of the previous approaches, but it has some significant
16    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 log
20      replay (this is not significantly different from what happens during
21      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 files
25      for replay, continuous backup can be achieved simply by continuing to archive
26      the WAL files.  This is particularly valuable for large databases, where
27      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 the
30      way to the end.  We could stop the replay at any point and have a
31      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 is
33      possible to restore the database to its state at any time since your base
34      backup was taken.
35     </p></li><li class="listitem"><p>
36      If we continuously feed the series of WAL files to another
37      machine that has been loaded with the same base backup file, we
38      have a <em class="firstterm">warm standby</em> system: at any point we can bring up
39      the second machine and it will have a nearly-current copy of the
40      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> and
44     <span class="application">pg_dumpall</span> do not produce file-system-level
45     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 enough
47     information to be used by WAL replay.
48    </p></div><p>
49    As with the plain file-system-backup technique, this method can only
50    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 that
53    have to be archived.  Still, it is the preferred backup technique in
54    many situations where high reliability is needed.
55   </p><p>
56    To recover successfully using continuous archiving (also called
57    <span class="quote">“<span class="quote">online backup</span>”</span> by many database vendors), you need a continuous
58    sequence of archived WAL files that extends back at least as far as the
59    start time of your backup.  So to get started, you should set up and test
60    your procedure for archiving WAL files <span class="emphasis"><em>before</em></span> you take your
61    first base backup.  Accordingly, we first discuss the mechanics of
62    archiving WAL files.
63   </p><div class="sect2" id="BACKUP-ARCHIVING-WAL"><div class="titlepage"><div><div><h3 class="title">25.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> system
65     produces an indefinitely long sequence of WAL records.  The system
66     physically divides this sequence into WAL <em class="firstterm">segment
67     files</em>, which are normally 16MB apiece (although the segment size
68     can be altered during <span class="application">initdb</span>).  The segment
69     files are given numeric names that reflect their position in the
70     abstract WAL sequence.  When not using WAL archiving, the system
71     normally creates just a few segment files and then
72     <span class="quote">“<span class="quote">recycles</span>”</span> them by renaming no-longer-needed segment files
73     to higher segment numbers.  It's assumed that segment files whose
74     contents precede the last checkpoint are no longer of
75     interest and can be recycled.
76    </p><p>
77     When archiving WAL data, we need to capture the contents of each segment
78     file once it is filled, and save that data somewhere before the segment
79     file is recycled for reuse.  Depending on the application and the
80     available hardware, there could be many different ways of <span class="quote">“<span class="quote">saving
81     the data somewhere</span>”</span>: we could copy the segment files to an NFS-mounted
82     directory on another machine, write them onto a tape drive (ensuring that
83     you have a way of identifying the original name of each file), or batch
84     them together and burn them onto CDs, or something else entirely.  To
85     provide the database administrator with flexibility,
86     <span class="productname">PostgreSQL</span> tries not to make any assumptions about how
87     the archiving will be done.  Instead, <span class="productname">PostgreSQL</span> lets
88     the administrator specify a shell command or an archive library to be executed to copy a
89     completed segment file to wherever it needs to go.  This could be as simple
90     as a shell command that uses <code class="literal">cp</code>, or it could invoke a
91     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 parameter
97     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 practice
98     these settings will always be placed in the
99     <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 to
103     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 something
108     like:
109 </p><pre class="programlisting">
110 archive_command = 'test ! -f /mnt/server/archivedir/%f &amp;&amp; cp %p /mnt/server/archivedir/%f'  # Unix
111 archive_command = 'copy "%p" "C:\\server\\archivedir\\%f"'  # Windows
112 </pre><p>
113     which will copy archivable WAL segments to the directory
114     <code class="filename">/mnt/server/archivedir</code>.  (This is an example, not a
115     recommendation, and might not work on all platforms.)  After the
116     <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">
119 test ! -f /mnt/server/archivedir/00000001000000A900000065 &amp;&amp; cp pg_wal/00000001000000A900000065 /mnt/server/archivedir/00000001000000A900000065
120 </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 same
124     user that the <span class="productname">PostgreSQL</span> server is running as.  Since
125     the series of WAL files being archived contains effectively everything
126     in your database, you will want to be sure that the archived data is
127     protected from prying eyes; for example, archive into a directory that
128     does not have group or world read access.
129    </p><p>
130     It is important that the archive command return zero exit status if and
131     only if it succeeds.  Upon getting a zero result,
132     <span class="productname">PostgreSQL</span> will assume that the file has been
133     successfully archived, and will remove or recycle it.  However, a nonzero
134     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 the
138     <code class="varname">archive_library</code>.  Since such modules are written in
139     <code class="literal">C</code>, creating your own may require considerably more effort
140     than writing a shell command.  However, archive modules can be more
141     performant than archiving via shell, and they will have access to many
142     useful server resources.  For more information about archive modules, see
143     <a class="xref" href="archive-modules.html" title="Chapter 49. Archive Modules">Chapter 49</a>.
144    </p><p>
145     When the archive command is terminated by a signal (other than
146     <span class="systemitem">SIGTERM</span> that is used as part of a server
147     shutdown) or an error by the shell with an exit status greater than
148     125 (such as command not found), or if the archive function emits an
149     <code class="literal">ERROR</code> or <code class="literal">FATAL</code>, the archiver process
150     aborts and gets restarted by the postmaster. In such cases, the failure is
151     not reported in <a class="xref" href="monitoring-stats.html#PG-STAT-ARCHIVER-VIEW" title="Table 27.22. pg_stat_archiver View">pg_stat_archiver</a>.
152    </p><p>
153     Archive commands and libraries should generally be designed to refuse to overwrite
154     any pre-existing archive file.  This is an important safety feature to
155     preserve the integrity of your archive in case of administrator error
156     (such as sending the output of two different servers to the same archive
157     directory).  It is advisable to test your proposed archive library to ensure
158     that it does not overwrite an existing file.
159    </p><p>
160     In rare cases, <span class="productname">PostgreSQL</span> may attempt to
161     re-archive a WAL file that was previously archived.  For example, if the
162     system crashes before the server makes a durable record of archival
163     success, the server will attempt to archive the file again after
164     restarting (provided archiving is still enabled).  When an archive command or library
165     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 the
167     pre-existing archive is fully persisted to storage.  If a pre-existing
168     file contains different contents than the WAL file being archived, the
169     archive command or library <span class="emphasis"><em>must</em></span> return a nonzero status or
170     <code class="literal">false</code>, respectively.
171    </p><p>
172     The example command above for Unix avoids overwriting a pre-existing archive
173     by including a separate
174     <code class="command">test</code> step.  On some Unix platforms, <code class="command">cp</code> has
175     switches such as <code class="option">-i</code> that can be used to do the same thing
176     less verbosely, but you should not rely on these without verifying that
177     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 file
179     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 if
182     the archive command or library fails repeatedly because some aspect requires
183     operator intervention or the archive runs out of space. For example, this
184     could occur if you write to tape without an autochanger; when the tape
185     fills, nothing further can be archived until the tape is swapped.
186     You should ensure that any error condition or request to a human operator
187     is reported appropriately so that the situation can be
188     resolved reasonably quickly. The <code class="filename">pg_wal/</code> directory will
189     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 committed
192     transactions will be lost, but the database will remain offline until
193     you free some space.)
194    </p><p>
195     The speed of the archive command or library is unimportant as long as it can keep up
196     with the average rate at which your server generates WAL data.  Normal
197     operation continues even if the archiving process falls a little behind.
198     If archiving falls significantly behind, this will increase the amount of
199     data that would be lost in the event of a disaster. It will also mean that
200     the <code class="filename">pg_wal/</code> directory will contain large numbers of
201     not-yet-archived segment files, which could eventually exceed available
202     disk space. You are advised to monitor the archiving process to ensure that
203     it is working as you intend.
204    </p><p>
205     In writing your archive command or library, you should assume that the file names to
206     be archived can be up to 64 characters long and can contain any
207     combination of ASCII letters, digits, and dots.  It is not necessary to
208     preserve the original relative path (<code class="literal">%p</code>) but it is necessary to
209     preserve the file name (<code class="literal">%f</code>).
210    </p><p>
211     Note that although WAL archiving will allow you to restore any
212     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> and
215     <code class="filename">pg_ident.conf</code>), since those are edited manually rather
216     than through SQL operations.
217     You might wish to keep the configuration files in a location that will
218     be backed up by your regular file system backup procedures.  See
219     <a class="xref" href="runtime-config-file-locations.html" title="19.2. File Locations">Section 19.2</a> for how to relocate the
220     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 periods
224     where it does so), there could be a long delay between the completion
225     of a transaction and its safe recording in archive storage.  To put
226     a limit on how old unarchived data can be, you can set
227     <a class="xref" href="runtime-config-wal.html#GUC-ARCHIVE-TIMEOUT">archive_timeout</a> to force the server to switch
228     to a new WAL segment file at least that often.  Note that archived
229     files that are archived early due to a forced switch are still the same
230     length as completely full files.  It is therefore unwise to set a very
231     short <code class="varname">archive_timeout</code> — it will bloat your archive
232     storage.  <code class="varname">archive_timeout</code> settings of a minute or so are
233     usually reasonable.
234    </p><p>
235     Also, you can force a segment switch manually with
236     <code class="function">pg_switch_wal</code> if you want to ensure that a
237     just-finished transaction is archived as soon as possible.  Other utility
238     functions related to WAL management are listed in <a class="xref" href="functions-admin.html#FUNCTIONS-ADMIN-BACKUP-TABLE" title="Table 9.97. Backup Control Functions">Table 9.97</a>.
239    </p><p>
240     When <code class="varname">wal_level</code> is <code class="literal">minimal</code> some SQL commands
241     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 were
242     turned on during execution of one of these statements, WAL would not
243     contain enough information for archive recovery.  (Crash recovery is
244     unaffected.)  For this reason, <code class="varname">wal_level</code> can only be changed at
245     server start.  However, <code class="varname">archive_command</code> and <code class="varname">archive_library</code> can be changed with a
246     configuration file reload.  If you are archiving via shell and wish to
247     temporarily stop archiving,
248     one way to do it is to set <code class="varname">archive_command</code> to the empty
249     string (<code class="literal">''</code>).
250     This will cause WAL files to accumulate in <code class="filename">pg_wal/</code> until a
251     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">25.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 the
254     <a class="xref" href="app-pgbasebackup.html" title="pg_basebackup"><span class="refentrytitle"><span class="application">pg_basebackup</span></span></a> tool. It can create
255     a base backup either as regular files or as a tar archive. If more
256     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 is
257     required, you can also make a base backup using the low level API
258     (see <a class="xref" href="continuous-archiving.html#BACKUP-LOWLEVEL-BASE-BACKUP" title="25.3.4. Making a Base Backup Using the Low Level API">Section 25.3.4</a>).
259    </p><p>
260     It is not necessary to be concerned about the amount of time it takes
261     to make a base backup. However, if you normally run the
262     server with <code class="varname">full_page_writes</code> disabled, you might notice a drop
263     in performance while the backup runs since <code class="varname">full_page_writes</code> is
264     effectively forced on during backup mode.
265    </p><p>
266     To make use of the backup, you will need to keep all the WAL
267     segment files generated during and after the file system backup.
268     To aid you in doing this, the base backup process
269     creates a <em class="firstterm">backup history file</em> that is immediately
270     stored into the WAL archive area. This file is named after the first
271     WAL segment file that you need for the file system backup.
272     For example, if the starting WAL file is
273     <code class="literal">0000000100001234000055CD</code> the backup history file will be
274     named something like
275     <code class="literal">0000000100001234000055CD.007C9330.backup</code>. (The second
276     part of the file name stands for an exact position within the WAL
277     file, and can ordinarily be ignored.) Once you have safely archived
278     the file system backup and the WAL segment files used during the
279     backup (as specified in the backup history file), all archived WAL
280     segments with names numerically less are no longer needed to recover
281     the file system backup and can be deleted. However, you should
282     consider keeping several backup sets to be absolutely certain that
283     you can recover your data.
284    </p><p>
285     The backup history file is just a small text file. It contains the
286     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 as
287     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 to
290     restore.
291    </p><p>
292     Since you have to keep around all the archived WAL files back to your
293     last base backup, the interval between base backups should usually be
294     chosen based on how much storage you want to expend on archived WAL
295     files.  You should also consider how long you are prepared to spend
296     recovering, if recovery should be necessary — the system will have to
297     replay all those WAL segments, and that could take awhile if it has
298     been a long time since the last base backup.
299    </p></div><div class="sect2" id="BACKUP-INCREMENTAL-BACKUP"><div class="titlepage"><div><div><h3 class="title">25.3.3. Making an Incremental Backup <a href="#BACKUP-INCREMENTAL-BACKUP" class="id_link">#</a></h3></div></div></div><p>
300     You can use <a class="xref" href="app-pgbasebackup.html" title="pg_basebackup"><span class="refentrytitle"><span class="application">pg_basebackup</span></span></a> to take an incremental
301     backup by specifying the <code class="literal">--incremental</code> option. You must
302     supply, as an argument to <code class="literal">--incremental</code>, the backup
303     manifest to an earlier backup from the same server. In the resulting
304     backup, non-relation files will be included in their entirety, but some
305     relation files may be replaced by smaller incremental files which contain
306     only the blocks which have been changed since the earlier backup and enough
307     metadata to reconstruct the current version of the file.
308    </p><p>
309     To figure out which blocks need to be backed up, the server uses WAL
310     summaries, which are stored in the data directory, inside the directory
311     <code class="literal">pg_wal/summaries</code>. If the required summary files are not
312     present, an attempt to take an incremental backup will fail. The summaries
313     present in this directory must cover all LSNs from the start LSN of the
314     prior backup to the start LSN of the current backup. Since the server looks
315     for WAL summaries just after establishing the start LSN of the current
316     backup, the necessary summary files probably won't be instantly present
317     on disk, but the server will wait for any missing files to show up.
318     This also helps if the WAL summarization process has fallen behind.
319     However, if the necessary files have already been removed, or if the WAL
320     summarizer doesn't catch up quickly enough, the incremental backup will
321     fail.
322    </p><p>
323     When restoring an incremental backup, it will be necessary to have not
324     only the incremental backup itself but also all earlier backups that
325     are required to supply the blocks omitted from the incremental backup.
326     See <a class="xref" href="app-pgcombinebackup.html" title="pg_combinebackup"><span class="refentrytitle"><span class="application">pg_combinebackup</span></span></a> for further information about
327     this requirement. Note that there are restrictions on the use of
328     <code class="literal">pg_combinebackup</code> when the checksum status of the
329     cluster has been changed; see
330     <a class="link" href="app-pgcombinebackup.html#APP-PGCOMBINEBACKUP-LIMITATIONS" title="Limitations">pg_combinebackup
331     limitations</a>.
332    </p><p>
333     Note that all of the requirements for making use of a full backup also
334     apply to an incremental backup. For instance, you still need all of the
335     WAL segment files generated during and after the file system backup, and
336     any relevant WAL history files. And you still need to create a
337     <code class="literal">recovery.signal</code> (or <code class="literal">standby.signal</code>)
338     and perform recovery, as described in
339     <a class="xref" href="continuous-archiving.html#BACKUP-PITR-RECOVERY" title="25.3.5. Recovering Using a Continuous Archive Backup">Section 25.3.5</a>. The requirement to have earlier
340     backups available at restore time and to use
341     <code class="literal">pg_combinebackup</code> is an additional requirement on top of
342     everything else. Keep in mind that <span class="application">PostgreSQL</span>
343     has no built-in mechanism to figure out which backups are still needed as
344     a basis for restoring later incremental backups. You must keep track of
345     the relationships between your full and incremental backups on your own,
346     and be certain not to remove earlier backups if they might be needed when
347     restoring later incremental backups.
348    </p><p>
349     Incremental backups typically only make sense for relatively large
350     databases where a significant portion of the data does not change, or only
351     changes slowly. For a small database, it's simpler to ignore the existence
352     of incremental backups and simply take full backups, which are simpler
353     to manage. For a large database all of which is heavily modified,
354     incremental backups won't be much smaller than full backups.
355    </p><p>
356     An incremental backup is only possible if replay would begin from a later
357     checkpoint than for the previous backup upon which it depends.  If you
358     take the incremental backup on the primary, this condition is always
359     satisfied, because each backup triggers a new checkpoint.  On a standby,
360     replay begins from the most recent restartpoint.  Therefore, an
361     incremental backup of a standby server can fail if there has been very
362     little activity since the previous backup, since no new restartpoint might
363     have been created.
364    </p></div><div class="sect2" id="BACKUP-LOWLEVEL-BASE-BACKUP"><div class="titlepage"><div><div><h3 class="title">25.3.4. Making a Base Backup Using the Low Level API <a href="#BACKUP-LOWLEVEL-BASE-BACKUP" class="id_link">#</a></h3></div></div></div><p>
365     Instead of taking a full or incremental base backup using
366     <a class="xref" href="app-pgbasebackup.html" title="pg_basebackup"><span class="refentrytitle"><span class="application">pg_basebackup</span></span></a>, you can take a base backup using the
367     low-level API. This procedure contains a few more steps than
368     the <span class="application">pg_basebackup</span> method, but is relatively
369     simple. It is very important that these steps are executed in
370     sequence, and that the success of a step is verified before
371     proceeding to the next step.
372    </p><p>
373      Multiple backups are able to be run concurrently (both those
374      started using this backup API and those started using
375      <a class="xref" href="app-pgbasebackup.html" title="pg_basebackup"><span class="refentrytitle"><span class="application">pg_basebackup</span></span></a>).
376     </p><p>
377   </p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>
378      Ensure that WAL archiving is enabled and working.
379     </p></li><li class="listitem"><p>
380      Connect to the server (it does not matter which database) as a user with
381      rights to run <code class="function">pg_backup_start</code> (superuser,
382      or a user who has been granted <code class="literal">EXECUTE</code> on the
383      function) and issue the command:
384 </p><pre class="programlisting">
385 SELECT pg_backup_start(label =&gt; 'label', fast =&gt; false);
386 </pre><p>
387      where <code class="literal">label</code> is any string you want to use to uniquely
388      identify this backup operation. The connection
389      calling <code class="function">pg_backup_start</code> must be maintained until the end of
390      the backup, or the backup will be automatically aborted.
391     </p><p>
392      Online backups are always started at the beginning of a checkpoint.
393      By default, <code class="function">pg_backup_start</code> will wait for the next
394      regularly scheduled checkpoint to complete, which may take a long time (see the
395      configuration parameters <a class="xref" href="runtime-config-wal.html#GUC-CHECKPOINT-TIMEOUT">checkpoint_timeout</a> and
396      <a class="xref" href="runtime-config-wal.html#GUC-CHECKPOINT-COMPLETION-TARGET">checkpoint_completion_target</a>).  This is
397      usually preferable as it minimizes the impact on the running system.  If you
398      want to start the backup as soon as possible, pass <code class="literal">true</code> as
399      the second parameter to <code class="function">pg_backup_start</code> and it will
400      request an immediate checkpoint, which will finish as fast as possible using
401      as much I/O as possible.
402     </p></li><li class="listitem"><p>
403      Perform the backup, using any convenient file-system-backup tool
404      such as <span class="application">tar</span> or <span class="application">cpio</span> (not
405      <span class="application">pg_dump</span> or
406      <span class="application">pg_dumpall</span>).  It is neither
407      necessary nor desirable to stop normal operation of the database
408      while you do this. See
409      <a class="xref" href="continuous-archiving.html#BACKUP-LOWLEVEL-BASE-BACKUP-DATA" title="25.3.4.1. Backing Up the Data Directory">Section 25.3.4.1</a> for things to
410      consider during this backup.
411     </p></li><li class="listitem"><p>
412      In the same connection as before, issue the command:
413 </p><pre class="programlisting">
414 SELECT * FROM pg_backup_stop(wait_for_archive =&gt; true);
415 </pre><p>
416      This terminates backup mode. On a primary, it also performs an automatic
417      switch to the next WAL segment.  On a standby, it is not possible to
418      automatically switch WAL segments, so you may wish to run
419      <code class="function">pg_switch_wal</code> on the primary to perform a manual
420      switch. The reason for the switch is to arrange for
421      the last WAL segment file written during the backup interval to be
422      ready to archive.
423     </p><p>
424      <code class="function">pg_backup_stop</code> will return one row with three
425      values. The second of these fields should be written to a file named
426      <code class="filename">backup_label</code> in the root directory of the backup. The
427      third field should be written to a file named
428      <code class="filename">tablespace_map</code> unless the field is empty. These files are
429      vital to the backup working and must be written byte for byte without
430      modification, which may require opening the file in binary mode.
431     </p></li><li class="listitem"><p>
432      Once the WAL segment files active during the backup are archived, you are
433      done.  The file identified by <code class="function">pg_backup_stop</code>'s first return
434      value is the last segment that is required to form a complete set of
435      backup files.  On a primary, if <code class="varname">archive_mode</code> is enabled and the
436      <code class="literal">wait_for_archive</code> parameter is <code class="literal">true</code>,
437      <code class="function">pg_backup_stop</code> does not return until the last segment has
438      been archived.
439      On a standby, <code class="varname">archive_mode</code> must be <code class="literal">always</code> in order
440      for <code class="function">pg_backup_stop</code> to wait.
441      Archiving of these files happens automatically since you have
442      already configured <code class="varname">archive_command</code> or <code class="varname">archive_library</code>.
443      In most cases this happens quickly, but you are advised to monitor your
444      archive system to ensure there are no delays.
445      If the archive process has fallen behind because of failures of the
446      archive command or library, it will keep retrying
447      until the archive succeeds and the backup is complete.
448      If you wish to place a time limit on the execution of
449      <code class="function">pg_backup_stop</code>, set an appropriate
450      <code class="varname">statement_timeout</code> value, but make note that if
451      <code class="function">pg_backup_stop</code> terminates because of this your backup
452      may not be valid.
453     </p><p>
454      If the backup process monitors and ensures that all WAL segment files
455      required for the backup are successfully archived then the
456      <code class="literal">wait_for_archive</code> parameter (which defaults to true) can be set
457      to false to have
458      <code class="function">pg_backup_stop</code> return as soon as the stop backup record is
459      written to the WAL.  By default, <code class="function">pg_backup_stop</code> will wait
460      until all WAL has been archived, which can take some time.  This option
461      must be used with caution: if WAL archiving is not monitored correctly
462      then the backup might not include all of the WAL files and will
463      therefore be incomplete and not able to be restored.
464     </p></li></ol></div><p>
465     </p><div class="sect3" id="BACKUP-LOWLEVEL-BASE-BACKUP-DATA"><div class="titlepage"><div><div><h4 class="title">25.3.4.1. Backing Up the Data Directory <a href="#BACKUP-LOWLEVEL-BASE-BACKUP-DATA" class="id_link">#</a></h4></div></div></div><p>
466     Some file system backup tools emit warnings or errors
467     if the files they are trying to copy change while the copy proceeds.
468     When taking a base backup of an active database, this situation is normal
469     and not an error.  However, you need to ensure that you can distinguish
470     complaints of this sort from real errors.  For example, some versions
471     of <span class="application">rsync</span> return a separate exit code for
472     <span class="quote">“<span class="quote">vanished source files</span>”</span>, and you can write a driver script to
473     accept this exit code as a non-error case.  Also, some versions of
474     GNU <span class="application">tar</span> return an error code indistinguishable from
475     a fatal error if a file was truncated while <span class="application">tar</span> was
476     copying it.  Fortunately, GNU <span class="application">tar</span> versions 1.16 and
477     later exit with 1 if a file was changed during the backup,
478     and 2 for other errors.  With GNU <span class="application">tar</span> version 1.23 and
479     later, you can use the warning options <code class="literal">--warning=no-file-changed
480     --warning=no-file-removed</code> to hide the related warning messages.
481    </p><p>
482     Be certain that your backup includes all of the files under
483     the database cluster directory (e.g., <code class="filename">/usr/local/pgsql/data</code>).
484     If you are using tablespaces that do not reside underneath this directory,
485     be careful to include them as well (and be sure that your backup
486     archives symbolic links as links, otherwise the restore will corrupt
487     your tablespaces).
488    </p><p>
489     You should, however, omit from the backup the files within the
490     cluster's <code class="filename">pg_wal/</code> subdirectory.  This
491     slight adjustment is worthwhile because it reduces the risk
492     of mistakes when restoring.  This is easy to arrange if
493     <code class="filename">pg_wal/</code> is a symbolic link pointing to someplace outside
494     the cluster directory, which is a common setup anyway for performance
495     reasons.  You might also want to exclude <code class="filename">postmaster.pid</code>
496     and <code class="filename">postmaster.opts</code>, which record information
497     about the running <span class="application">postmaster</span>, not about the
498     <span class="application">postmaster</span> which will eventually use this backup.
499     (These files can confuse <span class="application">pg_ctl</span>.)
500    </p><p>
501     It is often a good idea to also omit from the backup the files
502     within the cluster's <code class="filename">pg_replslot/</code> directory, so that
503     replication slots that exist on the primary do not become part of the
504     backup.  Otherwise, the subsequent use of the backup to create a standby
505     may result in indefinite retention of WAL files on the standby, and
506     possibly bloat on the primary if hot standby feedback is enabled, because
507     the clients that are using those replication slots will still be connecting
508     to and updating the slots on the primary, not the standby.  Even if the
509     backup is only intended for use in creating a new primary, copying the
510     replication slots isn't expected to be particularly useful, since the
511     contents of those slots will likely be badly out of date by the time
512     the new primary comes on line.
513    </p><p>
514     The contents of the directories <code class="filename">pg_dynshmem/</code>,
515     <code class="filename">pg_notify/</code>, <code class="filename">pg_serial/</code>,
516     <code class="filename">pg_snapshots/</code>, <code class="filename">pg_stat_tmp/</code>,
517     and <code class="filename">pg_subtrans/</code> (but not the directories themselves) can be
518     omitted from the backup as they will be initialized on postmaster startup.
519    </p><p>
520     Any file or directory beginning with <code class="filename">pgsql_tmp</code> can be
521     omitted from the backup.  These files are removed on postmaster start and
522     the directories will be recreated as needed.
523    </p><p>
524     <code class="filename">pg_internal.init</code> files can be omitted from the
525     backup whenever a file of that name is found.  These files contain
526     relation cache data that is always rebuilt when recovering.
527    </p><p>
528     The backup label
529     file includes the label string you gave to <code class="function">pg_backup_start</code>,
530     as well as the time at which <code class="function">pg_backup_start</code> was run, and
531     the name of the starting WAL file.  In case of confusion it is therefore
532     possible to look inside a backup file and determine exactly which
533     backup session the dump file came from.  The tablespace map file includes
534     the symbolic link names as they exist in the directory
535     <code class="filename">pg_tblspc/</code> and the full path of each symbolic link.
536     These files are not merely for your information; their presence and
537     contents are critical to the proper operation of the system's recovery
538     process.
539    </p><p>
540     It is also possible to make a backup while the server is
541     stopped.  In this case, you obviously cannot use
542     <code class="function">pg_backup_start</code> or <code class="function">pg_backup_stop</code>, and
543     you will therefore be left to your own devices to keep track of which
544     backup is which and how far back the associated WAL files go.
545     It is generally better to follow the continuous archiving procedure above.
546    </p></div></div><div class="sect2" id="BACKUP-PITR-RECOVERY"><div class="titlepage"><div><div><h3 class="title">25.3.5. Recovering Using a Continuous Archive Backup <a href="#BACKUP-PITR-RECOVERY" class="id_link">#</a></h3></div></div></div><p>
547     Okay, the worst has happened and you need to recover from your backup.
548     Here is the procedure:
549   </p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>
550      Stop the server, if it's running.
551     </p></li><li class="listitem"><p>
552      If you have the space to do so,
553      copy the whole cluster data directory and any tablespaces to a temporary
554      location in case you need them later. Note that this precaution will
555      require that you have enough free space on your system to hold two
556      copies of your existing database. If you do not have enough space,
557      you should at least save the contents of the cluster's <code class="filename">pg_wal</code>
558      subdirectory, as it might contain WAL files which
559      were not archived before the system went down.
560     </p></li><li class="listitem"><p>
561      Remove all existing files and subdirectories under the cluster data
562      directory and under the root directories of any tablespaces you are using.
563     </p></li><li class="listitem"><p>
564      If you're restoring a full backup, you can restore the database files
565      directly into the target directories.  Be sure that they
566      are restored with the right ownership (the database system user, not
567      <code class="literal">root</code>!) and with the right permissions.  If you are using
568      tablespaces,
569      you should verify that the symbolic links in <code class="filename">pg_tblspc/</code>
570      were correctly restored.
571     </p></li><li class="listitem"><p>
572      If you're restoring an incremental backup, you'll need to restore the
573      incremental backup and all earlier backups upon which it directly or
574      indirectly depends to the machine where you are performing the restore.
575      These backups will need to be placed in separate directories, not the
576      target directories where you want the running server to end up.
577      Once this is done, use <a class="xref" href="app-pgcombinebackup.html" title="pg_combinebackup"><span class="refentrytitle"><span class="application">pg_combinebackup</span></span></a> to pull
578      data from the full backup and all of the subsequent incremental backups
579      and write out a synthetic full backup to the target directories. As above,
580      verify that permissions and tablespace links are correct.
581     </p></li><li class="listitem"><p>
582      Remove any files present in <code class="filename">pg_wal/</code>; these came from the
583      file system backup and are therefore probably obsolete rather than current.
584      If you didn't archive <code class="filename">pg_wal/</code> at all, then recreate
585      it with proper permissions,
586      being careful to ensure that you re-establish it as a symbolic link
587      if you had it set up that way before.
588     </p></li><li class="listitem"><p>
589      If you have unarchived WAL segment files that you saved in step 2,
590      copy them into <code class="filename">pg_wal/</code>.  (It is best to copy them,
591      not move them, so you still have the unmodified files if a
592      problem occurs and you have to start over.)
593     </p></li><li class="listitem"><p>
594      Set recovery configuration settings in
595      <code class="filename">postgresql.conf</code> (see <a class="xref" href="runtime-config-wal.html#RUNTIME-CONFIG-WAL-ARCHIVE-RECOVERY" title="19.5.5. Archive Recovery">Section 19.5.5</a>) and create a file
596      <code class="filename">recovery.signal</code> in the cluster
597      data directory. You might
598      also want to temporarily modify <code class="filename">pg_hba.conf</code> to prevent
599      ordinary users from connecting until you are sure the recovery was successful.
600     </p></li><li class="listitem"><p>
601      Start the server.  The server will go into recovery mode and
602      proceed to read through the archived WAL files it needs.  Should the
603      recovery be terminated because of an external error, the server can
604      simply be restarted and it will continue recovery.  Upon completion
605      of the recovery process, the server will remove
606      <code class="filename">recovery.signal</code> (to prevent
607      accidentally re-entering recovery mode later) and then
608      commence normal database operations.
609     </p></li><li class="listitem"><p>
610      Inspect the contents of the database to ensure you have recovered to
611      the desired state.  If not, return to step 1.  If all is well,
612      allow your users to connect by restoring <code class="filename">pg_hba.conf</code> to normal.
613     </p></li></ol></div><p>
614    </p><p>
615     The key part of all this is to set up a recovery configuration that
616     describes how you want to recover and how far the recovery should
617     run.  The one thing that you absolutely must specify is the <code class="varname">restore_command</code>,
618     which tells <span class="productname">PostgreSQL</span> how to retrieve archived
619     WAL file segments.  Like the <code class="varname">archive_command</code>, this is
620     a shell command string.  It can contain <code class="literal">%f</code>, which is
621     replaced by the name of the desired WAL file, and <code class="literal">%p</code>,
622     which is replaced by the path name to copy the WAL file to.
623     (The path name is relative to the current working directory,
624     i.e., the cluster's data directory.)
625     Write <code class="literal">%%</code> if you need to embed an actual <code class="literal">%</code>
626     character in the command.  The simplest useful command is
627     something like:
628 </p><pre class="programlisting">
629 restore_command = 'cp /mnt/server/archivedir/%f %p'
630 </pre><p>
631     which will copy previously archived WAL segments from the directory
632     <code class="filename">/mnt/server/archivedir</code>.  Of course, you can use something
633     much more complicated, perhaps even a shell script that requests the
634     operator to mount an appropriate tape.
635    </p><p>
636     It is important that the command return nonzero exit status on failure.
637     The command <span class="emphasis"><em>will</em></span> be called requesting files that are not
638     present in the archive; it must return nonzero when so asked.  This is not
639     an error condition.  An exception is that if the command was terminated by
640     a signal (other than <span class="systemitem">SIGTERM</span>, which is used as
641     part of a database server shutdown) or an error by the shell (such as
642     command not found), then recovery will abort and the server will not start
643     up.
644    </p><p>
645     Not all of the requested files will be WAL segment
646     files; you should also expect requests for files with a suffix of
647     <code class="literal">.history</code>. Also be aware that
648     the base name of the <code class="literal">%p</code> path will be different from
649     <code class="literal">%f</code>; do not expect them to be interchangeable.
650    </p><p>
651     WAL segments that cannot be found in the archive will be sought in
652     <code class="filename">pg_wal/</code>; this allows use of recent un-archived segments.
653     However, segments that are available from the archive will be used in
654     preference to files in <code class="filename">pg_wal/</code>.
655    </p><p>
656     Normally, recovery will proceed through all available WAL segments,
657     thereby restoring the database to the current point in time (or as
658     close as possible given the available WAL segments).  Therefore, a normal
659     recovery will end with a <span class="quote">“<span class="quote">file not found</span>”</span> message, the exact text
660     of the error message depending upon your choice of
661     <code class="varname">restore_command</code>.  You may also see an error message
662     at the start of recovery for a file named something like
663     <code class="filename">00000001.history</code>.  This is also normal and does not
664     indicate a problem in simple recovery situations; see
665     <a class="xref" href="continuous-archiving.html#BACKUP-TIMELINES" title="25.3.6. Timelines">Section 25.3.6</a> for discussion.
666    </p><p>
667     If you want to recover to some previous point in time (say, right before
668     the junior DBA dropped your main transaction table), just specify the
669     required <a class="link" href="runtime-config-wal.html#RUNTIME-CONFIG-WAL-RECOVERY-TARGET" title="19.5.6. Recovery Target">stopping point</a>.  You can specify
670     the stop point, known as the <span class="quote">“<span class="quote">recovery target</span>”</span>, either by
671     date/time, named restore point or by completion of a specific transaction
672     ID.  As of this writing only the date/time and named restore point options
673     are very usable, since there are no tools to help you identify with any
674     accuracy which transaction ID to use.
675    </p><div class="note"><h3 class="title">Note</h3><p>
676       The stop point must be after the ending time of the base backup, i.e.,
677       the end time of <code class="function">pg_backup_stop</code>.  You cannot use a base backup
678       to recover to a time when that backup was in progress.  (To
679       recover to such a time, you must go back to your previous base backup
680       and roll forward from there.)
681      </p></div><p>
682     If recovery finds corrupted WAL data, recovery will
683     halt at that point and the server will not start. In such a case the
684     recovery process could be re-run from the beginning, specifying a
685     <span class="quote">“<span class="quote">recovery target</span>”</span> before the point of corruption so that recovery
686     can complete normally.
687     If recovery fails for an external reason, such as a system crash or
688     if the WAL archive has become inaccessible, then the recovery can simply
689     be restarted and it will restart almost from where it failed.
690     Recovery restart works much like checkpointing in normal operation:
691     the server periodically forces all its state to disk, and then updates
692     the <code class="filename">pg_control</code> file to indicate that the already-processed
693     WAL data need not be scanned again.
694    </p></div><div class="sect2" id="BACKUP-TIMELINES"><div class="titlepage"><div><div><h3 class="title">25.3.6. Timelines <a href="#BACKUP-TIMELINES" class="id_link">#</a></h3></div></div></div><a id="id-1.6.12.7.14.2" class="indexterm"></a><p>
695     The ability to restore the database to a previous point in time creates
696     some complexities that are akin to science-fiction stories about time
697     travel and parallel universes.  For example, in the original history of the database,
698     suppose you dropped a critical table at 5:15PM on Tuesday evening, but
699     didn't realize your mistake until Wednesday noon.
700     Unfazed, you get out your backup, restore to the point-in-time 5:14PM
701     Tuesday evening, and are up and running.  In <span class="emphasis"><em>this</em></span> history of
702     the database universe, you never dropped the table.  But suppose
703     you later realize this wasn't such a great idea, and would like
704     to return to sometime Wednesday morning in the original history.
705     You won't be able
706     to if, while your database was up-and-running, it overwrote some of the
707     WAL segment files that led up to the time you now wish you
708     could get back to.  Thus, to avoid this, you need to distinguish the series of
709     WAL records generated after you've done a point-in-time recovery from
710     those that were generated in the original database history.
711    </p><p>
712     To deal with this problem, <span class="productname">PostgreSQL</span> has a notion
713     of <em class="firstterm">timelines</em>.  Whenever an archive recovery completes,
714     a new timeline is created to identify the series of WAL records
715     generated after that recovery.  The timeline
716     ID number is part of WAL segment file names so a new timeline does
717     not overwrite the WAL data generated by previous timelines.
718     For example, in the WAL file name
719     <code class="filename">0000000100001234000055CD</code>, the leading
720     <code class="literal">00000001</code> is the timeline ID in hexadecimal.  (Note that
721     in other contexts, such as server log messages, timeline IDs are
722     usually printed in decimal.)
723    </p><p>
724     It is
725     in fact possible to archive many different timelines.  While that might
726     seem like a useless feature, it's often a lifesaver.  Consider the
727     situation where you aren't quite sure what point-in-time to recover to,
728     and so have to do several point-in-time recoveries by trial and error
729     until you find the best place to branch off from the old history.  Without
730     timelines this process would soon generate an unmanageable mess.  With
731     timelines, you can recover to <span class="emphasis"><em>any</em></span> prior state, including
732     states in timeline branches that you abandoned earlier.
733    </p><p>
734     Every time a new timeline is created, <span class="productname">PostgreSQL</span> creates
735     a <span class="quote">“<span class="quote">timeline history</span>”</span> file that shows which timeline it branched
736     off from and when.  These history files are necessary to allow the system
737     to pick the right WAL segment files when recovering from an archive that
738     contains multiple timelines.  Therefore, they are archived into the WAL
739     archive area just like WAL segment files.  The history files are just
740     small text files, so it's cheap and appropriate to keep them around
741     indefinitely (unlike the segment files which are large).  You can, if
742     you like, add comments to a history file to record your own notes about
743     how and why this particular timeline was created.  Such comments will be
744     especially valuable when you have a thicket of different timelines as
745     a result of experimentation.
746    </p><p>
747     The default behavior of recovery is to recover to the latest timeline found
748     in the archive. If you wish to recover to the timeline that was current
749     when the base backup was taken or into a specific child timeline (that
750     is, you want to return to some state that was itself generated after a
751     recovery attempt), you need to specify <code class="literal">current</code> or the
752     target timeline ID in <a class="xref" href="runtime-config-wal.html#GUC-RECOVERY-TARGET-TIMELINE">recovery_target_timeline</a>. You
753     cannot recover into timelines that branched off earlier than the base backup.
754    </p></div><div class="sect2" id="BACKUP-TIPS"><div class="titlepage"><div><div><h3 class="title">25.3.7. Tips and Examples <a href="#BACKUP-TIPS" class="id_link">#</a></h3></div></div></div><p>
755     Some tips for configuring continuous archiving are given here.
756    </p><div class="sect3" id="BACKUP-STANDALONE"><div class="titlepage"><div><div><h4 class="title">25.3.7.1. Standalone Hot Backups <a href="#BACKUP-STANDALONE" class="id_link">#</a></h4></div></div></div><p>
757       It is possible to use <span class="productname">PostgreSQL</span>'s backup facilities to
758       produce standalone hot backups. These are backups that cannot be used
759       for point-in-time recovery, yet are typically much faster to backup and
760       restore than <span class="application">pg_dump</span> dumps.  (They are also much larger
761       than <span class="application">pg_dump</span> dumps, so in some cases the speed advantage
762       might be negated.)
763      </p><p>
764       As with base backups, the easiest way to produce a standalone
765       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>
766       tool. If you include the <code class="literal">-X</code> parameter when calling
767       it, all the write-ahead log required to use the backup will be
768       included in the backup automatically, and no special action is
769       required to restore the backup.
770      </p></div><div class="sect3" id="COMPRESSED-ARCHIVE-LOGS"><div class="titlepage"><div><div><h4 class="title">25.3.7.2. Compressed Archive Logs <a href="#COMPRESSED-ARCHIVE-LOGS" class="id_link">#</a></h4></div></div></div><p>
771       If archive storage size is a concern, you can use
772       <span class="application">gzip</span> to compress the archive files:
773 </p><pre class="programlisting">
774 archive_command = 'gzip &lt; %p &gt; /mnt/server/archivedir/%f.gz'
775 </pre><p>
776       You will then need to use <span class="application">gunzip</span> during recovery:
777 </p><pre class="programlisting">
778 restore_command = 'gunzip &lt; /mnt/server/archivedir/%f.gz &gt; %p'
779 </pre><p>
780      </p></div><div class="sect3" id="BACKUP-SCRIPTS"><div class="titlepage"><div><div><h4 class="title">25.3.7.3. <code class="varname">archive_command</code> Scripts <a href="#BACKUP-SCRIPTS" class="id_link">#</a></h4></div></div></div><p>
781       Many people choose to use scripts to define their
782       <code class="varname">archive_command</code>, so that their
783       <code class="filename">postgresql.conf</code> entry looks very simple:
784 </p><pre class="programlisting">
785 archive_command = 'local_backup_script.sh "%p" "%f"'
786 </pre><p>
787       Using a separate script file is advisable any time you want to use
788       more than a single command in the archiving process.
789       This allows all complexity to be managed within the script, which
790       can be written in a popular scripting language such as
791       <span class="application">bash</span> or <span class="application">perl</span>.
792      </p><p>
793       Examples of requirements that might be solved within a script include:
794       </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
795          Copying data to secure off-site data storage
796         </p></li><li class="listitem"><p>
797          Batching WAL files so that they are transferred every three hours,
798          rather than one at a time
799         </p></li><li class="listitem"><p>
800          Interfacing with other backup and recovery software
801         </p></li><li class="listitem"><p>
802          Interfacing with monitoring software to report errors
803         </p></li></ul></div><p>
804      </p><div class="tip"><h3 class="title">Tip</h3><p>
805        When using an <code class="varname">archive_command</code> script, it's desirable
806        to enable <a class="xref" href="runtime-config-logging.html#GUC-LOGGING-COLLECTOR">logging_collector</a>.
807        Any messages written to <span class="systemitem">stderr</span> from the script will then
808        appear in the database server log, allowing complex configurations to
809        be diagnosed easily if they fail.
810       </p></div></div></div><div class="sect2" id="CONTINUOUS-ARCHIVING-CAVEATS"><div class="titlepage"><div><div><h3 class="title">25.3.8. Caveats <a href="#CONTINUOUS-ARCHIVING-CAVEATS" class="id_link">#</a></h3></div></div></div><p>
811     At this writing, there are several limitations of the continuous archiving
812     technique.  These will probably be fixed in future releases:
813
814   </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
815      If a <a class="link" href="sql-createdatabase.html" title="CREATE DATABASE"><code class="command">CREATE DATABASE</code></a>
816      command is executed while a base backup is being taken, and then
817      the template database that the <code class="command">CREATE DATABASE</code> copied
818      is modified while the base backup is still in progress, it is
819      possible that recovery will cause those modifications to be
820      propagated into the created database as well.  This is of course
821      undesirable.  To avoid this risk, it is best not to modify any
822      template databases while taking a base backup.
823     </p></li><li class="listitem"><p>
824      <a class="link" href="sql-createtablespace.html" title="CREATE TABLESPACE"><code class="command">CREATE TABLESPACE</code></a>
825      commands are WAL-logged with the literal absolute path, and will
826      therefore be replayed as tablespace creations with the same
827      absolute path.  This might be undesirable if the WAL is being
828      replayed on a different machine.  It can be dangerous even if the
829      WAL is being replayed on the same machine, but into a new data
830      directory: the replay will still overwrite the contents of the
831      original tablespace.  To avoid potential gotchas of this sort,
832      the best practice is to take a new base backup after creating or
833      dropping tablespaces.
834     </p></li></ul></div><p>
835    </p><p>
836     It should also be noted that the default <acronym class="acronym">WAL</acronym>
837     format is fairly bulky since it includes many disk page snapshots.
838     These page snapshots are designed to support crash recovery, since
839     we might need to fix partially-written disk pages.  Depending on
840     your system hardware and software, the risk of partial writes might
841     be small enough to ignore, in which case you can significantly
842     reduce the total volume of archived WAL files by turning off page
843     snapshots using the <a class="xref" href="runtime-config-wal.html#GUC-FULL-PAGE-WRITES">full_page_writes</a>
844     parameter.  (Read the notes and warnings in <a class="xref" href="wal.html" title="Chapter 28. Reliability and the Write-Ahead Log">Chapter 28</a>
845     before you do so.)  Turning off page snapshots does not prevent
846     use of the WAL for PITR operations.  An area for future
847     development is to compress archived WAL data by removing
848     unnecessary page copies even when <code class="varname">full_page_writes</code> is
849     on.  In the meantime, administrators might wish to reduce the number
850     of page snapshots included in WAL by increasing the checkpoint
851     interval parameters as much as feasible.
852    </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="25.2. File System Level Backup">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="backup.html" title="Chapter 25. Backup and Restore">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="high-availability.html" title="Chapter 26. High Availability, Load Balancing, and Replication">Next</a></td></tr><tr><td width="40%" align="left" valign="top">25.2. File System Level Backup </td><td width="20%" align="center"><a accesskey="h" href="index.html" title="PostgreSQL 18.0 Documentation">Home</a></td><td width="40%" align="right" valign="top"> Chapter 26. High Availability, Load Balancing, and Replication</td></tr></table></div></body></html>