]> granicus.if.org Git - postgresql/blob - doc/src/sgml/backup.sgml
Add missing closing tag.
[postgresql] / doc / src / sgml / backup.sgml
1 <!-- $PostgreSQL: pgsql/doc/src/sgml/backup.sgml,v 2.138 2010/01/24 14:46:01 mha Exp $ -->
2
3 <chapter id="backup">
4  <title>Backup and Restore</title>
5
6  <indexterm zone="backup"><primary>backup</></>
7
8  <para>
9   As with everything that contains valuable data, <productname>PostgreSQL</>
10   databases should be backed up regularly. While the procedure is
11   essentially simple, it is important to have a clear understanding of
12   the underlying techniques and assumptions.
13  </para>
14
15  <para>
16   There are three fundamentally different approaches to backing up
17   <productname>PostgreSQL</> data:
18   <itemizedlist>
19    <listitem><para><acronym>SQL</> dump</para></listitem>
20    <listitem><para>File system level backup</para></listitem>
21    <listitem><para>Continuous archiving</para></listitem>
22   </itemizedlist>
23   Each has its own strengths and weaknesses.
24   Each is discussed in turn below.
25  </para>
26
27  <sect1 id="backup-dump">
28   <title><acronym>SQL</> Dump</title>
29
30   <para>
31    The idea behind this dump method is to generate a text file with SQL
32    commands that, when fed back to the server, will recreate the
33    database in the same state as it was at the time of the dump.
34    <productname>PostgreSQL</> provides the utility program
35    <xref linkend="app-pgdump"> for this purpose. The basic usage of this
36    command is:
37 <synopsis>
38 pg_dump <replaceable class="parameter">dbname</replaceable> &gt; <replaceable class="parameter">outfile</replaceable>
39 </synopsis>
40    As you see, <application>pg_dump</> writes its results to the
41    standard output. We will see below how this can be useful.
42   </para>
43
44   <para>
45    <application>pg_dump</> is a regular <productname>PostgreSQL</>
46    client application (albeit a particularly clever one). This means
47    that you can do this backup procedure from any remote host that has
48    access to the database. But remember that <application>pg_dump</>
49    does not operate with special permissions. In particular, it must
50    have read access to all tables that you want to back up, so in
51    practice you almost always have to run it as a database superuser.
52   </para>
53
54   <para>
55    To specify which database server <application>pg_dump</> should
56    contact, use the command line options <option>-h
57    <replaceable>host</></> and <option>-p <replaceable>port</></>. The
58    default host is the local host or whatever your
59    <envar>PGHOST</envar> environment variable specifies. Similarly,
60    the default port is indicated by the <envar>PGPORT</envar>
61    environment variable or, failing that, by the compiled-in default.
62    (Conveniently, the server will normally have the same compiled-in
63    default.)
64   </para>
65
66   <para>
67    Like any other <productname>PostgreSQL</> client application,
68    <application>pg_dump</> will by default connect with the database
69    user name that is equal to the current operating system user name. To override
70    this, either specify the <option>-U</option> option or set the
71    environment variable <envar>PGUSER</envar>. Remember that
72    <application>pg_dump</> connections are subject to the normal
73    client authentication mechanisms (which are described in <xref
74    linkend="client-authentication">).
75   </para>
76
77   <para>
78    Dumps created by <application>pg_dump</> are internally consistent,
79    that is, the dump represents a snapshot of the database as of the time
80    <application>pg_dump</> begins running. <application>pg_dump</> does not
81    block other operations on the database while it is working.
82    (Exceptions are those operations that need to operate with an
83    exclusive lock, such as most forms of <command>ALTER TABLE</command>.)
84   </para>
85
86   <important>
87    <para>
88     If your database schema relies on OIDs (for instance as foreign
89     keys) you must instruct <application>pg_dump</> to dump the OIDs
90     as well. To do this, use the <option>-o</option> command line
91     option.
92    </para>
93   </important>
94
95   <sect2 id="backup-dump-restore">
96    <title>Restoring the dump</title>
97
98    <para>
99     The text files created by <application>pg_dump</> are intended to
100     be read in by the <application>psql</application> program. The
101     general command form to restore a dump is
102 <synopsis>
103 psql <replaceable class="parameter">dbname</replaceable> &lt; <replaceable class="parameter">infile</replaceable>
104 </synopsis>
105     where <replaceable class="parameter">infile</replaceable> is what
106     you used as <replaceable class="parameter">outfile</replaceable>
107     for the <application>pg_dump</> command. The database <replaceable
108     class="parameter">dbname</replaceable> will not be created by this
109     command, so you must create it yourself from <literal>template0</>
110     before executing <application>psql</> (e.g., with
111     <literal>createdb -T template0 <replaceable
112     class="parameter">dbname</></literal>).  <application>psql</>
113     supports options similar to <application>pg_dump</>'s for specifying
114     the database server to connect to and the user name to use. See
115     the <xref linkend="app-psql"> reference page for more information.
116    </para>
117
118    <para>
119     Before restoring a SQL dump, all the users who own objects or were
120     granted permissions on objects in the dumped database must already
121     exist. If they do not, then the restore will fail to recreate the
122     objects with the original ownership and/or permissions.
123     (Sometimes this is what you want, but usually it is not.)
124    </para>
125
126    <para>
127     By default, the <application>psql</> script will continue to
128     execute after an SQL error is encountered. You might wish to use the
129     following command at the top of the script to alter that
130     behaviour and have <application>psql</application> exit with an
131     exit status of 3 if an SQL error occurs:
132 <programlisting>
133 \set ON_ERROR_STOP
134 </programlisting>
135     Either way, you will have an only partially restored database.
136     Alternatively, you can specify that the whole dump should be
137     restored as a single transaction, so the restore is either fully
138     completed or fully rolled back. This mode can be specified by
139     passing the <option>-1</> or <option>--single-transaction</>
140     command-line options to <application>psql</>. When using this
141     mode, be aware that even the smallest of errors can rollback a
142     restore that has already run for many hours. However, that might
143     still be preferable to manually cleaning up a complex database
144     after a partially restored dump.
145    </para>
146
147    <para>
148     The ability of <application>pg_dump</> and <application>psql</> to
149     write to or read from pipes makes it possible to dump a database
150     directly from one server to another, for example:
151 <programlisting>
152 pg_dump -h <replaceable>host1</> <replaceable>dbname</> | psql -h <replaceable>host2</> <replaceable>dbname</>
153 </programlisting>
154    </para>
155
156    <important>
157     <para>
158      The dumps produced by <application>pg_dump</> are relative to
159      <literal>template0</>. This means that any languages, procedures,
160      etc. added via <literal>template1</> will also be dumped by
161      <application>pg_dump</>. As a result, when restoring, if you are
162      using a customized <literal>template1</>, you must create the
163      empty database from <literal>template0</>, as in the example
164      above.
165     </para>
166    </important>
167
168    <para>
169     After restoring a backup, it is wise to run <xref
170     linkend="sql-analyze" endterm="sql-analyze-title"> on each
171     database so the query optimizer has useful statistics;
172     see <xref linkend="vacuum-for-statistics" endterm="vacuum-for-statistics-title">
173     and <xref linkend="autovacuum" endterm="autovacuum-title"> for more information.
174     For more advice on how to load large amounts of data
175     into <productname>PostgreSQL</> efficiently, refer to <xref
176     linkend="populate">.
177    </para>
178   </sect2>
179
180   <sect2 id="backup-dump-all">
181    <title>Using <application>pg_dumpall</></title>
182
183    <para>
184     <application>pg_dump</> dumps only a single database at a time,
185     and it does not dump information about roles or tablespaces
186     (because those are cluster-wide rather than per-database).
187     To support convenient dumping of the entire contents of a database
188     cluster, the <xref linkend="app-pg-dumpall"> program is provided.
189     <application>pg_dumpall</> backs up each database in a given
190     cluster, and also preserves cluster-wide data such as role and
191     tablespace definitions. The basic usage of this command is:
192 <synopsis>
193 pg_dumpall &gt; <replaceable>outfile</>
194 </synopsis>
195     The resulting dump can be restored with <application>psql</>:
196 <synopsis>
197 psql -f <replaceable class="parameter">infile</replaceable> postgres
198 </synopsis>
199     (Actually, you can specify any existing database name to start from,
200     but if you are reloading into an empty cluster then <literal>postgres</>
201     should usually be used.)  It is always necessary to have
202     database superuser access when restoring a <application>pg_dumpall</>
203     dump, as that is required to restore the role and tablespace information.
204     If you use tablespaces, be careful that the tablespace paths in the
205     dump are appropriate for the new installation.
206    </para>
207
208    <para>
209     <application>pg_dumpall</> works by emitting commands to re-create
210     roles, tablespaces, and empty databases, then invoking
211     <application>pg_dump</> for each database.  This means that while
212     each database will be internally consistent, the snapshots of
213     different databases might not be exactly in-sync.
214    </para>
215   </sect2>
216
217   <sect2 id="backup-dump-large">
218    <title>Handling large databases</title>
219
220    <para>
221     Since <productname>PostgreSQL</productname> allows tables larger
222     than the maximum file size on your system, it can be problematic
223     to dump such a table to a file, since the resulting file will likely
224     be larger than the maximum size allowed by your system. Since
225     <application>pg_dump</> can write to the standard output, you can
226     use standard Unix tools to work around this possible problem.
227     There are several ways to do it:
228    </para>
229
230    <formalpara>
231     <title>Use compressed dumps.</title>
232     <para>
233      You can use your favorite compression program, for example
234      <application>gzip</application>:
235
236 <programlisting>
237 pg_dump <replaceable class="parameter">dbname</replaceable> | gzip &gt; <replaceable class="parameter">filename</replaceable>.gz
238 </programlisting>
239
240      Reload with:
241
242 <programlisting>
243 gunzip -c <replaceable class="parameter">filename</replaceable>.gz | psql <replaceable class="parameter">dbname</replaceable>
244 </programlisting>
245
246      or:
247
248 <programlisting>
249 cat <replaceable class="parameter">filename</replaceable>.gz | gunzip | psql <replaceable class="parameter">dbname</replaceable>
250 </programlisting>
251     </para>
252    </formalpara>
253
254    <formalpara>
255     <title>Use <command>split</>.</title>
256     <para>
257      The <command>split</command> command
258      allows you to split the output into pieces that are
259      acceptable in size to the underlying file system. For example, to
260      make chunks of 1 megabyte:
261
262 <programlisting>
263 pg_dump <replaceable class="parameter">dbname</replaceable> | split -b 1m - <replaceable class="parameter">filename</replaceable>
264 </programlisting>
265
266      Reload with:
267
268 <programlisting>
269 cat <replaceable class="parameter">filename</replaceable>* | psql <replaceable class="parameter">dbname</replaceable>
270 </programlisting>
271     </para>
272    </formalpara>
273
274    <formalpara>
275     <title>Use <application>pg_dump</>'s custom dump format.</title>
276     <para>
277      If <productname>PostgreSQL</productname> was built on a system with the
278      <application>zlib</> compression library installed, the custom dump
279      format will compress data as it writes it to the output file. This will
280      produce dump file sizes similar to using <command>gzip</command>, but it
281      has the added advantage that tables can be restored selectively. The
282      following command dumps a database using the custom dump format:
283
284 <programlisting>
285 pg_dump -Fc <replaceable class="parameter">dbname</replaceable> &gt; <replaceable class="parameter">filename</replaceable>
286 </programlisting>
287
288      A custom-format dump is not a script for <application>psql</>, but
289      instead must be restored with <application>pg_restore</>, for example:
290
291 <programlisting>
292 pg_restore -d <replaceable class="parameter">dbname</replaceable> <replaceable class="parameter">filename</replaceable>
293 </programlisting>
294
295      See the <xref linkend="app-pgdump"> and <xref
296      linkend="app-pgrestore"> reference pages for details.
297     </para>
298    </formalpara>
299
300    <para>
301     For very large databases, you might need to combine <command>split</>
302     with one of the other two approaches.
303    </para>
304
305   </sect2>
306  </sect1>
307
308  <sect1 id="backup-file">
309   <title>File System Level Backup</title>
310
311   <para>
312    An alternative backup strategy is to directly copy the files that
313    <productname>PostgreSQL</> uses to store the data in the database. In
314    <xref linkend="creating-cluster"> it is explained where these files
315    are located, but you have probably found them already if you are
316    interested in this method. You can use whatever method you prefer
317    for doing usual file system backups, for example:
318
319 <programlisting>
320 tar -cf backup.tar /usr/local/pgsql/data
321 </programlisting>
322   </para>
323
324   <para>
325    There are two restrictions, however, which make this method
326    impractical, or at least inferior to the <application>pg_dump</>
327    method:
328
329    <orderedlist>
330     <listitem>
331      <para>
332       The database server <emphasis>must</> be shut down in order to
333       get a usable backup. Half-way measures such as disallowing all
334       connections will <emphasis>not</emphasis> work
335       (in part because <command>tar</command> and similar tools do not take
336       an atomic snapshot of the state of the file system,
337       but also because of internal buffering within the server).
338       Information about stopping the server can be found in
339       <xref linkend="server-shutdown">.  Needless to say that you
340       also need to shut down the server before restoring the data.
341      </para>
342     </listitem>
343
344     <listitem>
345      <para>
346       If you have dug into the details of the file system layout of the
347       database, you might be tempted to try to back up or restore only certain
348       individual tables or databases from their respective files or
349       directories. This will <emphasis>not</> work because the
350       information contained in these files contains only half the
351       truth. The other half is in the commit log files
352       <filename>pg_clog/*</filename>, which contain the commit status of
353       all transactions. A table file is only usable with this
354       information. Of course it is also impossible to restore only a
355       table and the associated <filename>pg_clog</filename> data
356       because that would render all other tables in the database
357       cluster useless.  So file system backups only work for complete
358       backup and restoration of an entire database cluster.
359      </para>
360     </listitem>
361    </orderedlist>
362   </para>
363
364   <para>
365    An alternative file-system backup approach is to make a
366    <quote>consistent snapshot</quote> of the data directory, if the
367    file system supports that functionality (and you are willing to
368    trust that it is implemented correctly).  The typical procedure is
369    to make a <quote>frozen snapshot</> of the volume containing the
370    database, then copy the whole data directory (not just parts, see
371    above) from the snapshot to a backup device, then release the frozen
372    snapshot.  This will work even while the database server is running.
373    However, a backup created in this way saves
374    the database files in a state where the database server was not
375    properly shut down; therefore, when you start the database server
376    on the backed-up data, it will think the previous server instance had
377    crashed and replay the WAL log.  This is not a problem, just be aware of
378    it (and be sure to include the WAL files in your backup).
379   </para>
380
381   <para>
382    If your database is spread across multiple file systems, there might not
383    be any way to obtain exactly-simultaneous frozen snapshots of all
384    the volumes.  For example, if your data files and WAL log are on different
385    disks, or if tablespaces are on different file systems, it might
386    not be possible to use snapshot backup because the snapshots
387    <emphasis>must</> be simultaneous.
388    Read your file system documentation very carefully before trusting
389    to the consistent-snapshot technique in such situations.
390   </para>
391
392   <para>
393    If simultaneous snapshots are not possible, one option is to shut down
394    the database server long enough to establish all the frozen snapshots.
395    Another option is perform a continuous archiving base backup (<xref
396    linkend="backup-base-backup">) because such backups are immune to file
397    system changes during the backup.  This requires enabling continuous
398    archiving just during the backup process; restore is done using
399    continuous archive recovery (<xref linkend="backup-pitr-recovery">).
400   </para>
401
402   <para>
403    Another option is to use <application>rsync</> to perform a file
404    system backup.  This is done by first running <application>rsync</>
405    while the database server is running, then shutting down the database
406    server just long enough to do a second <application>rsync</>.  The
407    second <application>rsync</> will be much quicker than the first,
408    because it has relatively little data to transfer, and the end result
409    will be consistent because the server was down.  This method
410    allows a file system backup to be performed with minimal downtime.
411   </para>
412
413   <para>
414    Note that a file system backup will not necessarily be
415    smaller than an SQL dump. On the contrary, it will most likely be
416    larger. (<application>pg_dump</application> does not need to dump
417    the contents of indexes for example, just the commands to recreate
418    them.)  However, taking a file system backup might be faster.
419   </para>
420  </sect1>
421
422  <sect1 id="continuous-archiving">
423   <title>Continuous Archiving and Point-In-Time Recovery (PITR)</title>
424
425   <indexterm zone="backup">
426    <primary>continuous archiving</primary>
427   </indexterm>
428
429   <indexterm zone="backup">
430    <primary>point-in-time recovery</primary>
431   </indexterm>
432
433   <indexterm zone="backup">
434    <primary>PITR</primary>
435   </indexterm>
436
437   <para>
438    At all times, <productname>PostgreSQL</> maintains a
439    <firstterm>write ahead log</> (WAL) in the <filename>pg_xlog/</>
440    subdirectory of the cluster's data directory. The log describes
441    every change made to the database's data files.  This log exists
442    primarily for crash-safety purposes: if the system crashes, the
443    database can be restored to consistency by <quote>replaying</> the
444    log entries made since the last checkpoint.  However, the existence
445    of the log makes it possible to use a third strategy for backing up
446    databases: we can combine a file-system-level backup with backup of
447    the WAL files.  If recovery is needed, we restore the backup and
448    then replay from the backed-up WAL files to bring the backup up to
449    current time.  This approach is more complex to administer than
450    either of the previous approaches, but it has some significant
451    benefits:
452   <itemizedlist>
453    <listitem>
454     <para>
455      We do not need a perfectly consistent backup as the starting point.
456      Any internal inconsistency in the backup will be corrected by log
457      replay (this is not significantly different from what happens during
458      crash recovery).  So we don't need file system snapshot capability,
459      just <application>tar</> or a similar archiving tool.
460     </para>
461    </listitem>
462    <listitem>
463     <para>
464      Since we can string together an indefinitely long sequence of WAL files
465      for replay, continuous backup can be achieved simply by continuing to archive
466      the WAL files.  This is particularly valuable for large databases, where
467      it might not be convenient to take a full backup frequently.
468     </para>
469    </listitem>
470    <listitem>
471     <para>
472      There is nothing that says we have to replay the WAL entries all the
473      way to the end.  We could stop the replay at any point and have a
474      consistent snapshot of the database as it was at that time.  Thus,
475      this technique supports <firstterm>point-in-time recovery</>: it is
476      possible to restore the database to its state at any time since your base
477      backup was taken.
478     </para>
479    </listitem>
480    <listitem>
481     <para>
482      If we continuously feed the series of WAL files to another
483      machine that has been loaded with the same base backup file, we
484      have a <firstterm>warm standby</> system: at any point we can bring up
485      the second machine and it will have a nearly-current copy of the
486      database.
487     </para>
488    </listitem>
489   </itemizedlist>
490   </para>
491
492   <para>
493    As with the plain file-system-backup technique, this method can only
494    support restoration of an entire database cluster, not a subset.
495    Also, it requires a lot of archival storage: the base backup might be bulky,
496    and a busy system will generate many megabytes of WAL traffic that
497    have to be archived.  Still, it is the preferred backup technique in
498    many situations where high reliability is needed.
499   </para>
500
501   <para>
502    To recover successfully using continuous archiving (also called
503    <quote>online backup</> by many database vendors), you need a continuous
504    sequence of archived WAL files that extends back at least as far as the
505    start time of your backup.  So to get started, you should set up and test
506    your procedure for archiving WAL files <emphasis>before</> you take your
507    first base backup.  Accordingly, we first discuss the mechanics of
508    archiving WAL files.
509   </para>
510
511   <sect2 id="backup-archiving-wal">
512    <title>Setting up WAL archiving</title>
513
514    <para>
515     In an abstract sense, a running <productname>PostgreSQL</> system
516     produces an indefinitely long sequence of WAL records.  The system
517     physically divides this sequence into WAL <firstterm>segment
518     files</>, which are normally 16MB apiece (although the segment size
519     can be altered when building <productname>PostgreSQL</>).  The segment
520     files are given numeric names that reflect their position in the
521     abstract WAL sequence.  When not using WAL archiving, the system
522     normally creates just a few segment files and then
523     <quote>recycles</> them by renaming no-longer-needed segment files
524     to higher segment numbers.  It's assumed that a segment file whose
525     contents precede the checkpoint-before-last is no longer of
526     interest and can be recycled.
527    </para>
528
529    <para>
530     When archiving WAL data, we need to capture the contents of each segment
531     file once it is filled, and save that data somewhere before the segment
532     file is recycled for reuse.  Depending on the application and the
533     available hardware, there could be many different ways of <quote>saving
534     the data somewhere</>: we could copy the segment files to an NFS-mounted
535     directory on another machine, write them onto a tape drive (ensuring that
536     you have a way of identifying the original name of each file), or batch
537     them together and burn them onto CDs, or something else entirely.  To
538     provide the database administrator with as much flexibility as possible,
539     <productname>PostgreSQL</> tries not to make any assumptions about how
540     the archiving will be done.  Instead, <productname>PostgreSQL</> lets
541     the administrator specify a shell command to be executed to copy a
542     completed segment file to wherever it needs to go.  The command could be
543     as simple as a <literal>cp</>, or it could invoke a complex shell
544     script &mdash; it's all up to you.
545    </para>
546
547    <para>
548     To enable WAL archiving, set the <xref
549     linkend="guc-archive-mode"> configuration parameter to <literal>on</>,
550     and specify the shell command to use in the <xref
551     linkend="guc-archive-command"> configuration parameter.  In practice
552     these settings will always be placed in the
553     <filename>postgresql.conf</filename> file.
554     In <varname>archive_command</>,
555     any <literal>%p</> is replaced by the path name of the file to
556     archive, while any <literal>%f</> is replaced by the file name only.
557     (The path name is relative to the current working directory,
558     i.e., the cluster's data directory.)
559     Write <literal>%%</> if you need to embed an actual <literal>%</>
560     character in the command.  The simplest useful command is something
561     like:
562 <programlisting>
563 archive_command = 'cp -i %p /mnt/server/archivedir/%f &lt;/dev/null'
564 </programlisting>
565     which will copy archivable WAL segments to the directory
566     <filename>/mnt/server/archivedir</>.  (This is an example, not a
567     recommendation, and might not work on all platforms.)  After the
568     <literal>%p</> and <literal>%f</> parameters have been replaced,
569     the actual command executed might look like this:
570 <programlisting>
571 cp -i pg_xlog/00000001000000A900000065 /mnt/server/archivedir/00000001000000A900000065 &lt;/dev/null
572 </programlisting>
573     A similar command will be generated for each new file to be archived.
574    </para>
575
576    <para>
577     The archive command will be executed under the ownership of the same
578     user that the <productname>PostgreSQL</> server is running as.  Since
579     the series of WAL files being archived contains effectively everything
580     in your database, you will want to be sure that the archived data is
581     protected from prying eyes; for example, archive into a directory that
582     does not have group or world read access.
583    </para>
584
585    <para>
586     It is important that the archive command return zero exit status if and
587     only if it succeeded.  Upon getting a zero result,
588     <productname>PostgreSQL</> will assume that the file has been
589     successfully archived, and will remove or recycle it.  However, a nonzero
590     status tells <productname>PostgreSQL</> that the file was not archived;
591     it will try again periodically until it succeeds.
592    </para>
593
594    <para>
595     The archive command should generally be designed to refuse to overwrite
596     any pre-existing archive file.  This is an important safety feature to
597     preserve the integrity of your archive in case of administrator error
598     (such as sending the output of two different servers to the same archive
599     directory).
600     It is advisable to test your proposed archive command to ensure that it
601     indeed does not overwrite an existing file, <emphasis>and that it returns
602     nonzero status in this case</>.  We have found that <literal>cp -i</> does
603     this correctly on some platforms but not others.  If the chosen command
604     does not itself handle this case correctly, you should add a command
605     to test for pre-existence of the archive file.  For example, something
606     like:
607 <programlisting>
608 archive_command = 'test ! -f .../%f &amp;&amp; cp %p .../%f'
609 </programlisting>
610     works correctly on most Unix variants.
611    </para>
612
613    <para>
614     While designing your archiving setup, consider what will happen if
615     the archive command fails repeatedly because some aspect requires
616     operator intervention or the archive runs out of space. For example, this
617     could occur if you write to tape without an autochanger; when the tape
618     fills, nothing further can be archived until the tape is swapped.
619     You should ensure that any error condition or request to a human operator
620     is reported appropriately so that the situation can be
621     resolved reasonably quickly. The <filename>pg_xlog/</> directory will
622     continue to fill with WAL segment files until the situation is resolved.
623     (If the filesystem containing <filename>pg_xlog/</> fills up,
624     <productname>PostgreSQL</> will do a PANIC shutdown.  No prior
625     transactions will be lost, but the database will be unavailable until
626     you free some space.)
627    </para>
628
629    <para>
630     The speed of the archiving command is not important, so long as it can keep up
631     with the average rate at which your server generates WAL data.  Normal
632     operation continues even if the archiving process falls a little behind.
633     If archiving falls significantly behind, this will increase the amount of
634     data that would be lost in the event of a disaster. It will also mean that
635     the <filename>pg_xlog/</> directory will contain large numbers of
636     not-yet-archived segment files, which could eventually exceed available
637     disk space. You are advised to monitor the archiving process to ensure that
638     it is working as you intend.
639    </para>
640
641    <para>
642     In writing your archive command, you should assume that the file names to
643     be archived can be up to 64 characters long and can contain any
644     combination of ASCII letters, digits, and dots.  It is not necessary to
645     remember the original relative path (<literal>%p</>) but it is necessary to
646     remember the file name (<literal>%f</>).
647    </para>
648
649    <para>
650     Note that although WAL archiving will allow you to restore any
651     modifications made to the data in your <productname>PostgreSQL</> database,
652     it will not restore changes made to configuration files (that is,
653     <filename>postgresql.conf</>, <filename>pg_hba.conf</> and
654     <filename>pg_ident.conf</>), since those are edited manually rather
655     than through SQL operations.
656     You might wish to keep the configuration files in a location that will
657     be backed up by your regular file system backup procedures.  See
658     <xref linkend="runtime-config-file-locations"> for how to relocate the
659     configuration files.
660    </para>
661
662    <para>
663     The archive command is only invoked on completed WAL segments.  Hence,
664     if your server generates only little WAL traffic (or has slack periods
665     where it does so), there could be a long delay between the completion
666     of a transaction and its safe recording in archive storage.  To put
667     a limit on how old unarchived data can be, you can set
668     <xref linkend="guc-archive-timeout"> to force the server to switch
669     to a new WAL segment file at least that often.  Note that archived
670     files that are ended early due to a forced switch are still the same
671     length as completely full files.  It is therefore unwise to set a very
672     short <varname>archive_timeout</> &mdash; it will bloat your archive
673     storage.  <varname>archive_timeout</> settings of a minute or so are
674     usually reasonable.
675    </para>
676
677    <para>
678     Also, you can force a segment switch manually with
679     <function>pg_switch_xlog</>, if you want to ensure that a
680     just-finished transaction is archived as soon as possible.  Other utility
681     functions related to WAL management are listed in <xref
682     linkend="functions-admin-backup-table">.
683    </para>
684
685    <para>
686     When <varname>archive_mode</> is <literal>off</> some SQL commands
687     are optimized to avoid WAL logging, as described in <xref
688     linkend="populate-pitr">. If archiving were turned on during execution
689     of one of these statements, WAL would not contain enough information
690     for archive recovery.  (Crash recovery is unaffected.)  For
691     this reason, <varname>archive_mode</> can only be changed at server
692     start.  However, <varname>archive_command</> can be changed with a
693     configuration file reload.  If you wish to temporarily stop archiving,
694     one way to do it is to set <varname>archive_command</> to the empty
695     string (<literal>''</>).
696     This will cause WAL files to accumulate in <filename>pg_xlog/</> until a
697     working <varname>archive_command</> is re-established.
698    </para>
699   </sect2>
700
701   <sect2 id="backup-base-backup">
702    <title>Making a Base Backup</title>
703
704    <para>
705     The procedure for making a base backup is relatively simple:
706   <orderedlist>
707    <listitem>
708     <para>
709      Ensure that WAL archiving is enabled and working.
710     </para>
711    </listitem>
712    <listitem>
713     <para>
714      Connect to the database as a superuser, and issue the command:
715 <programlisting>
716 SELECT pg_start_backup('label');
717 </programlisting>
718      where <literal>label</> is any string you want to use to uniquely
719      identify this backup operation.  (One good practice is to use the
720      full path where you intend to put the backup dump file.)
721      <function>pg_start_backup</> creates a <firstterm>backup label</> file,
722      called <filename>backup_label</>, in the cluster directory with
723      information about your backup.
724     </para>
725
726     <para>
727      It does not matter which database within the cluster you connect to to
728      issue this command.  You can ignore the result returned by the function;
729      but if it reports an error, deal with that before proceeding.
730     </para>
731
732     <para>
733      By default, <function>pg_start_backup</> can take a long time to finish.
734      This is because it performs a checkpoint, and the I/O
735      required for the checkpoint will be spread out over a significant
736      period of time, by default half your inter-checkpoint interval
737      (see the configuration parameter
738      <xref linkend="guc-checkpoint-completion-target">).  Usually
739      this is what you want, because it minimizes the impact on query
740      processing.  If you just want to start the backup as soon as
741      possible, use:
742 <programlisting>
743 SELECT pg_start_backup('label', true);
744 </programlisting>
745      This forces the checkpoint to be done as quickly as possible.
746     </para>
747    </listitem>
748    <listitem>
749     <para>
750      Perform the backup, using any convenient file-system-backup tool
751      such as <application>tar</> or <application>cpio</>.  It is neither
752      necessary nor desirable to stop normal operation of the database
753      while you do this.
754     </para>
755    </listitem>
756    <listitem>
757     <para>
758      Again connect to the database as a superuser, and issue the command:
759 <programlisting>
760 SELECT pg_stop_backup();
761 </programlisting>
762      This terminates the backup mode and performs an automatic switch to
763      the next WAL segment.  The reason for the switch is to arrange that
764      the last WAL segment file written during the backup interval is
765      immediately ready to archive.
766     </para>
767    </listitem>
768    <listitem>
769     <para>
770      Once the WAL segment files used during the backup are archived, you are
771      done.  The file identified by <function>pg_stop_backup</>'s result is
772      the last segment that is required to form a complete set of backup files.
773      <function>pg_stop_backup</> does not return until the last segment has
774      been archived.
775      Archiving of these files happens automatically since you have
776      already configured <varname>archive_command</>. In most cases this
777      happens quickly, but you are advised to monitor your archive
778      system to ensure there are no delays.
779      If the archive process has fallen behind
780      because of failures of the archive command, it will keep retrying
781      until the archive succeeds and the backup is complete.
782      If you wish to place a time limit on the execution of
783      <function>pg_stop_backup</>, set an appropriate
784      <varname>statement_timeout</varname> value.
785     </para>
786    </listitem>
787   </orderedlist>
788    </para>
789
790    <para>
791     Some backup tools that you might wish to use emit warnings or errors
792     if the files they are trying to copy change while the copy proceeds.
793     This situation is normal, and not an error, when taking a base backup
794     of an active database; so you need to ensure that you can distinguish
795     complaints of this sort from real errors.  For example, some versions
796     of <application>rsync</> return a separate exit code for
797     <quote>vanished source files</>, and you can write a driver script to
798     accept this exit code as a non-error case.  Also, some versions of
799     GNU <application>tar</> return an error code indistinguishable from
800     a fatal error if a file was truncated while <application>tar</> was
801     copying it.  Fortunately, GNU <application>tar</> versions 1.16 and
802     later exit with <literal>1</> if a file was changed during the backup,
803     and <literal>2</> for other errors.
804    </para>
805
806    <para>
807     It is not necessary to be very concerned about the amount of time elapsed
808     between <function>pg_start_backup</> and the start of the actual backup,
809     nor between the end of the backup and <function>pg_stop_backup</>; a
810     few minutes' delay won't hurt anything.  (However, if you normally run the
811     server with <varname>full_page_writes</> disabled, you might notice a drop
812     in performance between <function>pg_start_backup</> and
813     <function>pg_stop_backup</>, since <varname>full_page_writes</> is
814     effectively forced on during backup mode.)  You must ensure that these
815     steps are carried out in sequence without any possible
816     overlap, or you will invalidate the backup.
817    </para>
818
819    <para>
820     Be certain that your backup dump includes all of the files underneath
821     the database cluster directory (e.g., <filename>/usr/local/pgsql/data</>).
822     If you are using tablespaces that do not reside underneath this directory,
823     be careful to include them as well (and be sure that your backup dump
824     archives symbolic links as links, otherwise the restore will mess up
825     your tablespaces).
826    </para>
827
828    <para>
829     You can, however, omit from the backup dump the files within the
830     <filename>pg_xlog/</> subdirectory of the cluster directory.  This
831     slight complication is worthwhile because it reduces the risk
832     of mistakes when restoring.  This is easy to arrange if
833     <filename>pg_xlog/</> is a symbolic link pointing to someplace outside
834     the cluster directory, which is a common setup anyway for performance
835     reasons.
836    </para>
837
838    <para>
839     To make use of the backup, you will need to keep around all the WAL
840     segment files generated during and after the file system backup.
841     To aid you in doing this, the <function>pg_stop_backup</> function
842     creates a <firstterm>backup history file</> that is immediately
843     stored into the WAL archive area. This file is named after the first
844     WAL segment file that you need to have to make use of the backup.
845     For example, if the starting WAL file is
846     <literal>0000000100001234000055CD</> the backup history file will be
847     named something like
848     <literal>0000000100001234000055CD.007C9330.backup</>. (The second
849     part of the file name stands for an exact position within the WAL
850     file, and can ordinarily be ignored.) Once you have safely archived
851     the file system backup and the WAL segment files used during the
852     backup (as specified in the backup history file), all archived WAL
853     segments with names numerically less are no longer needed to recover
854     the file system backup and can be deleted. However, you should
855     consider keeping several backup sets to be absolutely certain that
856     you can recover your data.
857    </para>
858
859    <para>
860     The backup history file is just a small text file. It contains the
861     label string you gave to <function>pg_start_backup</>, as well as
862     the starting and ending times and WAL segments of the backup.
863     If you used the label to identify where the associated dump file is kept,
864     then the archived history file is enough to tell you which dump file to
865     restore, should you need to do so.
866    </para>
867
868    <para>
869     Since you have to keep around all the archived WAL files back to your
870     last base backup, the interval between base backups should usually be
871     chosen based on how much storage you want to expend on archived WAL
872     files.  You should also consider how long you are prepared to spend
873     recovering, if recovery should be necessary &mdash; the system will have to
874     replay all those WAL segments, and that could take awhile if it has
875     been a long time since the last base backup.
876    </para>
877
878    <para>
879     It's also worth noting that the <function>pg_start_backup</> function
880     makes a file named <filename>backup_label</> in the database cluster
881     directory, which is then removed again by <function>pg_stop_backup</>.
882     This file will of course be archived as a part of your backup dump file.
883     The backup label file includes the label string you gave to
884     <function>pg_start_backup</>, as well as the time at which
885     <function>pg_start_backup</> was run, and the name of the starting WAL
886     file.  In case of confusion it will
887     therefore be possible to look inside a backup dump file and determine
888     exactly which backup session the dump file came from.
889    </para>
890
891    <para>
892     It is also possible to make a backup dump while the server is
893     stopped.  In this case, you obviously cannot use
894     <function>pg_start_backup</> or <function>pg_stop_backup</>, and
895     you will therefore be left to your own devices to keep track of which
896     backup dump is which and how far back the associated WAL files go.
897     It is generally better to follow the continuous archiving procedure above.
898    </para>
899   </sect2>
900
901   <sect2 id="backup-pitr-recovery">
902    <title>Recovering using a Continuous Archive Backup</title>
903
904    <para>
905     Okay, the worst has happened and you need to recover from your backup.
906     Here is the procedure:
907   <orderedlist>
908    <listitem>
909     <para>
910      Stop the server, if it's running.
911     </para>
912    </listitem>
913    <listitem>
914     <para>
915      If you have the space to do so,
916      copy the whole cluster data directory and any tablespaces to a temporary
917      location in case you need them later. Note that this precaution will
918      require that you have enough free space on your system to hold two
919      copies of your existing database. If you do not have enough space,
920      you need at the least to copy the contents of the <filename>pg_xlog</>
921      subdirectory of the cluster data directory, as it might contain logs which
922      were not archived before the system went down.
923     </para>
924    </listitem>
925    <listitem>
926     <para>
927      Clean out all existing files and subdirectories under the cluster data
928      directory and under the root directories of any tablespaces you are using.
929     </para>
930    </listitem>
931    <listitem>
932     <para>
933      Restore the database files from your base backup.  Be careful that they
934      are restored with the right ownership (the database system user, not
935      <literal>root</>!) and with the right permissions.  If you are using
936      tablespaces,
937      you should verify that the symbolic links in <filename>pg_tblspc/</>
938      were correctly restored.
939     </para>
940    </listitem>
941    <listitem>
942     <para>
943      Remove any files present in <filename>pg_xlog/</>; these came from the
944      backup dump and are therefore probably obsolete rather than current.
945      If you didn't archive <filename>pg_xlog/</> at all, then recreate it,
946      being careful to ensure that you re-establish it as a symbolic link
947      if you had it set up that way before.
948     </para>
949    </listitem>
950    <listitem>
951     <para>
952      If you had unarchived WAL segment files that you saved in step 2,
953      copy them into <filename>pg_xlog/</>.  (It is best to copy them,
954      not move them, so that you still have the unmodified files if a
955      problem occurs and you have to start over.)
956     </para>
957    </listitem>
958    <listitem>
959     <para>
960      Create a recovery command file <filename>recovery.conf</> in the cluster
961      data directory (see <xref linkend="recovery-config-settings">). You might
962      also want to temporarily modify <filename>pg_hba.conf</> to prevent
963      ordinary users from connecting until you are sure the recovery has worked.
964     </para>
965    </listitem>
966    <listitem>
967     <para>
968      Start the server.  The server will go into recovery mode and
969      proceed to read through the archived WAL files it needs.  Should the
970      recovery be terminated because of an external error, the server can
971      simply be restarted and it will continue recovery.  Upon completion
972      of the recovery process, the server will rename
973      <filename>recovery.conf</> to <filename>recovery.done</> (to prevent
974      accidentally re-entering recovery mode in case of a crash later) and then
975      commence normal database operations.
976     </para>
977    </listitem>
978    <listitem>
979     <para>
980      Inspect the contents of the database to ensure you have recovered to
981      where you want to be.  If not, return to step 1.  If all is well,
982      let in your users by restoring <filename>pg_hba.conf</> to normal.
983     </para>
984    </listitem>
985   </orderedlist>
986    </para>
987
988    <para>
989     The key part of all this is to set up a recovery command file that
990     describes how you want to recover and how far the recovery should
991     run.  You can use <filename>recovery.conf.sample</> (normally
992     installed in the installation <filename>share/</> directory) as a
993     prototype.  The one thing that you absolutely must specify in
994     <filename>recovery.conf</> is the <varname>restore_command</>,
995     which tells <productname>PostgreSQL</> how to get back archived
996     WAL file segments.  Like the <varname>archive_command</>, this is
997     a shell command string.  It can contain <literal>%f</>, which is
998     replaced by the name of the desired log file, and <literal>%p</>,
999     which is replaced by the path name to copy the log file to.
1000     (The path name is relative to the current working directory,
1001     i.e., the cluster's data directory.)
1002     Write <literal>%%</> if you need to embed an actual <literal>%</>
1003     character in the command.  The simplest useful command is
1004     something like:
1005 <programlisting>
1006 restore_command = 'cp /mnt/server/archivedir/%f %p'
1007 </programlisting>
1008     which will copy previously archived WAL segments from the directory
1009     <filename>/mnt/server/archivedir</>.  You could of course use something
1010     much more complicated, perhaps even a shell script that requests the
1011     operator to mount an appropriate tape.
1012    </para>
1013
1014    <para>
1015     It is important that the command return nonzero exit status on failure.
1016     The command <emphasis>will</> be asked for files that are not present
1017     in the archive; it must return nonzero when so asked.  This is not an
1018     error condition.  Not all of the requested files will be WAL segment
1019     files; you should also expect requests for files with a suffix of
1020     <literal>.backup</> or <literal>.history</>. Also be aware that
1021     the base name of the <literal>%p</> path will be different from
1022     <literal>%f</>; do not expect them to be interchangeable.
1023    </para>
1024
1025    <para>
1026     WAL segments that cannot be found in the archive will be sought in
1027     <filename>pg_xlog/</>; this allows use of recent un-archived segments.
1028     However segments that are available from the archive will be used in
1029     preference to files in <filename>pg_xlog/</>.  The system will not
1030     overwrite the existing contents of <filename>pg_xlog/</> when retrieving
1031     archived files.
1032    </para>
1033
1034    <para>
1035     Normally, recovery will proceed through all available WAL segments,
1036     thereby restoring the database to the current point in time (or as
1037     close as we can get given the available WAL segments).  So a normal
1038     recovery will end with a <quote>file not found</> message, the exact text
1039     of the error message depending upon your choice of
1040     <varname>restore_command</>.  You may also see an error message
1041     at the start of recovery for a file named something like
1042     <filename>00000001.history</>.  This is also normal and does not
1043     indicate a problem in simple recovery situations. See
1044     <xref linkend="backup-timelines"> for discussion.
1045    </para>
1046
1047    <para>
1048     If you want to recover to some previous point in time (say, right before
1049     the junior DBA dropped your main transaction table), just specify the
1050     required stopping point in <filename>recovery.conf</>.  You can specify
1051     the stop point, known as the <quote>recovery target</>, either by
1052     date/time or by completion of a specific transaction ID.  As of this
1053     writing only the date/time option is very usable, since there are no tools
1054     to help you identify with any accuracy which transaction ID to use.
1055    </para>
1056
1057    <note>
1058      <para>
1059       The stop point must be after the ending time of the base backup, i.e.,
1060       the end time of <function>pg_stop_backup</>.  You cannot use a base backup
1061       to recover to a time when that backup was still going on.  (To
1062       recover to such a time, you must go back to your previous base backup
1063       and roll forward from there.)
1064      </para>
1065    </note>
1066
1067    <para>
1068     If recovery finds a corruption in the WAL data then recovery will
1069     complete at that point and the server will not start. In such a case the
1070     recovery process could be re-run from the beginning, specifying a
1071     <quote>recovery target</> before the point of corruption so that recovery
1072     can complete normally.
1073     If recovery fails for an external reason, such as a system crash or
1074     if the WAL archive has become inaccessible, then the recovery can simply
1075     be restarted and it will restart almost from where it failed.
1076     Recovery restart works much like checkpointing in normal operation:
1077     the server periodically forces all its state to disk, and then updates
1078     the <filename>pg_control</> file to indicate that the already-processed
1079     WAL data need not be scanned again.
1080    </para>
1081
1082
1083     <sect3 id="recovery-config-settings" xreflabel="Recovery Settings">
1084      <title>Recovery Settings</title>
1085
1086      <para>
1087       These settings can only be made in the <filename>recovery.conf</>
1088       file, and apply only for the duration of the recovery. They must be
1089       reset for any subsequent recovery you wish to perform. They cannot be
1090       changed once recovery has begun.
1091       The parameters for streaming replication are described in <xref
1092       linkend="replication-config-settings">.
1093      </para>
1094
1095      <variablelist>
1096
1097      <varlistentry id="restore-command" xreflabel="restore_command">
1098       <term><varname>restore_command</varname> (<type>string</type>)</term>
1099       <listitem>
1100        <para>
1101         The shell command to execute to retrieve an archived segment of
1102         the WAL file series. This parameter is required for archive recovery,
1103         but optional for streaming replication.
1104         Any <literal>%f</> in the string is
1105         replaced by the name of the file to retrieve from the archive,
1106         and any <literal>%p</> is replaced by the path name to copy
1107         it to on the server.
1108         (The path name is relative to the current working directory,
1109         i.e., the cluster's data directory.)
1110         Any <literal>%r</> is replaced by the name of the file containing the
1111         last valid restart point. That is the earliest file that must be kept
1112         to allow a restore to be restartable, so this information can be used
1113         to truncate the archive to just the minimum required to support
1114         restart from the current restore. <literal>%r</> would typically be
1115         used in a warm-standby configuration
1116         (see <xref linkend="warm-standby">).
1117         Write <literal>%%</> to embed an actual <literal>%</> character
1118         in the command.
1119        </para>
1120        <para>
1121         It is important for the command to return a zero exit status if and
1122         only if it succeeds.  The command <emphasis>will</> be asked for file
1123         names that are not present in the archive; it must return nonzero
1124         when so asked.  Examples:
1125 <programlisting>
1126 restore_command = 'cp /mnt/server/archivedir/%f "%p"'
1127 restore_command = 'copy "C:\\server\\archivedir\\%f" "%p"'  # Windows
1128 </programlisting>
1129        </para>
1130       </listitem>
1131      </varlistentry>
1132
1133      <varlistentry id="recovery-end-command" xreflabel="recovery_end_command">
1134       <term><varname>recovery_end_command</varname> (<type>string</type>)</term>
1135       <listitem>
1136        <para>
1137         This parameter specifies a shell command that will be executed once only
1138         at the end of recovery. This parameter is optional. The purpose of the
1139         <varname>recovery_end_command</> is to provide a mechanism for cleanup
1140         following replication or recovery.
1141         Any <literal>%r</> is replaced by the name of the file
1142         containing the last valid restart point. That is the earliest file that
1143         must be kept to allow a restore to be restartable, so this information
1144         can be used to truncate the archive to just the minimum required to
1145         support restart from the current restore. <literal>%r</> would
1146         typically be used in a warm-standby configuration
1147         (see <xref linkend="warm-standby">).
1148         Write <literal>%%</> to embed an actual <literal>%</> character
1149         in the command.
1150        </para>
1151        <para>
1152         If the command returns a non-zero exit status then a WARNING log
1153         message will be written and the database will proceed to start up
1154         anyway.  An exception is that if the command was terminated by a
1155         signal, the database will not proceed with startup.
1156        </para>
1157       </listitem>
1158      </varlistentry>
1159
1160      <varlistentry id="recovery-target-time" xreflabel="recovery_target_time">
1161       <term><varname>recovery_target_time</varname>
1162            (<type>timestamp</type>)
1163       </term>
1164       <listitem>
1165        <para>
1166         This parameter specifies the time stamp up to which recovery
1167         will proceed.
1168         At most one of <varname>recovery_target_time</> and
1169         <xref linkend="recovery-target-xid"> can be specified.
1170         The default is to recover to the end of the WAL log.
1171         The precise stopping point is also influenced by
1172         <xref linkend="recovery-target-inclusive">.
1173        </para>
1174       </listitem>
1175      </varlistentry>
1176
1177      <varlistentry id="recovery-target-xid" xreflabel="recovery_target_xid">
1178       <term><varname>recovery_target_xid</varname> (<type>string</type>)</term>
1179       <listitem>
1180        <para>
1181         This parameter specifies the transaction ID up to which recovery
1182         will proceed. Keep in mind
1183         that while transaction IDs are assigned sequentially at transaction
1184         start, transactions can complete in a different numeric order.
1185         The transactions that will be recovered are those that committed
1186         before (and optionally including) the specified one.
1187         At most one of <varname>recovery_target_xid</> and
1188         <xref linkend="recovery-target-time"> can be specified.
1189         The default is to recover to the end of the WAL log.
1190         The precise stopping point is also influenced by
1191         <xref linkend="recovery-target-inclusive">.
1192        </para>
1193       </listitem>
1194      </varlistentry>
1195
1196      <varlistentry id="recovery-target-inclusive"
1197                    xreflabel="recovery_target_inclusive">
1198       <term><varname>recovery_target_inclusive</varname>
1199         (<type>boolean</type>)
1200       </term>
1201       <listitem>
1202        <para>
1203         Specifies whether we stop just after the specified recovery target
1204         (<literal>true</literal>), or just before the recovery target
1205         (<literal>false</literal>).
1206         Applies to both <xref linkend="recovery-target-time">
1207         and <xref linkend="recovery-target-xid">, whichever one is
1208         specified for this recovery.  This indicates whether transactions
1209         having exactly the target commit time or ID, respectively, will
1210         be included in the recovery.  Default is <literal>true</>.
1211        </para>
1212       </listitem>
1213      </varlistentry>
1214
1215      <varlistentry id="recovery-target-timeline"
1216                    xreflabel="recovery_target_timeline">
1217       <term><varname>recovery_target_timeline</varname>
1218         (<type>string</type>)
1219       </term>
1220       <listitem>
1221        <para>
1222         Specifies recovering into a particular timeline.  The default is
1223         to recover along the same timeline that was current when the
1224         base backup was taken.  You would only need to set this parameter
1225         in complex re-recovery situations, where you need to return to
1226         a state that itself was reached after a point-in-time recovery.
1227         See <xref linkend="backup-timelines"> for discussion.
1228        </para>
1229       </listitem>
1230      </varlistentry>
1231
1232    </variablelist>
1233
1234    </sect3>
1235
1236   </sect2>
1237
1238   <sect2 id="backup-timelines">
1239    <title>Timelines</title>
1240
1241   <indexterm zone="backup">
1242    <primary>timelines</primary>
1243   </indexterm>
1244
1245    <para>
1246     The ability to restore the database to a previous point in time creates
1247     some complexities that are akin to science-fiction stories about time
1248     travel and parallel universes.  In the original history of the database,
1249     perhaps you dropped a critical table at 5:15PM on Tuesday evening, but
1250     didn't realize your mistake until Wednesday noon.
1251     Unfazed, you get out your backup, restore to the point-in-time 5:14PM
1252     Tuesday evening, and are up and running.  In <emphasis>this</> history of
1253     the database universe, you never dropped the table at all.  But suppose
1254     you later realize this wasn't such a great idea after all, and would like
1255     to return to sometime Wednesday morning in the original history.
1256     You won't be able
1257     to if, while your database was up-and-running, it overwrote some of the
1258     sequence of WAL segment files that led up to the time you now wish you
1259     could get back to.  So you really want to distinguish the series of
1260     WAL records generated after you've done a point-in-time recovery from
1261     those that were generated in the original database history.
1262    </para>
1263
1264    <para>
1265     To deal with these problems, <productname>PostgreSQL</> has a notion
1266     of <firstterm>timelines</>.  Whenever an archive recovery is completed,
1267     a new timeline is created to identify the series of WAL records
1268     generated after that recovery.  The timeline
1269     ID number is part of WAL segment file names, and so a new timeline does
1270     not overwrite the WAL data generated by previous timelines.  It is
1271     in fact possible to archive many different timelines.  While that might
1272     seem like a useless feature, it's often a lifesaver.  Consider the
1273     situation where you aren't quite sure what point-in-time to recover to,
1274     and so have to do several point-in-time recoveries by trial and error
1275     until you find the best place to branch off from the old history.  Without
1276     timelines this process would soon generate an unmanageable mess.  With
1277     timelines, you can recover to <emphasis>any</> prior state, including
1278     states in timeline branches that you later abandoned.
1279    </para>
1280
1281    <para>
1282     Each time a new timeline is created, <productname>PostgreSQL</> creates
1283     a <quote>timeline history</> file that shows which timeline it branched
1284     off from and when.  These history files are necessary to allow the system
1285     to pick the right WAL segment files when recovering from an archive that
1286     contains multiple timelines.  Therefore, they are archived into the WAL
1287     archive area just like WAL segment files.  The history files are just
1288     small text files, so it's cheap and appropriate to keep them around
1289     indefinitely (unlike the segment files which are large).  You can, if
1290     you like, add comments to a history file to make your own notes about
1291     how and why this particular timeline came to be.  Such comments will be
1292     especially valuable when you have a thicket of different timelines as
1293     a result of experimentation.
1294    </para>
1295
1296    <para>
1297     The default behavior of recovery is to recover along the same timeline
1298     that was current when the base backup was taken.  If you want to recover
1299     into some child timeline (that is, you want to return to some state that
1300     was itself generated after a recovery attempt), you need to specify the
1301     target timeline ID in <filename>recovery.conf</>.  You cannot recover into
1302     timelines that branched off earlier than the base backup.
1303    </para>
1304   </sect2>
1305
1306   <sect2 id="backup-tips">
1307    <title>Tips and Examples</title>
1308
1309    <para>
1310     Some tips for configuring continuous archiving are given here.
1311    </para>
1312
1313     <sect3 id="backup-standalone">
1314      <title>Standalone hot backups</title>
1315
1316      <para>
1317       It is possible to use <productname>PostgreSQL</>'s backup facilities to
1318       produce standalone hot backups. These are backups that cannot be used
1319       for point-in-time recovery, yet are typically much faster to backup and
1320       restore than <application>pg_dump</> dumps.  (They are also much larger
1321       than <application>pg_dump</> dumps, so in some cases the speed advantage
1322       could be negated.)
1323      </para>
1324
1325      <para>
1326       To prepare for standalone hot backups, set <varname>archive_mode</> to
1327       <literal>on</>, and set up an <varname>archive_command</> that performs
1328       archiving only when a <quote>switch file</> exists.  For example:
1329 <programlisting>
1330 archive_command = 'test ! -f /var/lib/pgsql/backup_in_progress || cp -i %p /var/lib/pgsql/archive/%f &lt; /dev/null'
1331 </programlisting>
1332       This command will perform archiving when
1333       <filename>/var/lib/pgsql/backup_in_progress</> exists, and otherwise
1334       silently return zero exit status (allowing <productname>PostgreSQL</>
1335       to recycle the unwanted WAL file).
1336      </para>
1337
1338      <para>
1339       With this preparation, a backup can be taken using a script like the
1340       following:
1341 <programlisting>
1342 touch /var/lib/pgsql/backup_in_progress
1343 psql -c "select pg_start_backup('hot_backup');"
1344 tar -cf /var/lib/pgsql/backup.tar /var/lib/pgsql/data/
1345 psql -c "select pg_stop_backup();"
1346 rm /var/lib/pgsql/backup_in_progress
1347 tar -rf /var/lib/pgsql/backup.tar /var/lib/pgsql/archive/
1348 </programlisting>
1349       The switch file <filename>/var/lib/pgsql/backup_in_progress</> is
1350       created first, enabling archiving of completed WAL files to occur.
1351       After the backup the switch file is removed. Archived WAL files are
1352       then added to the backup so that both base backup and all required
1353       WAL files are part of the same <application>tar</> file.
1354       Please remember to add error handling to your backup scripts.
1355      </para>
1356
1357      <para>
1358       If archive storage size is a concern, use <application>pg_compresslog</>,
1359       <ulink url="http://pglesslog.projects.postgresql.org"></ulink>, to
1360       remove unnecessary <xref linkend="guc-full-page-writes"> and trailing
1361       space from the WAL files.  You can then use
1362       <application>gzip</application> to further compress the output of
1363       <application>pg_compresslog</>:
1364 <programlisting>
1365 archive_command = 'pg_compresslog %p - | gzip &gt; /var/lib/pgsql/archive/%f'
1366 </programlisting>
1367       You will then need to use <application>gunzip</> and
1368       <application>pg_decompresslog</> during recovery:
1369 <programlisting>
1370 restore_command = 'gunzip &lt; /mnt/server/archivedir/%f | pg_decompresslog - %p'
1371 </programlisting>
1372      </para>
1373     </sect3>
1374
1375     <sect3 id="backup-scripts">
1376      <title><varname>archive_command</varname> scripts</title>
1377
1378      <para>
1379       Many people choose to use scripts to define their
1380       <varname>archive_command</varname>, so that their
1381       <filename>postgresql.conf</> entry looks very simple:
1382 <programlisting>
1383 archive_command = 'local_backup_script.sh'
1384 </programlisting>
1385       Using a separate script file is advisable any time you want to use
1386       more than a single command in the archiving process.
1387       This allows all complexity to be managed within the script, which
1388       can be written in a popular scripting language such as
1389       <application>bash</> or <application>perl</>.
1390       Any messages written to <literal>stderr</> from the script will appear
1391       in the database server log, allowing complex configurations to be
1392       diagnosed easily if they fail.
1393      </para>
1394
1395      <para>
1396       Examples of requirements that might be solved within a script include:
1397       <itemizedlist>
1398        <listitem>
1399         <para>
1400          Copying data to secure off-site data storage
1401         </para>
1402        </listitem>
1403        <listitem>
1404         <para>
1405          Batching WAL files so that they are transferred every three hours,
1406          rather than one at a time
1407         </para>
1408        </listitem>
1409        <listitem>
1410         <para>
1411          Interfacing with other backup and recovery software
1412         </para>
1413        </listitem>
1414        <listitem>
1415         <para>
1416          Interfacing with monitoring software to report errors
1417         </para>
1418        </listitem>
1419       </itemizedlist>
1420      </para>
1421     </sect3>
1422   </sect2>
1423
1424   <sect2 id="continuous-archiving-caveats">
1425    <title>Caveats</title>
1426
1427    <para>
1428     At this writing, there are several limitations of the continuous archiving
1429     technique.  These will probably be fixed in future releases:
1430
1431   <itemizedlist>
1432    <listitem>
1433     <para>
1434      Operations on hash indexes are not presently WAL-logged, so
1435      replay will not update these indexes.  This will mean that any new inserts
1436      will be ignored by the index, updated rows will apparently disappear and
1437      deleted rows will still retain pointers. In other words, if you modify a
1438      table with a hash index on it then you will get incorrect query results
1439      on a standby server.  When recovery completes it is recommended that you
1440      manually <xref linkend="sql-reindex" endterm="sql-reindex-title">
1441      each such index after completing a recovery operation.
1442     </para>
1443    </listitem>
1444
1445    <listitem>
1446     <para>
1447      If a <xref linkend="sql-createdatabase" endterm="sql-createdatabase-title">
1448      command is executed while a base backup is being taken, and then
1449      the template database that the <command>CREATE DATABASE</> copied
1450      is modified while the base backup is still in progress, it is
1451      possible that recovery will cause those modifications to be
1452      propagated into the created database as well.  This is of course
1453      undesirable.  To avoid this risk, it is best not to modify any
1454      template databases while taking a base backup.
1455     </para>
1456    </listitem>
1457
1458    <listitem>
1459     <para>
1460      <xref linkend="sql-createtablespace" endterm="sql-createtablespace-title">
1461      commands are WAL-logged with the literal absolute path, and will
1462      therefore be replayed as tablespace creations with the same
1463      absolute path.  This might be undesirable if the log is being
1464      replayed on a different machine.  It can be dangerous even if the
1465      log is being replayed on the same machine, but into a new data
1466      directory: the replay will still overwrite the contents of the
1467      original tablespace.  To avoid potential gotchas of this sort,
1468      the best practice is to take a new base backup after creating or
1469      dropping tablespaces.
1470     </para>
1471    </listitem>
1472   </itemizedlist>
1473    </para>
1474
1475    <para>
1476     It should also be noted that the default <acronym>WAL</acronym>
1477     format is fairly bulky since it includes many disk page snapshots.
1478     These page snapshots are designed to support crash recovery, since
1479     we might need to fix partially-written disk pages.  Depending on
1480     your system hardware and software, the risk of partial writes might
1481     be small enough to ignore, in which case you can significantly
1482     reduce the total volume of archived logs by turning off page
1483     snapshots using the <xref linkend="guc-full-page-writes">
1484     parameter.  (Read the notes and warnings in <xref linkend="wal">
1485     before you do so.)  Turning off page snapshots does not prevent
1486     use of the logs for PITR operations.  An area for future
1487     development is to compress archived WAL data by removing
1488     unnecessary page copies even when <varname>full_page_writes</> is
1489     on.  In the meantime, administrators might wish to reduce the number
1490     of page snapshots included in WAL by increasing the checkpoint
1491     interval parameters as much as feasible.
1492    </para>
1493   </sect2>
1494  </sect1>
1495
1496  <sect1 id="warm-standby">
1497   <title>Warm Standby Servers for High Availability</title>
1498
1499   <indexterm zone="backup">
1500    <primary>warm standby</primary>
1501   </indexterm>
1502
1503   <indexterm zone="backup">
1504    <primary>PITR standby</primary>
1505   </indexterm>
1506
1507   <indexterm zone="backup">
1508    <primary>standby server</primary>
1509   </indexterm>
1510
1511   <indexterm zone="backup">
1512    <primary>log shipping</primary>
1513   </indexterm>
1514
1515   <indexterm zone="backup">
1516    <primary>witness server</primary>
1517   </indexterm>
1518
1519   <indexterm zone="backup">
1520    <primary>STONITH</primary>
1521   </indexterm>
1522
1523   <indexterm zone="backup">
1524    <primary>high availability</primary>
1525   </indexterm>
1526
1527   <para>
1528    Continuous archiving can be used to create a <firstterm>high
1529    availability</> (HA) cluster configuration with one or more
1530    <firstterm>standby servers</> ready to take over operations if the
1531    primary server fails. This capability is widely referred to as
1532    <firstterm>warm standby</> or <firstterm>log shipping</>.
1533   </para>
1534
1535   <para>
1536    The primary and standby server work together to provide this capability,
1537    though the servers are only loosely coupled. The primary server operates
1538    in continuous archiving mode, while each standby server operates in
1539    continuous recovery mode, reading the WAL files from the primary. No
1540    changes to the database tables are required to enable this capability,
1541    so it offers low administration overhead in comparison with some other
1542    replication approaches. This configuration also has relatively low
1543    performance impact on the primary server.
1544   </para>
1545
1546   <para>
1547    Directly moving WAL records from one database server to another
1548    is typically described as log shipping. <productname>PostgreSQL</>
1549    implements file-based log shipping, which means that WAL records are
1550    transferred one file (WAL segment) at a time. WAL files (16MB) can be
1551    shipped easily and cheaply over any distance, whether it be to an
1552    adjacent system, another system on the same site or another system on
1553    the far side of the globe. The bandwidth required for this technique
1554    varies according to the transaction rate of the primary server.
1555    Record-based log shipping is also possible with custom-developed
1556    procedures, as discussed in <xref linkend="warm-standby-record">.
1557   </para>
1558
1559   <para>
1560    It should be noted that the log shipping is asynchronous, i.e., the WAL
1561    records are shipped after transaction commit. As a result there is a
1562    window for data loss should the primary server suffer a catastrophic
1563    failure: transactions not yet shipped will be lost.  The length of the
1564    window of data loss can be limited by use of the
1565    <varname>archive_timeout</varname> parameter, which can be set as low
1566    as a few seconds if required.  However such low settings will
1567    substantially increase the bandwidth requirements for file shipping.
1568    If you need a window of less than a minute or so, it's probably better
1569    to look into record-based log shipping.
1570   </para>
1571
1572   <para>
1573    The standby server is not available for access, since it is continually
1574    performing recovery processing. Recovery performance is sufficiently
1575    good that the standby will typically be only moments away from full
1576    availability once it has been activated. As a result, we refer to this
1577    capability as a warm standby configuration that offers high
1578    availability. Restoring a server from an archived base backup and
1579    rollforward will take considerably longer, so that technique only
1580    offers a solution for disaster recovery, not high availability.
1581   </para>
1582
1583   <sect2 id="warm-standby-planning">
1584    <title>Planning</title>
1585
1586    <para>
1587     It is usually wise to create the primary and standby servers
1588     so that they are as similar as possible, at least from the
1589     perspective of the database server.  In particular, the path names
1590     associated with tablespaces will be passed across as-is, so both
1591     primary and standby servers must have the same mount paths for
1592     tablespaces if that feature is used.  Keep in mind that if
1593     <xref linkend="sql-createtablespace" endterm="sql-createtablespace-title">
1594     is executed on the primary, any new mount point needed for it must
1595     be created on both the primary and all standby servers before the command
1596     is executed. Hardware need not be exactly the same, but experience shows
1597     that maintaining two identical systems is easier than maintaining two
1598     dissimilar ones over the lifetime of the application and system.
1599     In any case the hardware architecture must be the same &mdash; shipping
1600     from, say, a 32-bit to a 64-bit system will not work.
1601    </para>
1602
1603    <para>
1604     In general, log shipping between servers running different major
1605     <productname>PostgreSQL</> release
1606     levels will not be possible. It is the policy of the PostgreSQL Global
1607     Development Group not to make changes to disk formats during minor release
1608     upgrades, so it is likely that running different minor release levels
1609     on primary and standby servers will work successfully. However, no
1610     formal support for that is offered and you are advised to keep primary
1611     and standby servers at the same release level as much as possible.
1612     When updating to a new minor release, the safest policy is to update
1613     the standby servers first &mdash; a new minor release is more likely
1614     to be able to read WAL files from a previous minor release than vice
1615     versa.
1616    </para>
1617
1618    <para>
1619     There is no special mode required to enable a standby server. The
1620     operations that occur on both primary and standby servers are entirely
1621     normal continuous archiving and recovery tasks. The only point of
1622     contact between the two database servers is the archive of WAL files
1623     that both share: primary writing to the archive, standby reading from
1624     the archive. Care must be taken to ensure that WAL archives for separate
1625     primary servers do not become mixed together or confused. The archive
1626     need not be large, if it is only required for the standby operation.
1627    </para>
1628
1629    <para>
1630     The magic that makes the two loosely coupled servers work together is
1631     simply a <varname>restore_command</> used on the standby that,
1632     when asked for the next WAL file, waits for it to become available from
1633     the primary. The <varname>restore_command</> is specified in the
1634     <filename>recovery.conf</> file on the standby server. Normal recovery
1635     processing would request a file from the WAL archive, reporting failure
1636     if the file was unavailable.  For standby processing it is normal for
1637     the next WAL file to be unavailable, so we must be patient and wait for
1638     it to appear. For files ending in <literal>.backup</> or
1639     <literal>.history</> there is no need to wait, and a non-zero return
1640     code must be returned. A waiting <varname>restore_command</> can be
1641     written as a custom script that loops after polling for the existence of
1642     the next WAL file. There must also be some way to trigger failover, which
1643     should interrupt the <varname>restore_command</>, break the loop and
1644     return a file-not-found error to the standby server. This ends recovery
1645     and the standby will then come up as a normal server.
1646    </para>
1647
1648    <para>
1649     Pseudocode for a suitable <varname>restore_command</> is:
1650 <programlisting>
1651 triggered = false;
1652 while (!NextWALFileReady() &amp;&amp; !triggered)
1653 {
1654     sleep(100000L);         /* wait for ~0.1 sec */
1655     if (CheckForExternalTrigger())
1656         triggered = true;
1657 }
1658 if (!triggered)
1659         CopyWALFileForRecovery();
1660 </programlisting>
1661    </para>
1662
1663    <para>
1664     A working example of a waiting <varname>restore_command</> is provided
1665     as a <filename>contrib</> module named <application>pg_standby</>. It
1666     should be used as a reference on how to correctly implement the logic
1667     described above. It can also be extended as needed to support specific
1668     configurations or environments.
1669    </para>
1670
1671    <para>
1672     <productname>PostgreSQL</productname> does not provide the system
1673     software required to identify a failure on the primary and notify
1674     the standby system and then the standby database server. Many such
1675     tools exist and are well integrated with other aspects required for
1676     successful failover, such as IP address migration.
1677    </para>
1678
1679    <para>
1680     The means for triggering failover is an important part of planning and
1681     design. The <varname>restore_command</> is executed in full once
1682     for each WAL file. The process running the <varname>restore_command</>
1683     is therefore created and dies for each file, so there is no daemon
1684     or server process and so we cannot use signals and a signal
1685     handler. A more permanent notification is required to trigger the
1686     failover. It is possible to use a simple timeout facility,
1687     especially if used in conjunction with a known
1688     <varname>archive_timeout</> setting on the primary. This is
1689     somewhat error prone since a network problem or busy primary server might
1690     be sufficient to initiate failover. A notification mechanism such
1691     as the explicit creation of a trigger file is less error prone, if
1692     this can be arranged.
1693    </para>
1694
1695    <para>
1696     The size of the WAL archive can be minimized by using the <literal>%r</>
1697     option of the <varname>restore_command</>. This option specifies the
1698     last archive file name that needs to be kept to allow the recovery to
1699     restart correctly. This can be used to truncate the archive once
1700     files are no longer required, if the archive is writable from the
1701     standby server.
1702    </para>
1703   </sect2>
1704
1705   <sect2 id="warm-standby-config">
1706    <title>Implementation</title>
1707
1708    <para>
1709     The short procedure for configuring a standby server is as follows. For
1710     full details of each step, refer to previous sections as noted.
1711     <orderedlist>
1712      <listitem>
1713       <para>
1714        Set up primary and standby systems as near identically as
1715        possible, including two identical copies of
1716        <productname>PostgreSQL</> at the same release level.
1717       </para>
1718      </listitem>
1719      <listitem>
1720       <para>
1721        Set up continuous archiving from the primary to a WAL archive located
1722        in a directory on the standby server. Ensure that
1723        <xref linkend="guc-archive-mode">,
1724        <xref linkend="guc-archive-command"> and
1725        <xref linkend="guc-archive-timeout">
1726        are set appropriately on the primary
1727        (see <xref linkend="backup-archiving-wal">).
1728       </para>
1729      </listitem>
1730      <listitem>
1731       <para>
1732        Make a base backup of the primary server (see <xref
1733        linkend="backup-base-backup">), and load this data onto the standby.
1734       </para>
1735      </listitem>
1736      <listitem>
1737       <para>
1738        Begin recovery on the standby server from the local WAL
1739        archive, using a <filename>recovery.conf</> that specifies a
1740        <varname>restore_command</> that waits as described
1741        previously (see <xref linkend="backup-pitr-recovery">).
1742       </para>
1743      </listitem>
1744     </orderedlist>
1745    </para>
1746
1747    <para>
1748     Recovery treats the WAL archive as read-only, so once a WAL file has
1749     been copied to the standby system it can be copied to tape at the same
1750     time as it is being read by the standby database server.
1751     Thus, running a standby server for high availability can be performed at
1752     the same time as files are stored for longer term disaster recovery
1753     purposes.
1754    </para>
1755
1756    <para>
1757     For testing purposes, it is possible to run both primary and standby
1758     servers on the same system. This does not provide any worthwhile
1759     improvement in server robustness, nor would it be described as HA.
1760    </para>
1761   </sect2>
1762
1763   <sect2 id="warm-standby-failover">
1764    <title>Failover</title>
1765
1766    <para>
1767     If the primary server fails then the standby server should begin
1768     failover procedures.
1769    </para>
1770
1771    <para>
1772     If the standby server fails then no failover need take place. If the
1773     standby server can be restarted, even some time later, then the recovery
1774     process can also be immediately restarted, taking advantage of
1775     restartable recovery. If the standby server cannot be restarted, then a
1776     full new standby server instance should be created.
1777    </para>
1778
1779    <para>
1780     If the primary server fails and then immediately restarts, you must have
1781     a mechanism for informing it that it is no longer the primary. This is
1782     sometimes known as STONITH (Shoot the Other Node In The Head), which is
1783     necessary to avoid situations where both systems think they are the
1784     primary, which will lead to confusion and ultimately data loss.
1785    </para>
1786
1787    <para>
1788     Many failover systems use just two systems, the primary and the standby,
1789     connected by some kind of heartbeat mechanism to continually verify the
1790     connectivity between the two and the viability of the primary. It is
1791     also possible to use a third system (called a witness server) to prevent
1792     some cases of inappropriate failover, but the additional complexity
1793     might not be worthwhile unless it is set up with sufficient care and
1794     rigorous testing.
1795    </para>
1796
1797    <para>
1798     Once failover to the standby occurs, we have only a
1799     single server in operation. This is known as a degenerate state.
1800     The former standby is now the primary, but the former primary is down
1801     and might stay down.  To return to normal operation we must
1802     fully recreate a standby server,
1803     either on the former primary system when it comes up, or on a third,
1804     possibly new, system. Once complete the primary and standby can be
1805     considered to have switched roles. Some people choose to use a third
1806     server to provide backup to the new primary until the new standby
1807     server is recreated,
1808     though clearly this complicates the system configuration and
1809     operational processes.
1810    </para>
1811
1812    <para>
1813     So, switching from primary to standby server can be fast but requires
1814     some time to re-prepare the failover cluster. Regular switching from
1815     primary to standby is useful, since it allows regular downtime on
1816     each system for maintenance. This also serves as a test of the
1817     failover mechanism to ensure that it will really work when you need it.
1818     Written administration procedures are advised.
1819    </para>
1820   </sect2>
1821
1822   <sect2 id="warm-standby-record">
1823    <title>Record-based Log Shipping</title>
1824
1825    <para>
1826     <productname>PostgreSQL</productname> directly supports file-based
1827     log shipping as described above. It is also possible to implement
1828     record-based log shipping, though this requires custom development.
1829    </para>
1830
1831    <para>
1832     An external program can call the <function>pg_xlogfile_name_offset()</>
1833     function (see <xref linkend="functions-admin">)
1834     to find out the file name and the exact byte offset within it of
1835     the current end of WAL.  It can then access the WAL file directly
1836     and copy the data from the last known end of WAL through the current end
1837     over to the standby server(s).  With this approach, the window for data
1838     loss is the polling cycle time of the copying program, which can be very
1839     small, but there is no wasted bandwidth from forcing partially-used
1840     segment files to be archived.  Note that the standby servers'
1841     <varname>restore_command</> scripts still deal in whole WAL files,
1842     so the incrementally copied data is not ordinarily made available to
1843     the standby servers.  It is of use only when the primary dies &mdash;
1844     then the last partial WAL file is fed to the standby before allowing
1845     it to come up.  So correct implementation of this process requires
1846     cooperation of the <varname>restore_command</> script with the data
1847     copying program.
1848    </para>
1849
1850    <para>
1851     Starting with <productname>PostgreSQL</> version 8.5, you can use
1852     streaming replication (see <xref linkend="streaming-replication">) to
1853     achieve the same with less effort.
1854    </para>
1855   </sect2>
1856
1857   <sect2 id="streaming-replication">
1858    <title>Streaming Replication</title>
1859
1860    <para>
1861     <productname>PostgreSQL</> includes a simple streaming replication
1862     mechanism, which lets the standby server to stay more up-to-date than
1863     file-based replication allows. The standby connects to the primary
1864     and the primary starts streaming WAL records from where the standby
1865     left off, and continues streaming them as they are generated, without
1866     waiting for the WAL file to be filled. So with streaming replication,
1867     <varname>archive_timeout</> does not need to be configured.
1868    </para>
1869
1870    <para>
1871     Streaming replication relies on file-based continuous archiving for
1872     making the base backup and for allowing a standby to catch up if it's
1873     disconnected from the primary for long enough for the primary to
1874     delete old WAL files still required by the standby.
1875    </para>
1876
1877    <sect3 id="streaming-replication-setup">
1878     <title>Setup</title>
1879     <para>
1880      The short procedure for configuring streaming replication is as follows.
1881      For full details of each step, refer to other sections as noted.
1882      <orderedlist>
1883       <listitem>
1884        <para>
1885         Set up primary and standby systems as near identically as possible,
1886         including two identical copies of <productname>PostgreSQL</> at the
1887         same release level.
1888        </para>
1889       </listitem>
1890      <listitem>
1891       <para>
1892        Set up continuous archiving from the primary to a WAL archive located
1893        in a directory on the standby server. Ensure that
1894        <xref linkend="guc-archive-mode">,
1895        <xref linkend="guc-archive-command"> and
1896        <xref linkend="guc-archive-timeout">
1897        are set appropriately on the primary
1898        (see <xref linkend="backup-archiving-wal">).
1899       </para>
1900      </listitem>
1901
1902      <listitem>
1903       <para>
1904        Set up connections and authentication so that the standby server can
1905        successfully connect to the pseudo <literal>replication</> database of
1906        the primary server (see
1907        <xref linkend="streaming-replication-authentication">). Ensure that
1908        <xref linkend="guc-listen-addresses"> and <filename>pg_hba.conf</> are
1909        configured appropriately on the primary.
1910       </para>
1911       <para>
1912        On systems that support the keepalive socket option, setting
1913        <xref linkend="guc-tcp-keepalives-idle">,
1914        <xref linkend="guc-tcp-keepalives-interval"> and
1915        <xref linkend="guc-tcp-keepalives-count"> helps you to find the
1916        troubles with replication (e.g., the network outage or the failure of
1917        the standby server) as soon as possible.
1918       </para>
1919      </listitem>
1920      <listitem>
1921       <para>
1922        Set the maximum number of concurrent connections from the standby servers
1923        (see <xref linkend="guc-max-wal-senders"> for details).
1924       </para>
1925      </listitem>
1926      <listitem>
1927       <para>
1928        Enable WAL archiving in the primary server because we need to make a base
1929        backup of it later (see <xref linkend="guc-archive-mode"> and
1930        <xref linkend="guc-archive-command"> for details).
1931       </para>
1932      </listitem>
1933      <listitem>
1934       <para>
1935        Start the <productname>PostgreSQL</> server on the primary.
1936       </para>
1937      </listitem>
1938      <listitem>
1939       <para>
1940        Make a base backup of the primary server (see
1941        <xref linkend="backup-base-backup">), and load this data onto the
1942        standby. Note that all files present in <filename>pg_xlog</>
1943        and <filename>pg_xlog/archive_status</> on the <emphasis>standby</>
1944        server should be removed because they might be obsolete.
1945       </para>
1946      </listitem>
1947      <listitem>
1948       <para>
1949        Set up WAL archiving, connections and authentication like the primary
1950        server, because the standby server might work as a primary server after
1951        failover. Ensure that your settings are consistent with the
1952        <emphasis>future</> environment after the primary and the standby
1953        server are interchanged by failover. If you're setting up the standby
1954        server for e.g reporting purposes, with no plans to fail over to it,
1955        configure the standby accordingly.
1956       </para>
1957      </listitem>
1958      <listitem>
1959       <para>
1960        Create a recovery command file <filename>recovery.conf</> in the data
1961        directory on the standby server.
1962       </para>
1963
1964       <variablelist id="replication-config-settings" xreflabel="Replication Settings">
1965        <varlistentry id="standby-mode" xreflabel="standby_mode">
1966         <term><varname>standby_mode</varname> (<type>boolean</type>)</term>
1967         <listitem>
1968          <para>
1969           Specifies whether to start the <productname>PostgreSQL</> server as
1970           a standby. If this parameter is <literal>on</>, the streaming
1971           replication is enabled and the standby server will try to connect
1972           to the primary to receive and apply WAL records continuously. The
1973           default is <literal>off</>, which allows only an archive recovery
1974           without replication. So, streaming replication requires this
1975           parameter to be explicitly set to <literal>on</>.
1976          </para>
1977         </listitem>
1978        </varlistentry>
1979        <varlistentry id="primary-conninfo" xreflabel="primary_conninfo">
1980         <term><varname>primary_conninfo</varname> (<type>string</type>)</term>
1981         <listitem>
1982          <para>
1983           Specifies a connection string which is used for the standby server
1984           to connect with the primary. This string is in the same format as
1985           described in <xref linkend="libpq-connect">. If any option is
1986           unspecified in this string, then the corresponding environment
1987           variable (see <xref linkend="libpq-envars">) is checked. If the
1988           environment variable is not set either, then the indicated built-in
1989           defaults are used.
1990          </para>
1991          <para>
1992           The built-in replication requires that a host name (or host address)
1993           or port number which the primary server listens on should be
1994           specified in this string, respectively. Also ensure that a role with
1995           the <literal>SUPERUSER</> and <literal>LOGIN</> privileges on the
1996           primary is set (see
1997           <xref linkend="streaming-replication-authentication">). Note that
1998           the password needs to be set if the primary demands password
1999           authentication.
2000          </para>
2001         </listitem>
2002        </varlistentry>
2003        <varlistentry id="trigger-file" xreflabel="trigger_file">
2004         <term><varname>trigger_file</varname> (<type>string</type>)</term>
2005         <listitem>
2006          <para>
2007           Specifies a trigger file whose presence activates the standby.
2008           If no trigger file is specified, the standby never exits
2009           recovery.
2010          </para>
2011         </listitem>
2012        </varlistentry>
2013       </variablelist>
2014      </listitem>
2015      <listitem>
2016       <para>
2017        Start the <productname>PostgreSQL</> server on the standby. The standby
2018        server will go into recovery mode and proceeds to receive WAL records
2019        from the primary and apply them continuously.
2020       </para>
2021      </listitem>
2022      </orderedlist>
2023     </para>
2024    </sect3>
2025    <sect3 id="streaming-replication-authentication">
2026     <title>Authentication</title>
2027     <para>
2028      It's very important that the access privilege for replication are set
2029      properly so that only trusted users can read the WAL stream, because it's
2030      easy to extract serious information from it.
2031     </para>
2032     <para>
2033      Only superuser is allowed to connect to the primary as the replication
2034      standby. So a role with the <literal>SUPERUSER</> and <literal>LOGIN</>
2035      privileges needs to be created in the primary.
2036     </para>
2037     <para>
2038      Client authentication for replication is controlled by the
2039      <filename>pg_hba.conf</> record specifying <literal>replication</> in the
2040      <replaceable>database</> field. For example, if the standby is running on
2041      host IP <literal>192.168.1.100</> and the superuser's name for replication
2042      is <literal>foo</>, the administrator can add the following line to the
2043      <filename>pg_hba.conf</> file on the primary.
2044
2045 <programlisting>
2046 # Allow the user "foo" from host 192.168.1.100 to connect to the primary
2047 # as a replication standby if the user's password is correctly supplied.
2048 #
2049 # TYPE  DATABASE    USER        CIDR-ADDRESS          METHOD
2050 host    replication foo         192.168.1.100/32      md5
2051 </programlisting>
2052     </para>
2053     <para>
2054      The host name and port number of the primary, user name to connect as,
2055      and password are specified in the <filename>recovery.conf</> file or
2056      the corresponding environment variable on the standby.
2057      For example, if the primary is running on host IP <literal>192.168.1.50</>,
2058      port <literal>5432</literal>, the superuser's name for replication is
2059      <literal>foo</>, and the password is <literal>foopass</>, the administrator
2060      can add the following line to the <filename>recovery.conf</> file on the
2061      standby.
2062
2063 <programlisting>
2064 # The standby connects to the primary that is running on host 192.168.1.50
2065 # and port 5432 as the user "foo" whose password is "foopass".
2066 primary_conninfo = 'host=192.168.1.50 port=5432 user=foo password=foopass'
2067 </programlisting>
2068     </para>
2069    </sect3>
2070   </sect2>
2071
2072   <sect2 id="backup-incremental-updated">
2073    <title>Incrementally Updated Backups</title>
2074
2075   <indexterm zone="backup">
2076    <primary>incrementally updated backups</primary>
2077   </indexterm>
2078
2079   <indexterm zone="backup">
2080    <primary>change accumulation</primary>
2081   </indexterm>
2082
2083    <para>
2084     In a warm standby configuration, it is possible to offload the expense of
2085     taking periodic base backups from the primary server; instead base backups
2086     can be made by backing
2087     up a standby server's files.  This concept is generally known as
2088     incrementally updated backups, log change accumulation, or more simply,
2089     change accumulation.
2090    </para>
2091
2092    <para>
2093     If we take a backup of the standby server's data directory while it is processing
2094     logs shipped from the primary, we will be able to reload that data and
2095     restart the standby's recovery process from the last restart point.
2096     We no longer need to keep WAL files from before the restart point.
2097     If we need to recover, it will be faster to recover from the incrementally
2098     updated backup than from the original base backup.
2099    </para>
2100
2101    <para>
2102     Since the standby server is not <quote>live</>, it is not possible to
2103     use <function>pg_start_backup()</> and <function>pg_stop_backup()</>
2104     to manage the backup process; it will be up to you to determine how
2105     far back you need to keep WAL segment files to have a recoverable
2106     backup.  You can do this by running <application>pg_controldata</>
2107     on the standby server to inspect the control file and determine the
2108     current checkpoint WAL location, or by using the
2109     <varname>log_checkpoints</> option to print values to the server log.
2110    </para>
2111   </sect2>
2112  </sect1>
2113
2114  <sect1 id="hot-standby">
2115   <title>Hot Standby</title>
2116
2117   <indexterm zone="backup">
2118    <primary>Hot Standby</primary>
2119   </indexterm>
2120
2121    <para>
2122     Hot Standby is the term used to describe the ability to connect to
2123     the server and run queries while the server is in archive recovery. This
2124     is useful for both log shipping replication and for restoring a backup
2125     to an exact state with great precision.
2126     The term Hot Standby also refers to the ability of the server to move
2127     from recovery through to normal running while users continue running
2128     queries and/or continue their connections.
2129    </para>
2130
2131    <para>
2132     Running queries in recovery is in many ways the same as normal running
2133     though there are a large number of usage and administrative points
2134     to note.
2135    </para>
2136
2137   <sect2 id="hot-standby-users">
2138    <title>User's Overview</title>
2139
2140    <para>
2141     Users can connect to the database while the server is in recovery
2142     and perform read-only queries. Read-only access to catalogs and views
2143     will also occur as normal.
2144    </para>
2145
2146    <para>
2147     The data on the standby takes some time to arrive from the primary server
2148     so there will be a measurable delay between primary and standby. Running the
2149     same query nearly simultaneously on both primary and standby might therefore
2150     return differing results. We say that data on the standby is eventually
2151     consistent with the primary.
2152     Queries executed on the standby will be correct with regard to the transactions
2153     that had been recovered at the start of the query, or start of first statement,
2154     in the case of serializable transactions. In comparison with the primary,
2155     the standby returns query results that could have been obtained on the primary
2156     at some exact moment in the past.
2157    </para>
2158
2159    <para>
2160     When a transaction is started in recovery, the parameter
2161     <varname>transaction_read_only</> will be forced to be true, regardless of the
2162     <varname>default_transaction_read_only</> setting in <filename>postgresql.conf</>.
2163     It can't be manually set to false either. As a result, all transactions
2164     started during recovery will be limited to read-only actions only. In all
2165     other ways, connected sessions will appear identical to sessions
2166     initiated during normal processing mode. There are no special commands
2167     required to initiate a connection at this time, so all interfaces
2168     work normally without change. After recovery finishes, the session
2169     will allow normal read-write transactions at the start of the next
2170     transaction, if these are requested.
2171    </para>
2172
2173    <para>
2174     Read-only here means "no writes to the permanent database tables".
2175     There are no problems with queries that make use of transient sort and
2176     work files.
2177    </para>
2178
2179    <para>
2180     The following actions are allowed
2181
2182     <itemizedlist>
2183      <listitem>
2184       <para>
2185        Query access - SELECT, COPY TO including views and SELECT RULEs
2186       </para>
2187      </listitem>
2188      <listitem>
2189       <para>
2190        Cursor commands - DECLARE, FETCH, CLOSE,
2191       </para>
2192      </listitem>
2193      <listitem>
2194       <para>
2195        Parameters - SHOW, SET, RESET
2196       </para>
2197      </listitem>
2198      <listitem>
2199       <para>
2200        Transaction management commands
2201         <itemizedlist>
2202          <listitem>
2203           <para>
2204            BEGIN, END, ABORT, START TRANSACTION
2205           </para>
2206          </listitem>
2207          <listitem>
2208           <para>
2209            SAVEPOINT, RELEASE, ROLLBACK TO SAVEPOINT
2210           </para>
2211          </listitem>
2212          <listitem>
2213           <para>
2214            EXCEPTION blocks and other internal subtransactions
2215           </para>
2216          </listitem>
2217         </itemizedlist>
2218       </para>
2219      </listitem>
2220      <listitem>
2221       <para>
2222        LOCK TABLE, though only when explicitly in one of these modes:
2223        ACCESS SHARE, ROW SHARE or ROW EXCLUSIVE.
2224       </para>
2225      </listitem>
2226      <listitem>
2227       <para>
2228        Plans and resources - PREPARE, EXECUTE, DEALLOCATE, DISCARD
2229       </para>
2230      </listitem>
2231      <listitem>
2232       <para>
2233        Plugins and extensions - LOAD
2234       </para>
2235      </listitem>
2236     </itemizedlist>
2237    </para>
2238
2239    <para>
2240     These actions produce error messages
2241
2242     <itemizedlist>
2243      <listitem>
2244       <para>
2245        Data Manipulation Language (DML) - INSERT, UPDATE, DELETE, COPY FROM, TRUNCATE.
2246        Note that there are no allowed actions that result in a trigger
2247        being executed during recovery.
2248       </para>
2249      </listitem>
2250      <listitem>
2251       <para>
2252        Data Definition Language (DDL) - CREATE, DROP, ALTER, COMMENT.
2253        This also applies to temporary tables currently because currently their
2254        definition causes writes to catalog tables.
2255       </para>
2256      </listitem>
2257      <listitem>
2258       <para>
2259        SELECT ... FOR SHARE | UPDATE which cause row locks to be written
2260       </para>
2261      </listitem>
2262      <listitem>
2263       <para>
2264        RULEs on SELECT statements that generate DML commands.
2265       </para>
2266      </listitem>
2267      <listitem>
2268       <para>
2269        LOCK TABLE, in short default form, since it requests ACCESS EXCLUSIVE MODE.
2270        LOCK TABLE that explicitly requests a mode higher than ROW EXCLUSIVE MODE.
2271       </para>
2272      </listitem>
2273      <listitem>
2274       <para>
2275        Transaction management commands that explicitly set non-read only state
2276         <itemizedlist>
2277          <listitem>
2278           <para>
2279             BEGIN READ WRITE,
2280             START TRANSACTION READ WRITE
2281           </para>
2282          </listitem>
2283          <listitem>
2284           <para>
2285             SET TRANSACTION READ WRITE,
2286             SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE
2287           </para>
2288          </listitem>
2289          <listitem>
2290           <para>
2291            SET transaction_read_only = off
2292           </para>
2293          </listitem>
2294         </itemizedlist>
2295       </para>
2296      </listitem>
2297      <listitem>
2298       <para>
2299        Two-phase commit commands - PREPARE TRANSACTION, COMMIT PREPARED,
2300        ROLLBACK PREPARED because even read-only transactions need to write
2301        WAL in the prepare phase (the first phase of two phase commit).
2302       </para>
2303      </listitem>
2304      <listitem>
2305       <para>
2306        sequence update - nextval()
2307       </para>
2308      </listitem>
2309      <listitem>
2310       <para>
2311        LISTEN, UNLISTEN, NOTIFY since they currently write to system tables
2312       </para>
2313      </listitem>
2314     </itemizedlist>
2315    </para>
2316
2317    <para>
2318     Note that current behaviour of read only transactions when not in
2319     recovery is to allow the last two actions, so there are small and
2320     subtle differences in behaviour between read-only transactions
2321     run on standby and during normal running.
2322     It is possible that the restrictions on LISTEN, UNLISTEN, NOTIFY and
2323     temporary tables may be lifted in a future release, if their internal
2324     implementation is altered to make this possible.
2325    </para>
2326
2327    <para>
2328     If failover or switchover occurs the database will switch to normal
2329     processing mode. Sessions will remain connected while the server
2330     changes mode. Current transactions will continue, though will remain
2331     read-only. After recovery is complete, it will be possible to initiate
2332     read-write transactions.
2333    </para>
2334
2335    <para>
2336     Users will be able to tell whether their session is read-only by
2337     issuing SHOW transaction_read_only.  In addition a set of
2338     functions <xref linkend="functions-recovery-info-table"> allow users to
2339     access information about Hot Standby. These allow you to write
2340     functions that are aware of the current state of the database. These
2341     can be used to monitor the progress of recovery, or to allow you to
2342     write complex programs that restore the database to particular states.
2343    </para>
2344
2345    <para>
2346     In recovery, transactions will not be permitted to take any table lock
2347     higher than RowExclusiveLock. In addition, transactions may never assign
2348     a TransactionId and may never write WAL.
2349     Any <command>LOCK TABLE</> command that runs on the standby and requests
2350     a specific lock mode higher than ROW EXCLUSIVE MODE will be rejected.
2351    </para>
2352
2353    <para>
2354     In general queries will not experience lock conflicts with the database
2355     changes made by recovery. This is becase recovery follows normal
2356     concurrency control mechanisms, known as <acronym>MVCC</>. There are
2357     some types of change that will cause conflicts, covered in the following
2358     section.
2359    </para>
2360   </sect2>
2361
2362   <sect2 id="hot-standby-conflict">
2363    <title>Handling query conflicts</title>
2364
2365    <para>
2366     The primary and standby nodes are in many ways loosely connected. Actions
2367     on the primary will have an effect on the standby. As a result, there is
2368     potential for negative interactions or conflicts between them. The easiest
2369     conflict to understand is performance: if a huge data load is taking place
2370     on the primary then this will generate a similar stream of WAL records on the
2371     standby, so standby queries may contend for system resources, such as I/O.
2372    </para>
2373
2374    <para>
2375     There are also additional types of conflict that can occur with Hot Standby.
2376     These conflicts are <emphasis>hard conflicts</> in the sense that we may
2377     need to cancel queries and in some cases disconnect sessions to resolve them.
2378     The user is provided with a number of optional ways to handle these
2379     conflicts, though we must first understand the possible reasons behind a conflict.
2380
2381       <itemizedlist>
2382        <listitem>
2383         <para>
2384          Access Exclusive Locks from primary node, including both explicit
2385          LOCK commands and various kinds of DDL action
2386         </para>
2387        </listitem>
2388        <listitem>
2389         <para>
2390          Dropping tablespaces on the primary while standby queries are using
2391          those tablespaces for temporary work files (work_mem overflow)
2392         </para>
2393        </listitem>
2394        <listitem>
2395         <para>
2396          Dropping databases on the primary while users are connected to that
2397          database on the standby.
2398         </para>
2399        </listitem>
2400        <listitem>
2401         <para>
2402          Waiting to acquire buffer cleanup locks
2403         </para>
2404        </listitem>
2405        <listitem>
2406         <para>
2407          Early cleanup of data still visible to the current query's snapshot
2408         </para>
2409        </listitem>
2410       </itemizedlist>
2411    </para>
2412
2413    <para>
2414     Some WAL redo actions will be for DDL actions. These DDL actions are
2415     repeating actions that have already committed on the primary node, so
2416     they must not fail on the standby node. These DDL locks take priority
2417     and will automatically *cancel* any read-only transactions that get in
2418     their way, after a grace period. This is similar to the possibility of
2419     being canceled by the deadlock detector, but in this case the standby
2420     process always wins, since the replayed actions must not fail. This
2421     also ensures that replication doesn't fall behind while we wait for a
2422     query to complete. Again, we assume that the standby is there for high
2423     availability purposes primarily.
2424    </para>
2425
2426    <para>
2427     An example of the above would be an Administrator on Primary server
2428     runs a <command>DROP TABLE</> on a table that's currently being queried
2429     in the standby server.
2430     Clearly the query cannot continue if we let the <command>DROP TABLE</>
2431     proceed. If this situation occurred on the primary, the <command>DROP TABLE</>
2432     would wait until the query has finished. When the query is on the standby
2433     and the <command>DROP TABLE</> is on the primary, the primary doesn't have
2434     information about which queries are running on the standby and so the query
2435     does not wait on the primary. The WAL change records come through to the
2436     standby while the standby query is still running, causing a conflict.
2437    </para>
2438
2439    <para>
2440     The most common reason for conflict between standby queries and WAL redo is
2441     "early cleanup". Normally, <productname>PostgreSQL</> allows cleanup of old
2442     row versions when there are no users who may need to see them to ensure correct
2443     visibility of data (the heart of MVCC). If there is a standby query that has
2444     been running for longer than any query on the primary then it is possible
2445     for old row versions to be removed by either a vacuum or HOT. This will
2446     then generate WAL records that, if applied, would remove data on the
2447     standby that might *potentially* be required by the standby query.
2448     In more technical language, the primary's xmin horizon is later than
2449     the standby's xmin horizon, allowing dead rows to be removed.
2450    </para>
2451
2452    <para>
2453     Experienced users should note that both row version cleanup and row version
2454     freezing will potentially conflict with recovery queries. Running a
2455     manual <command>VACUUM FREEZE</> is likely to cause conflicts even on tables
2456     with no updated or deleted rows.
2457    </para>
2458
2459    <para>
2460     We have a number of choices for resolving query conflicts.  The default
2461     is that we wait and hope the query completes. The server will wait
2462     automatically until the lag between primary and standby is at most
2463     <varname>max_standby_delay</> seconds. Once that grace period expires,
2464     we take one of the following actions:
2465
2466       <itemizedlist>
2467        <listitem>
2468         <para>
2469          If the conflict is caused by a lock, we cancel the conflicting standby
2470          transaction immediately. If the transaction is idle-in-transaction
2471          then currently we abort the session instead, though this may change
2472          in the future.
2473         </para>
2474        </listitem>
2475
2476        <listitem>
2477         <para>
2478          If the conflict is caused by cleanup records we tell the standby query
2479          that a conflict has occurred and that it must cancel itself to avoid the
2480          risk that it silently fails to read relevant data because
2481          that data has been removed. (This is regrettably very similar to the
2482          much feared and iconic error message "snapshot too old"). Some cleanup
2483          records only cause conflict with older queries, though some types of
2484          cleanup record affect all queries.
2485         </para>
2486
2487         <para>
2488          If cancellation does occur, the query and/or transaction can always
2489          be re-executed. The error is dynamic and will not necessarily occur
2490          the same way if the query is executed again.
2491         </para>
2492        </listitem>
2493       </itemizedlist>
2494    </para>
2495
2496    <para>
2497     <varname>max_standby_delay</> is set in <filename>postgresql.conf</>.
2498     The parameter applies to the server as a whole so if the delay is all used
2499     up by a single query then there may be little or no waiting for queries that
2500     follow immediately, though they will have benefited equally from the initial
2501     waiting period. The server may take time to catch up again before the grace
2502     period is available again, though if there is a heavy and constant stream
2503     of conflicts it may seldom catch up fully.
2504    </para>
2505
2506    <para>
2507     Users should be clear that tables that are regularly and heavily updated on
2508     primary server will quickly cause cancellation of longer running queries on
2509     the standby. In those cases <varname>max_standby_delay</> can be
2510     considered somewhat but not exactly the same as setting
2511     <varname>statement_timeout</>.
2512     </para>
2513
2514    <para>
2515     Other remedial actions exist if the number of cancellations is unacceptable.
2516     The first option is to connect to primary server and keep a query active
2517     for as long as we need to run queries on the standby. This guarantees that
2518     a WAL cleanup record is never generated and we don't ever get query
2519     conflicts as described above. This could be done using contrib/dblink
2520     and pg_sleep(), or via other mechanisms. If you do this, you should note
2521     that this will delay cleanup of dead rows by vacuum or HOT and many
2522     people may find this undesirable. However, we should remember that
2523     primary and standby nodes are linked via the WAL, so this situation is no
2524     different to the case where we ran the query on the primary node itself
2525     except we have the benefit of off-loading the execution onto the standby.
2526    </para>
2527
2528    <para>
2529     It is also possible to set <varname>vacuum_defer_cleanup_age</> on the primary
2530     to defer the cleanup of records by autovacuum, vacuum and HOT. This may allow
2531     more time for queries to execute before they are cancelled on the standby,
2532     without the need for setting a high <varname>max_standby_delay</>.
2533    </para>
2534
2535    <para>
2536     Three-way deadlocks are possible between AccessExclusiveLocks arriving from
2537     the primary, cleanup WAL records that require buffer cleanup locks and
2538     user requests that are waiting behind replayed AccessExclusiveLocks. Deadlocks
2539     are resolved by time-out when we exceed <varname>max_standby_delay</>.
2540    </para>
2541
2542    <para>
2543     Dropping tablespaces or databases is discussed in the administrator's
2544     section since they are not typical user situations.
2545    </para>
2546   </sect2>
2547
2548   <sect2 id="hot-standby-admin">
2549    <title>Administrator's Overview</title>
2550
2551    <para>
2552     If there is a <filename>recovery.conf</> file present the server will start
2553     in Hot Standby mode by default, though <varname>recovery_connections</> can
2554     be disabled via <filename>postgresql.conf</>, if required. The server may take
2555     some time to enable recovery connections since the server must first complete
2556     sufficient recovery to provide a consistent state against which queries
2557     can run before enabling read only connections. Look for these messages
2558     in the server logs
2559
2560 <programlisting>
2561 LOG:  initializing recovery connections
2562
2563 ... then some time later ...
2564
2565 LOG:  consistent recovery state reached
2566 LOG:  database system is ready to accept read only connections
2567 </programlisting>
2568
2569     Consistency information is recorded once per checkpoint on the primary, as long
2570     as <varname>recovery_connections</> is enabled (on the primary). If this parameter
2571     is disabled, it will not be possible to enable recovery connections on the standby.
2572     The consistent state can also be delayed in the presence of both of these conditions
2573
2574       <itemizedlist>
2575        <listitem>
2576         <para>
2577          a write transaction has more than 64 subtransactions
2578         </para>
2579        </listitem>
2580        <listitem>
2581         <para>
2582          very long-lived write transactions
2583         </para>
2584        </listitem>
2585       </itemizedlist>
2586
2587     If you are running file-based log shipping ("warm standby"), you may need
2588     to wait until the next WAL file arrives, which could be as long as the
2589     <varname>archive_timeout</> setting on the primary.
2590    </para>
2591
2592    <para>
2593     The setting of some parameters on the standby will need reconfiguration
2594     if they have been changed on the primary. The value on the standby must
2595     be equal to or greater than the value on the primary. If these parameters
2596     are not set high enough then the standby will not be able to track work
2597     correctly from recovering transactions. If these values are set too low the
2598     the server will halt. Higher values can then be supplied and the server
2599     restarted to begin recovery again.
2600
2601       <itemizedlist>
2602        <listitem>
2603         <para>
2604          <varname>max_connections</>
2605         </para>
2606        </listitem>
2607        <listitem>
2608         <para>
2609          <varname>max_prepared_transactions</>
2610         </para>
2611        </listitem>
2612        <listitem>
2613         <para>
2614          <varname>max_locks_per_transaction</>
2615         </para>
2616        </listitem>
2617       </itemizedlist>
2618    </para>
2619
2620    <para>
2621     It is important that the administrator consider the appropriate setting
2622     of <varname>max_standby_delay</>, set in <filename>postgresql.conf</>.
2623     There is no optimal setting and should be set according to business
2624     priorities. For example if the server is primarily tasked as a High
2625     Availability server, then you may wish to lower
2626     <varname>max_standby_delay</> or even set it to zero, though that is a
2627     very aggressive setting. If the standby server is tasked as an additional
2628     server for decision support queries then it may be acceptable to set this
2629     to a value of many hours (in seconds).
2630    </para>
2631
2632    <para>
2633     Transaction status "hint bits" written on primary are not WAL-logged,
2634     so data on standby will likely re-write the hints again on the standby.
2635     Thus the main database blocks will produce write I/Os even though
2636     all users are read-only; no changes have occurred to the data values
2637     themselves.  Users will be able to write large sort temp files and
2638     re-generate relcache info files, so there is no part of the database
2639     that is truly read-only during hot standby mode. There is no restriction
2640     on the use of set returning functions, or other users of tuplestore/tuplesort
2641     code. Note also that writes to remote databases will still be possible,
2642     even though the transaction is read-only locally.
2643    </para>
2644
2645    <para>
2646     The following types of administrator command are not accepted
2647     during recovery mode
2648
2649       <itemizedlist>
2650        <listitem>
2651         <para>
2652          Data Definition Language (DDL) - e.g. CREATE INDEX
2653         </para>
2654        </listitem>
2655        <listitem>
2656         <para>
2657          Privilege and Ownership - GRANT, REVOKE, REASSIGN
2658         </para>
2659        </listitem>
2660        <listitem>
2661         <para>
2662          Maintenance commands - ANALYZE, VACUUM, CLUSTER, REINDEX
2663         </para>
2664        </listitem>
2665       </itemizedlist>
2666    </para>
2667
2668    <para>
2669     Note again that some of these commands are actually allowed during
2670     "read only" mode transactions on the primary.
2671    </para>
2672
2673    <para>
2674     As a result, you cannot create additional indexes that exist solely
2675     on the standby, nor can statistics that exist solely on the standby.
2676     If these administrator commands are needed they should be executed
2677     on the primary so that the changes will propagate through to the
2678     standby.
2679    </para>
2680
2681    <para>
2682     <function>pg_cancel_backend()</> will work on user backends, but not the
2683     Startup process, which performs recovery. pg_stat_activity does not
2684     show an entry for the Startup process, nor do recovering transactions
2685     show as active. As a result, pg_prepared_xacts is always empty during
2686     recovery. If you wish to resolve in-doubt prepared transactions
2687     then look at pg_prepared_xacts on the primary and issue commands to
2688     resolve those transactions there.
2689    </para>
2690
2691    <para>
2692     pg_locks will show locks held by backends as normal. pg_locks also shows
2693     a virtual transaction managed by the Startup process that owns all
2694     AccessExclusiveLocks held by transactions being replayed by recovery.
2695     Note that Startup process does not acquire locks to
2696     make database changes and thus locks other than AccessExclusiveLocks
2697     do not show in pg_locks for the Startup process, they are just presumed
2698     to exist.
2699    </para>
2700
2701    <para>
2702     <productname>check_pgsql</> will work, but it is very simple.
2703     <productname>check_postgres</> will also work, though many some actions
2704     could give different or confusing results.
2705     e.g. last vacuum time will not be maintained for example, since no
2706     vacuum occurs on the standby (though vacuums running on the primary do
2707     send their changes to the standby).
2708    </para>
2709
2710    <para>
2711     WAL file control commands will not work during recovery
2712     e.g. <function>pg_start_backup</>, <function>pg_switch_xlog</> etc..
2713    </para>
2714
2715    <para>
2716     Dynamically loadable modules work, including pg_stat_statements.
2717    </para>
2718
2719    <para>
2720     Advisory locks work normally in recovery, including deadlock detection.
2721     Note that advisory locks are never WAL logged, so it is not possible for
2722     an advisory lock on either the primary or the standby to conflict with WAL
2723     replay. Nor is it possible to acquire an advisory lock on the primary
2724     and have it initiate a similar advisory lock on the standby. Advisory
2725     locks relate only to a single server on which they are acquired.
2726    </para>
2727
2728    <para>
2729     Trigger-based replication systems such as <productname>Slony</>,
2730     <productname>Londiste</> and <productname>Bucardo</> won't run on the
2731     standby at all, though they will run happily on the primary server as
2732     long as the changes are not sent to standby servers to be applied.
2733     WAL replay is not trigger-based so you cannot relay from the
2734     standby to any system that requires additional database writes or
2735     relies on the use of triggers.
2736    </para>
2737
2738    <para>
2739     New oids cannot be assigned, though some <acronym>UUID</> generators may still
2740     work as long as they do not rely on writing new status to the database.
2741    </para>
2742
2743    <para>
2744     Currently, temp table creation is not allowed during read only
2745     transactions, so in some cases existing scripts will not run correctly.
2746     It is possible we may relax that restriction in a later release. This is
2747     both a SQL Standard compliance issue and a technical issue.
2748    </para>
2749
2750    <para>
2751     <command>DROP TABLESPACE</> can only succeed if the tablespace is empty.
2752     Some standby users may be actively using the tablespace via their
2753     <varname>temp_tablespaces</> parameter. If there are temp files in the
2754     tablespace we currently cancel all active queries to ensure that temp
2755     files are removed, so that we can remove the tablespace and continue with
2756     WAL replay.
2757    </para>
2758
2759    <para>
2760     Running <command>DROP DATABASE</>, <command>ALTER DATABASE ... SET TABLESPACE</>,
2761     or <command>ALTER DATABASE ... RENAME</> on primary will generate a log message
2762     that will cause all users connected to that database on the standby to be
2763     forcibly disconnected. This action occurs immediately, whatever the setting of
2764     <varname>max_standby_delay</>.
2765    </para>
2766
2767    <para>
2768     In normal running, if you issue <command>DROP USER</> or <command>DROP ROLE</>
2769     for a role with login capability while that user is still connected then
2770     nothing happens to the connected user - they remain connected. The user cannot
2771     reconnect however. This behaviour applies in recovery also, so a
2772     <command>DROP USER</> on the primary does not disconnect that user on the standby.
2773    </para>
2774
2775    <para>
2776     Stats collector is active during recovery. All scans, reads, blocks,
2777     index usage etc will all be recorded normally on the standby. Replayed
2778     actions will not duplicate their effects on primary, so replaying an
2779     insert will not increment the Inserts column of pg_stat_user_tables.
2780     The stats file is deleted at start of recovery, so stats from primary
2781     and standby will differ; this is considered a feature not a bug.
2782    </para>
2783
2784    <para>
2785     Autovacuum is not active during recovery, though will start normally
2786     at the end of recovery.
2787    </para>
2788
2789    <para>
2790     Background writer is active during recovery and will perform
2791     restartpoints (similar to checkpoints on primary) and normal block
2792     cleaning activities. The <command>CHECKPOINT</> command is accepted during recovery,
2793     though performs a restartpoint rather than a new checkpoint.
2794    </para>
2795   </sect2>
2796
2797   <sect2 id="hot-standby-parameters">
2798    <title>Hot Standby Parameter Reference</title>
2799
2800    <para>
2801     Various parameters have been mentioned above in the <xref linkend="hot-standby-admin">
2802     and <xref linkend="hot-standby-conflict"> sections.
2803    </para>
2804
2805    <para>
2806     On the primary, parameters <varname>recovery_connections</> and
2807     <varname>vacuum_defer_cleanup_age</> can be used to enable and control the
2808     primary server to assist the successful configuration of Hot Standby servers.
2809     <varname>max_standby_delay</> has no effect if set on the primary.
2810    </para>
2811
2812    <para>
2813     On the standby, parameters <varname>recovery_connections</> and
2814     <varname>max_standby_delay</> can be used to enable and control Hot Standby.
2815     standby server to assist the successful configuration of Hot Standby servers.
2816     <varname>vacuum_defer_cleanup_age</> has no effect during recovery.
2817    </para>
2818   </sect2>
2819
2820   <sect2 id="hot-standby-caveats">
2821    <title>Caveats</title>
2822
2823    <para>
2824     At this writing, there are several limitations of Hot Standby.
2825     These can and probably will be fixed in future releases:
2826
2827   <itemizedlist>
2828    <listitem>
2829     <para>
2830      Operations on hash indexes are not presently WAL-logged, so
2831      replay will not update these indexes.  Hash indexes will not be
2832      used for query plans during recovery.
2833     </para>
2834    </listitem>
2835    <listitem>
2836     <para>
2837      Full knowledge of running transactions is required before snapshots
2838      may be taken. Transactions that take use large numbers of subtransactions
2839      (currently greater than 64) will delay the start of read only
2840      connections until the completion of the longest running write transaction.
2841      If this situation occurs explanatory messages will be sent to server log.
2842     </para>
2843    </listitem>
2844    <listitem>
2845     <para>
2846      Valid starting points for recovery connections are generated at each
2847      checkpoint on the master. If the standby is shutdown while the master
2848      is in a shutdown state it may not be possible to re-enter Hot Standby
2849      until the primary is started up so that it generates further starting
2850      points in the WAL logs. This is not considered a serious issue
2851      because the standby is usually switched into the primary role while
2852      the first node is taken down.
2853     </para>
2854    </listitem>
2855    <listitem>
2856     <para>
2857      At the end of recovery, AccessExclusiveLocks held by prepared transactions
2858      will require twice the normal number of lock table entries. If you plan
2859      on running either a large number of concurrent prepared transactions
2860      that normally take AccessExclusiveLocks, or you plan on having one
2861      large transaction that takes many AccessExclusiveLocks then you are
2862      advised to select a larger value of <varname>max_locks_per_transaction</>,
2863      up to, but never more than twice the value of the parameter setting on
2864      the primary server in rare extremes. You need not consider this at all if
2865      your setting of <varname>max_prepared_transactions</> is <literal>0</>.
2866     </para>
2867    </listitem>
2868   </itemizedlist>
2869
2870    </para>
2871   </sect2>
2872
2873  </sect1>
2874
2875  <sect1 id="migration">
2876   <title>Migration Between Releases</title>
2877
2878   <indexterm zone="migration">
2879    <primary>upgrading</primary>
2880   </indexterm>
2881
2882   <indexterm zone="migration">
2883    <primary>version</primary>
2884    <secondary>compatibility</secondary>
2885   </indexterm>
2886
2887   <para>
2888    This section discusses how to migrate your database data from one
2889    <productname>PostgreSQL</> release to a newer one.
2890    The software installation procedure <foreignphrase>per se</> is not the
2891    subject of this section; those details are in <xref linkend="installation">.
2892   </para>
2893
2894   <para>
2895    As a general rule, the internal data storage format is subject to
2896    change between major releases of <productname>PostgreSQL</> (where
2897    the number after the first dot changes). This does not apply to
2898    different minor releases under the same major release (where the
2899    number after the second dot changes); these always have compatible
2900    storage formats. For example, releases 8.1.1, 8.2.3, and 8.3 are
2901    not compatible, whereas 8.2.3 and 8.2.4 are. When you update
2902    between compatible versions, you can simply replace the executables
2903    and reuse the data directory on disk. Otherwise you need to back
2904    up your data and restore it on the new server.  This has to be done
2905    using <application>pg_dump</>; file system level backup methods
2906    obviously won't work. There are checks in place that prevent you
2907    from using a data directory with an incompatible version of
2908    <productname>PostgreSQL</productname>, so no great harm can be done by
2909    trying to start the wrong server version on a data directory.
2910   </para>
2911
2912   <para>
2913    It is recommended that you use the <application>pg_dump</> and
2914    <application>pg_dumpall</> programs from the newer version of
2915    <productname>PostgreSQL</>, to take advantage of any enhancements
2916    that might have been made in these programs.  Current releases of the
2917    dump programs can read data from any server version back to 7.0.
2918   </para>
2919
2920   <para>
2921    The least downtime can be achieved by installing the new server in
2922    a different directory and running both the old and the new servers
2923    in parallel, on different ports. Then you can use something like:
2924
2925 <programlisting>
2926 pg_dumpall -p 5432 | psql -d postgres -p 6543
2927 </programlisting>
2928
2929    to transfer your data.  Or use an intermediate file if you want.
2930    Then you can shut down the old server and start the new server at
2931    the port the old one was running at. You should make sure that the
2932    old database is not updated after you begin to run
2933    <application>pg_dumpall</>, otherwise you will lose that data. See <xref
2934    linkend="client-authentication"> for information on how to prohibit
2935    access.
2936   </para>
2937
2938   <para>
2939    It is also possible to use replication methods, such as
2940    <productname>Slony</>, to create a slave server with the updated version of
2941    <productname>PostgreSQL</>.  The slave can be on the same computer or
2942    a different computer.  Once it has synced up with the master server
2943    (running the older version of <productname>PostgreSQL</>), you can
2944    switch masters and make the slave the master and shut down the older
2945    database instance.  Such a switch-over results in only several seconds
2946    of downtime for an upgrade.
2947   </para>
2948
2949   <para>
2950    If you cannot or do not want to run two servers in parallel, you can
2951    do the backup step before installing the new version, bring down
2952    the server, move the old version out of the way, install the new
2953    version, start the new server, and restore the data. For example:
2954
2955 <programlisting>
2956 pg_dumpall &gt; backup
2957 pg_ctl stop
2958 mv /usr/local/pgsql /usr/local/pgsql.old
2959 cd ~/postgresql-&version;
2960 gmake install
2961 initdb -D /usr/local/pgsql/data
2962 postgres -D /usr/local/pgsql/data
2963 psql -f backup postgres
2964 </programlisting>
2965
2966    See <xref linkend="runtime"> about ways to start and stop the
2967    server and other details. The installation instructions will advise
2968    you of strategic places to perform these steps.
2969   </para>
2970
2971   <note>
2972    <para>
2973     When you <quote>move the old installation out of the way</quote>
2974     it might no longer be perfectly usable. Some of the executable programs
2975     contain absolute paths to various installed programs and data files.
2976     This is usually not a big problem, but if you plan on using two
2977     installations in parallel for a while you should assign them
2978     different installation directories at build time.  (This problem
2979     is rectified in <productname>PostgreSQL</> 8.0 and later, so long
2980     as you move all subdirectories containing installed files together;
2981     for example if <filename>/usr/local/postgres/bin/</> goes to
2982     <filename>/usr/local/postgres.old/bin/</>, then
2983     <filename>/usr/local/postgres/share/</> must go to
2984     <filename>/usr/local/postgres.old/share/</>.  In pre-8.0 releases
2985     moving an installation like this will not work.)
2986    </para>
2987   </note>
2988
2989   <para>
2990    In practice you probably want to test your client applications on the
2991    new version before switching over completely.  This is another reason
2992    for setting up concurrent installations of old and new versions.  When
2993    testing a <productname>PostgreSQL</> major upgrade, consider the
2994    following categories of possible changes:
2995   </para>
2996
2997   <variablelist>
2998
2999    <varlistentry>
3000     <term>Administration</term>
3001     <listitem>
3002      <para>
3003       The capabilities available for administrators to monitor and control
3004       the server often change and improve in each major release.
3005      </para>
3006     </listitem>
3007    </varlistentry>
3008
3009    <varlistentry>
3010     <term>SQL</term>
3011     <listitem>
3012      <para>
3013       Typically this includes new SQL command capabilities and not changes
3014       in behavior, unless specifically mentioned in the release notes.
3015      </para>
3016     </listitem>
3017    </varlistentry>
3018
3019    <varlistentry>
3020     <term>Library API</term>
3021     <listitem>
3022      <para>
3023       Typically libraries like <application>libpq</> only add new
3024       functionality, again unless mentioned in the release notes.
3025      </para>
3026     </listitem>
3027    </varlistentry>
3028
3029    <varlistentry>
3030     <term>System Catalogs</term>
3031     <listitem>
3032      <para>
3033       System catalog changes usually only affect database management tools.
3034      </para>
3035     </listitem>
3036    </varlistentry>
3037
3038    <varlistentry>
3039     <term>Server C-language API</term>
3040     <listitem>
3041      <para>
3042       This involved changes in the backend function API, which is written
3043       in the C programming language.  Such changes effect code that
3044       references backend functions deep inside the server.
3045      </para>
3046     </listitem>
3047    </varlistentry>
3048
3049   </variablelist>
3050
3051  </sect1>
3052 </chapter>