1 <!-- $PostgreSQL: pgsql/doc/src/sgml/backup.sgml,v 2.101 2007/09/14 13:26:22 momjian Exp $ -->
4 <title>Backup and Restore</title>
6 <indexterm zone="backup"><primary>backup</></>
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 basic understanding of
12 the underlying techniques and assumptions.
16 There are three fundamentally different approaches to backing up
17 <productname>PostgreSQL</> data:
19 <listitem><para><acronym>SQL</> dump</para></listitem>
20 <listitem><para>File system level backup</para></listitem>
21 <listitem><para>Continuous archiving</para></listitem>
23 Each has its own strengths and weaknesses.
26 <sect1 id="backup-dump">
27 <title><acronym>SQL</> Dump</title>
30 The idea behind this dump method is to generate a text file with SQL
31 commands that, when fed back to the server, will recreate the
32 database in the same state as it was at the time of the dump.
33 <productname>PostgreSQL</> provides the utility program
34 <xref linkend="app-pgdump"> for this purpose. The basic usage of this
37 pg_dump <replaceable class="parameter">dbname</replaceable> > <replaceable class="parameter">outfile</replaceable>
39 As you see, <application>pg_dump</> writes its results to the
40 standard output. We will see below how this can be useful.
44 <application>pg_dump</> is a regular <productname>PostgreSQL</>
45 client application (albeit a particularly clever one). This means
46 that you can do this backup procedure from any remote host that has
47 access to the database. But remember that <application>pg_dump</>
48 does not operate with special permissions. In particular, it must
49 have read access to all tables that you want to back up, so in
50 practice you almost always have to run it as a database superuser.
54 To specify which database server <application>pg_dump</> should
55 contact, use the command line options <option>-h
56 <replaceable>host</></> and <option>-p <replaceable>port</></>. The
57 default host is the local host or whatever your
58 <envar>PGHOST</envar> environment variable specifies. Similarly,
59 the default port is indicated by the <envar>PGPORT</envar>
60 environment variable or, failing that, by the compiled-in default.
61 (Conveniently, the server will normally have the same compiled-in
66 As any other <productname>PostgreSQL</> client application,
67 <application>pg_dump</> will by default connect with the database
68 user name that is equal to the current operating system user name. To override
69 this, either specify the <option>-U</option> option or set the
70 environment variable <envar>PGUSER</envar>. Remember that
71 <application>pg_dump</> connections are subject to the normal
72 client authentication mechanisms (which are described in <xref
73 linkend="client-authentication">).
77 Dumps created by <application>pg_dump</> are internally consistent,
78 that is, updates to the database while <application>pg_dump</> is
79 running will not be in the dump. <application>pg_dump</> does not
80 block other operations on the database while it is working.
81 (Exceptions are those operations that need to operate with an
82 exclusive lock, such as <command>VACUUM FULL</command>.)
87 If your database schema relies on OIDs (for instance as foreign
88 keys) you must instruct <application>pg_dump</> to dump the OIDs
89 as well. To do this, use the <option>-o</option> command line
94 <sect2 id="backup-dump-restore">
95 <title>Restoring the dump</title>
98 The text files created by <application>pg_dump</> are intended to
99 be read in by the <application>psql</application> program. The
100 general command form to restore a dump is
102 psql <replaceable class="parameter">dbname</replaceable> < <replaceable class="parameter">infile</replaceable>
104 where <replaceable class="parameter">infile</replaceable> is what
105 you used as <replaceable class="parameter">outfile</replaceable>
106 for the <application>pg_dump</> command. The database <replaceable
107 class="parameter">dbname</replaceable> will not be created by this
108 command, so you must create it yourself from <literal>template0</>
109 before executing <application>psql</> (e.g., with
110 <literal>createdb -T template0 <replaceable
111 class="parameter">dbname</></literal>). <application>psql</>
112 supports similar options to <application>pg_dump</> for specifying
113 the database server to connect to and the user name to use. See
114 the <xref linkend="app-psql"> reference page for more information.
118 Before restoring a SQL dump, all the users who own objects or were
119 granted permissions on objects in the dumped database must already
120 exist. If they do not, then the restore will fail to recreate the
121 objects with the original ownership and/or permissions.
122 (Sometimes this is what you want, but usually it is not.)
126 By default, the <application>psql</> script will continue to
127 execute after an SQL error is encountered. You might wish to use the
128 following command at the top of the script to alter that
129 behaviour and have <application>psql</application> exit with an
130 exit status of 3 if an SQL error occurs:
134 Either way, you will only have a partially restored
135 dump. Alternatively, you can specify that the whole dump should be
136 restored as a single transaction, so the restore is either fully
137 completed or fully rolled back. This mode can be specified by
138 passing the <option>-1</> or <option>--single-transaction</>
139 command-line options to <application>psql</>. When using this
140 mode, be aware that even the smallest of errors can rollback a
141 restore that has already run for many hours. However, that might
142 still be preferable to manually cleaning up a complex database
143 after a partially restored dump.
147 The ability of <application>pg_dump</> and <application>psql</> to
148 write to or read from pipes makes it possible to dump a database
149 directly from one server to another; for example:
151 pg_dump -h <replaceable>host1</> <replaceable>dbname</> | psql -h <replaceable>host2</> <replaceable>dbname</>
157 The dumps produced by <application>pg_dump</> are relative to
158 <literal>template0</>. This means that any languages, procedures,
159 etc. added to <literal>template1</> will also be dumped by
160 <application>pg_dump</>. As a result, when restoring, if you are
161 using a customized <literal>template1</>, you must create the
162 empty database from <literal>template0</>, as in the example
168 After restoring a backup, it is wise to run <xref
169 linkend="sql-analyze" endterm="sql-analyze-title"> on each
170 database so the query optimizer has useful statistics. An easy way
171 to do this is to run <command>vacuumdb -a -z</>; this is
172 equivalent to running <command>VACUUM ANALYZE</> on each database
173 manually. For more advice on how to load large amounts of data
174 into <productname>PostgreSQL</> efficiently, refer to <xref
179 <sect2 id="backup-dump-all">
180 <title>Using <application>pg_dumpall</></title>
183 <application>pg_dump</> dumps only a single database at a time,
184 and it does not dump information about roles or tablespaces
185 (because those are cluster-wide rather than per-database).
186 To support convenient dumping of the entire contents of a database
187 cluster, the <xref linkend="app-pg-dumpall"> program is provided.
188 <application>pg_dumpall</> backs up each database in a given
189 cluster, and also preserves cluster-wide data such as role and
190 tablespace definitions. The basic usage of this command is:
192 pg_dumpall > <replaceable>outfile</>
194 The resulting dump can be restored with <application>psql</>:
196 psql -f <replaceable class="parameter">infile</replaceable> postgres
198 (Actually, you can specify any existing database name to start from,
199 but if you are reloading in an empty cluster then <literal>postgres</>
200 should generally be used.) It is always necessary to have
201 database superuser access when restoring a <application>pg_dumpall</>
202 dump, as that is required to restore the role and tablespace information.
203 If you use tablespaces, be careful that the tablespace paths in the
204 dump are appropriate for the new installation.
208 <sect2 id="backup-dump-large">
209 <title>Handling large databases</title>
212 Since <productname>PostgreSQL</productname> allows tables larger
213 than the maximum file size on your system, it can be problematic
214 to dump such a table to a file, since the resulting file will likely
215 be larger than the maximum size allowed by your system. Since
216 <application>pg_dump</> can write to the standard output, you can
217 use standard Unix tools to work around this possible problem.
221 <title>Use compressed dumps.</title>
223 You can use your favorite compression program, for example
224 <application>gzip</application>:
227 pg_dump <replaceable class="parameter">dbname</replaceable> | gzip > <replaceable class="parameter">filename</replaceable>.gz
233 createdb <replaceable class="parameter">dbname</replaceable>
234 gunzip -c <replaceable class="parameter">filename</replaceable>.gz | psql <replaceable class="parameter">dbname</replaceable>
240 cat <replaceable class="parameter">filename</replaceable>.gz | gunzip | psql <replaceable class="parameter">dbname</replaceable>
246 <title>Use <command>split</>.</title>
248 The <command>split</command> command
249 allows you to split the output into pieces that are
250 acceptable in size to the underlying file system. For example, to
251 make chunks of 1 megabyte:
254 pg_dump <replaceable class="parameter">dbname</replaceable> | split -b 1m - <replaceable class="parameter">filename</replaceable>
260 createdb <replaceable class="parameter">dbname</replaceable>
261 cat <replaceable class="parameter">filename</replaceable>* | psql <replaceable class="parameter">dbname</replaceable>
267 <title>Use the custom dump format.</title>
269 If <productname>PostgreSQL</productname> was built on a system with the
270 <application>zlib</> compression library installed, the custom dump
271 format will compress data as it writes it to the output file. This will
272 produce dump file sizes similar to using <command>gzip</command>, but it
273 has the added advantage that tables can be restored selectively. The
274 following command dumps a database using the custom dump format:
277 pg_dump -Fc <replaceable class="parameter">dbname</replaceable> > <replaceable class="parameter">filename</replaceable>
280 A custom-format dump is not a script for <application>psql</>, but
281 instead must be restored with <application>pg_restore</>.
282 See the <xref linkend="app-pgdump"> and <xref
283 linkend="app-pgrestore"> reference pages for details.
290 <sect1 id="backup-file">
291 <title>File System Level Backup</title>
294 An alternative backup strategy is to directly copy the files that
295 <productname>PostgreSQL</> uses to store the data in the database. In
296 <xref linkend="creating-cluster"> it is explained where these files
297 are located, but you have probably found them already if you are
298 interested in this method. You can use whatever method you prefer
299 for doing usual file system backups, for example:
302 tar -cf backup.tar /usr/local/pgsql/data
307 There are two restrictions, however, which make this method
308 impractical, or at least inferior to the <application>pg_dump</>
314 The database server <emphasis>must</> be shut down in order to
315 get a usable backup. Half-way measures such as disallowing all
316 connections will <emphasis>not</emphasis> work
317 (mainly because <command>tar</command> and similar tools do not take an
318 atomic snapshot of the state of the file system at a point in
319 time). Information about stopping the server can be found in
320 <xref linkend="server-shutdown">. Needless to say that you
321 also need to shut down the server before restoring the data.
327 If you have dug into the details of the file system layout of the
328 database, you might be tempted to try to back up or restore only certain
329 individual tables or databases from their respective files or
330 directories. This will <emphasis>not</> work because the
331 information contained in these files contains only half the
332 truth. The other half is in the commit log files
333 <filename>pg_clog/*</filename>, which contain the commit status of
334 all transactions. A table file is only usable with this
335 information. Of course it is also impossible to restore only a
336 table and the associated <filename>pg_clog</filename> data
337 because that would render all other tables in the database
338 cluster useless. So file system backups only work for complete
339 restoration of an entire database cluster.
346 An alternative file-system backup approach is to make a
347 <quote>consistent snapshot</quote> of the data directory, if the
348 file system supports that functionality (and you are willing to
349 trust that it is implemented correctly). The typical procedure is
350 to make a <quote>frozen snapshot</> of the volume containing the
351 database, then copy the whole data directory (not just parts, see
352 above) from the snapshot to a backup device, then release the frozen
353 snapshot. This will work even while the database server is running.
354 However, a backup created in this way saves
355 the database files in a state where the database server was not
356 properly shut down; therefore, when you start the database server
357 on the backed-up data, it will think the server had crashed
358 and replay the WAL log. This is not a problem, just be aware of
359 it (and be sure to include the WAL files in your backup).
363 If your database is spread across multiple file systems, there might not
364 be any way to obtain exactly-simultaneous frozen snapshots of all
365 the volumes. For example, if your data files and WAL log are on different
366 disks, or if tablespaces are on different file systems, it might
367 not be possible to use snapshot backup because the snapshots must be
369 Read your file system documentation very carefully before trusting
370 to the consistent-snapshot technique in such situations. The safest
371 approach is to shut down the database server for long enough to
372 establish all the frozen snapshots.
376 Another option is to use <application>rsync</> to perform a file
377 system backup. This is done by first running <application>rsync</>
378 while the database server is running, then shutting down the database
379 server just long enough to do a second <application>rsync</>. The
380 second <application>rsync</> will be much quicker than the first,
381 because it has relatively little data to transfer, and the end result
382 will be consistent because the server was down. This method
383 allows a file system backup to be performed with minimal downtime.
387 Note that a file system backup will not necessarily be
388 smaller than an SQL dump. On the contrary, it will most likely be
389 larger. (<application>pg_dump</application> does not need to dump
390 the contents of indexes for example, just the commands to recreate
395 <sect1 id="continuous-archiving">
396 <title>Continuous Archiving and Point-In-Time Recovery (PITR)</title>
398 <indexterm zone="backup">
399 <primary>continuous archiving</primary>
402 <indexterm zone="backup">
403 <primary>point-in-time recovery</primary>
406 <indexterm zone="backup">
407 <primary>PITR</primary>
411 At all times, <productname>PostgreSQL</> maintains a
412 <firstterm>write ahead log</> (WAL) in the <filename>pg_xlog/</>
413 subdirectory of the cluster's data directory. The log describes
414 every change made to the database's data files. This log exists
415 primarily for crash-safety purposes: if the system crashes, the
416 database can be restored to consistency by <quote>replaying</> the
417 log entries made since the last checkpoint. However, the existence
418 of the log makes it possible to use a third strategy for backing up
419 databases: we can combine a file-system-level backup with backup of
420 the WAL files. If recovery is needed, we restore the backup and
421 then replay from the backed-up WAL files to bring the backup up to
422 current time. This approach is more complex to administer than
423 either of the previous approaches, but it has some significant
428 We do not need a perfectly consistent backup as the starting point.
429 Any internal inconsistency in the backup will be corrected by log
430 replay (this is not significantly different from what happens during
431 crash recovery). So we don't need file system snapshot capability,
432 just <application>tar</> or a similar archiving tool.
437 Since we can string together an indefinitely long sequence of WAL files
438 for replay, continuous backup can be achieved simply by continuing to archive
439 the WAL files. This is particularly valuable for large databases, where
440 it might not be convenient to take a full backup frequently.
445 There is nothing that says we have to replay the WAL entries all the
446 way to the end. We could stop the replay at any point and have a
447 consistent snapshot of the database as it was at that time. Thus,
448 this technique supports <firstterm>point-in-time recovery</>: it is
449 possible to restore the database to its state at any time since your base
455 If we continuously feed the series of WAL files to another
456 machine that has been loaded with the same base backup file, we
457 have a <firstterm>warm standby</> system: at any point we can bring up
458 the second machine and it will have a nearly-current copy of the
466 As with the plain file-system-backup technique, this method can only
467 support restoration of an entire database cluster, not a subset.
468 Also, it requires a lot of archival storage: the base backup might be bulky,
469 and a busy system will generate many megabytes of WAL traffic that
470 have to be archived. Still, it is the preferred backup technique in
471 many situations where high reliability is needed.
475 To recover successfully using continuous archiving (also called "online
476 backup" by many database vendors), you need a continuous
477 sequence of archived WAL files that extends back at least as far as the
478 start time of your backup. So to get started, you should setup and test
479 your procedure for archiving WAL files <emphasis>before</> you take your
480 first base backup. Accordingly, we first discuss the mechanics of
484 <sect2 id="backup-archiving-wal">
485 <title>Setting up WAL archiving</title>
488 In an abstract sense, a running <productname>PostgreSQL</> system
489 produces an indefinitely long sequence of WAL records. The system
490 physically divides this sequence into WAL <firstterm>segment
491 files</>, which are normally 16MB apiece (although the size can be
492 altered when building <productname>PostgreSQL</>). The segment
493 files are given numeric names that reflect their position in the
494 abstract WAL sequence. When not using WAL archiving, the system
495 normally creates just a few segment files and then
496 <quote>recycles</> them by renaming no-longer-needed segment files
497 to higher segment numbers. It's assumed that a segment file whose
498 contents precede the checkpoint-before-last is no longer of
499 interest and can be recycled.
503 When archiving WAL data, we want to capture the contents of each segment
504 file once it is filled, and save that data somewhere before the segment
505 file is recycled for reuse. Depending on the application and the
506 available hardware, there could be many different ways of <quote>saving
507 the data somewhere</>: we could copy the segment files to an NFS-mounted
508 directory on another machine, write them onto a tape drive (ensuring that
509 you have a way of identifying the original name of each file), or batch
510 them together and burn them onto CDs, or something else entirely. To
511 provide the database administrator with as much flexibility as possible,
512 <productname>PostgreSQL</> tries not to make any assumptions about how
513 the archiving will be done. Instead, <productname>PostgreSQL</> lets
514 the administrator specify a shell command to be executed to copy a
515 completed segment file to wherever it needs to go. The command could be
516 as simple as a <literal>cp</>, or it could invoke a complex shell
517 script — it's all up to you.
521 The shell command to use is specified by the <xref
522 linkend="guc-archive-command"> configuration parameter, which in practice
523 will always be placed in the <filename>postgresql.conf</filename> file.
525 any <literal>%p</> is replaced by the path name of the file to
526 archive, while any <literal>%f</> is replaced by the file name only.
527 (The path name is relative to the working directory of the server,
528 i.e., the cluster's data directory.)
529 Write <literal>%%</> if you need to embed an actual <literal>%</>
530 character in the command. The simplest useful command is something
533 archive_command = 'cp -i %p /mnt/server/archivedir/%f </dev/null'
535 which will copy archivable WAL segments to the directory
536 <filename>/mnt/server/archivedir</>. (This is an example, not a
537 recommendation, and might not work on all platforms.)
541 The archive command will be executed under the ownership of the same
542 user that the <productname>PostgreSQL</> server is running as. Since
543 the series of WAL files being archived contains effectively everything
544 in your database, you will want to be sure that the archived data is
545 protected from prying eyes; for example, archive into a directory that
546 does not have group or world read access.
550 It is important that the archive command return zero exit status if and
551 only if it succeeded. Upon getting a zero result,
552 <productname>PostgreSQL</> will assume that the WAL segment file has been
553 successfully archived, and will remove or recycle it.
554 However, a nonzero status tells
555 <productname>PostgreSQL</> that the file was not archived; it will try
556 again periodically until it succeeds.
560 The archive command should generally be designed to refuse to overwrite
561 any pre-existing archive file. This is an important safety feature to
562 preserve the integrity of your archive in case of administrator error
563 (such as sending the output of two different servers to the same archive
565 It is advisable to test your proposed archive command to ensure that it
566 indeed does not overwrite an existing file, <emphasis>and that it returns
567 nonzero status in this case</>. We have found that <literal>cp -i</> does
568 this correctly on some platforms but not others. If the chosen command
569 does not itself handle this case correctly, you should add a command
570 to test for pre-existence of the archive file. For example, something
573 archive_command = 'test ! -f .../%f && cp %p .../%f'
575 works correctly on most Unix variants.
579 While designing your archiving setup, consider what will happen if
580 the archive command fails repeatedly because some aspect requires
581 operator intervention or the archive runs out of space. For example, this
582 could occur if you write to tape without an autochanger; when the tape
583 fills, nothing further can be archived until the tape is swapped.
584 You should ensure that any error condition or request to a human operator
585 is reported appropriately so that the situation can be
586 resolved relatively quickly. The <filename>pg_xlog/</> directory will
587 continue to fill with WAL segment files until the situation is resolved.
591 The speed of the archiving command is not important, so long as it can keep up
592 with the average rate at which your server generates WAL data. Normal
593 operation continues even if the archiving process falls a little behind.
594 If archiving falls significantly behind, this will increase the amount of
595 data that would be lost in the event of a disaster. It will also mean that
596 the <filename>pg_xlog/</> directory will contain large numbers of
597 not-yet-archived segment files, which could eventually exceed available
598 disk space. You are advised to monitor the archiving process to ensure that
599 it is working as you intend.
603 In writing your archive command, you should assume that the file names to
604 be archived can be up to 64 characters long and can contain any
605 combination of ASCII letters, digits, and dots. It is not necessary to
606 remember the original relative path (<literal>%p</>) but it is necessary to
607 remember the file name (<literal>%f</>).
611 Note that although WAL archiving will allow you to restore any
612 modifications made to the data in your <productname>PostgreSQL</> database,
613 it will not restore changes made to configuration files (that is,
614 <filename>postgresql.conf</>, <filename>pg_hba.conf</> and
615 <filename>pg_ident.conf</>), since those are edited manually rather
616 than through SQL operations.
617 You might wish to keep the configuration files in a location that will
618 be backed up by your regular file system backup procedures. See
619 <xref linkend="runtime-config-file-locations"> for how to relocate the
624 The archive command is only invoked on completed WAL segments. Hence,
625 if your server generates only little WAL traffic (or has slack periods
626 where it does so), there could be a long delay between the completion
627 of a transaction and its safe recording in archive storage. To put
628 a limit on how old unarchived data can be, you can set
629 <xref linkend="guc-archive-timeout"> to force the server to switch
630 to a new WAL segment file at least that often. Note that archived
631 files that are ended early due to a forced switch are still the same
632 length as completely full files. It is therefore unwise to set a very
633 short <varname>archive_timeout</> — it will bloat your archive
634 storage. <varname>archive_timeout</> settings of a minute or so are
639 Also, you can force a segment switch manually with
640 <function>pg_switch_xlog</>, if you want to ensure that a
641 just-finished transaction is archived immediately. Other utility
642 functions related to WAL management are listed in <xref
643 linkend="functions-admin-backup-table">.
647 <sect2 id="backup-base-backup">
648 <title>Making a Base Backup</title>
651 The procedure for making a base backup is relatively simple:
655 Ensure that WAL archiving is enabled and working.
660 Connect to the database as a superuser, and issue the command:
662 SELECT pg_start_backup('label');
664 where <literal>label</> is any string you want to use to uniquely
665 identify this backup operation. (One good practice is to use the
666 full path where you intend to put the backup dump file.)
667 <function>pg_start_backup</> creates a <firstterm>backup label</> file,
668 called <filename>backup_label</>, in the cluster directory with
669 information about your backup.
673 It does not matter which database within the cluster you connect to to
674 issue this command. You can ignore the result returned by the function;
675 but if it reports an error, deal with that before proceeding.
679 <function>pg_start_backup</> can take a long time to finish.
680 This is because it performs a checkpoint, and the I/O
681 required for a checkpoint will be spread out over a significant
682 period of time, by default half your inter-checkpoint interval
683 (see the configuration parameter
684 <xref linkend="guc-checkpoint-completion-target">). Usually
685 this is what you want because it minimizes the impact on query
686 processing. If you just want to start the backup as soon as
687 possible, execute a <command>CHECKPOINT</> command
688 (which performs a checkpoint as quickly as possible) and then
689 immediately execute <function>pg_start_backup</>. Then there
690 will be very little for <function>pg_start_backup</>'s checkpoint
691 to do, and it won't take long.
696 Perform the backup, using any convenient file-system-backup tool
697 such as <application>tar</> or <application>cpio</>. It is neither
698 necessary nor desirable to stop normal operation of the database
704 Again connect to the database as a superuser, and issue the command:
706 SELECT pg_stop_backup();
708 This terminates the backup mode and performs an automatic switch to
709 the next WAL segment. The reason for the switch is to arrange that
710 the last WAL segment file written during the backup interval is
711 immediately ready to archive.
716 Once the WAL segment files used during the backup are archived, you are
717 done. The file identified by <function>pg_stop_backup</>'s result is
718 the last segment that needs to be archived to complete the backup.
719 Archival of these files will happen automatically, since you have
720 already configured <varname>archive_command</>. In many cases, this
721 happens fairly quickly, but you are advised to monitor your archival
722 system to ensure this has taken place so that you can be certain you
723 have a complete backup.
730 Some backup tools that you might wish to use emit warnings or errors
731 if the files they are trying to copy change while the copy proceeds.
732 This situation is normal, and not an error, when taking a base backup
733 of an active database; so you need to ensure that you can distinguish
734 complaints of this sort from real errors. For example, some versions
735 of <application>rsync</> return a separate exit code for
736 <quote>vanished source files</>, and you can write a driver script to
737 accept this exit code as a non-error case. Also, some versions of
738 GNU <application>tar</> return an error code indistinguishable from
739 a fatal error if a file was truncated while <application>tar</> was
740 copying it. Fortunately, GNU <application>tar</> versions 1.16 and
741 later exits with <literal>1</> if a file was changed during the backup,
742 and <literal>2</> for other errors.
746 It is not necessary to be very concerned about the amount of time elapsed
747 between <function>pg_start_backup</> and the start of the actual backup,
748 nor between the end of the backup and <function>pg_stop_backup</>; a
749 few minutes' delay won't hurt anything. (However, if you normally run the
750 server with <varname>full_page_writes</> disabled, you might notice a drop
751 in performance between <function>pg_start_backup</> and
752 <function>pg_stop_backup</>, since <varname>full_page_writes</> is
753 effectively forced on during backup mode.) You must ensure that these
754 steps are carried out in sequence without any possible
755 overlap, or you will invalidate the backup.
759 Be certain that your backup dump includes all of the files underneath
760 the database cluster directory (e.g., <filename>/usr/local/pgsql/data</>).
761 If you are using tablespaces that do not reside underneath this directory,
762 be careful to include them as well (and be sure that your backup dump
763 archives symbolic links as links, otherwise the restore will mess up
768 You can, however, omit from the backup dump the files within the
769 <filename>pg_xlog/</> subdirectory of the cluster directory. This
770 slight complication is worthwhile because it reduces the risk
771 of mistakes when restoring. This is easy to arrange if
772 <filename>pg_xlog/</> is a symbolic link pointing to someplace outside
773 the cluster directory, which is a common setup anyway for performance
778 To make use of the backup, you will need to keep around all the WAL
779 segment files generated during and after the file system backup.
780 To aid you in doing this, the <function>pg_stop_backup</> function
781 creates a <firstterm>backup history file</> that is immediately
782 stored into the WAL archive area. This file is named after the first
783 WAL segment file that you need to have to make use of the backup.
784 For example, if the starting WAL file is
785 <literal>0000000100001234000055CD</> the backup history file will be
787 <literal>0000000100001234000055CD.007C9330.backup</>. (The second
788 number in the file name stands for an exact position within the WAL
789 file, and can ordinarily be ignored.) Once you have safely archived
790 the file system backup and the WAL segment files used during the
791 backup (as specified in the backup history file), all archived WAL
792 segments with names numerically less are no longer needed to recover
793 the file system backup and can be deleted. However, you should
794 consider keeping several backup sets to be absolutely certain that
795 you can recover your data.
799 The backup history file is just a small text file. It contains the
800 label string you gave to <function>pg_start_backup</>, as well as
801 the starting and ending times and WAL segments of the backup.
802 If you used the label to identify where the associated dump file is kept,
803 then the archived history file is enough to tell you which dump file to
804 restore, should you need to do so.
808 Since you have to keep around all the archived WAL files back to your
809 last base backup, the interval between base backups should usually be
810 chosen based on how much storage you want to expend on archived WAL
811 files. You should also consider how long you are prepared to spend
812 recovering, if recovery should be necessary — the system will have to
813 replay all those WAL segments, and that could take awhile if it has
814 been a long time since the last base backup.
818 It's also worth noting that the <function>pg_start_backup</> function
819 makes a file named <filename>backup_label</> in the database cluster
820 directory, which is then removed again by <function>pg_stop_backup</>.
821 This file will of course be archived as a part of your backup dump file.
822 The backup label file includes the label string you gave to
823 <function>pg_start_backup</>, as well as the time at which
824 <function>pg_start_backup</> was run, and the name of the starting WAL
825 file. In case of confusion it will
826 therefore be possible to look inside a backup dump file and determine
827 exactly which backup session the dump file came from.
831 It is also possible to make a backup dump while the server is
832 stopped. In this case, you obviously cannot use
833 <function>pg_start_backup</> or <function>pg_stop_backup</>, and
834 you will therefore be left to your own devices to keep track of which
835 backup dump is which and how far back the associated WAL files go.
836 It is generally better to follow the continuous archiving procedure above.
840 <sect2 id="backup-pitr-recovery">
841 <title>Recovering using a Continuous Archive Backup</title>
844 Okay, the worst has happened and you need to recover from your backup.
845 Here is the procedure:
849 Stop the server, if it's running.
854 If you have the space to do so,
855 copy the whole cluster data directory and any tablespaces to a temporary
856 location in case you need them later. Note that this precaution will
857 require that you have enough free space on your system to hold two
858 copies of your existing database. If you do not have enough space,
859 you need at the least to copy the contents of the <filename>pg_xlog</>
860 subdirectory of the cluster data directory, as it might contain logs which
861 were not archived before the system went down.
866 Clean out all existing files and subdirectories under the cluster data
867 directory and under the root directories of any tablespaces you are using.
872 Restore the database files from your backup dump. Be careful that they
873 are restored with the right ownership (the database system user, not
874 root!) and with the right permissions. If you are using tablespaces,
875 you should verify that the symbolic links in <filename>pg_tblspc/</>
876 were correctly restored.
881 Remove any files present in <filename>pg_xlog/</>; these came from the
882 backup dump and are therefore probably obsolete rather than current.
883 If you didn't archive <filename>pg_xlog/</> at all, then recreate it,
884 and be sure to recreate the subdirectory
885 <filename>pg_xlog/archive_status/</> as well.
890 If you had unarchived WAL segment files that you saved in step 2,
891 copy them into <filename>pg_xlog/</>. (It is best to copy them,
892 not move them, so that you still have the unmodified files if a
893 problem occurs and you have to start over.)
898 Create a recovery command file <filename>recovery.conf</> in the cluster
899 data directory (see <xref linkend="recovery-config-settings">). You might
900 also want to temporarily modify <filename>pg_hba.conf</> to prevent
901 ordinary users from connecting until you are sure the recovery has worked.
906 Start the server. The server will go into recovery mode and
907 proceed to read through the archived WAL files it needs. Should the
908 recovery be terminated because of an external error, the server can
909 simply be restarted and it will continue recovery. Upon completion
910 of the recovery process, the server will rename
911 <filename>recovery.conf</> to <filename>recovery.done</> (to prevent
912 accidentally re-entering recovery mode in case of a crash later) and then
913 commence normal database operations.
918 Inspect the contents of the database to ensure you have recovered to
919 where you want to be. If not, return to step 1. If all is well,
920 let in your users by restoring <filename>pg_hba.conf</> to normal.
927 The key part of all this is to setup a recovery command file that
928 describes how you want to recover and how far the recovery should
929 run. You can use <filename>recovery.conf.sample</> (normally
930 installed in the installation <filename>share/</> directory) as a
931 prototype. The one thing that you absolutely must specify in
932 <filename>recovery.conf</> is the <varname>restore_command</>,
933 which tells <productname>PostgreSQL</> how to get back archived
934 WAL file segments. Like the <varname>archive_command</>, this is
935 a shell command string. It can contain <literal>%f</>, which is
936 replaced by the name of the desired log file, and <literal>%p</>,
937 which is replaced by the path name to copy the log file to.
938 (The path name is relative to the working directory of the server,
939 i.e., the cluster's data directory.)
940 Write <literal>%%</> if you need to embed an actual <literal>%</>
941 character in the command. The simplest useful command is
944 restore_command = 'cp /mnt/server/archivedir/%f %p'
946 which will copy previously archived WAL segments from the directory
947 <filename>/mnt/server/archivedir</>. You could of course use something
948 much more complicated, perhaps even a shell script that requests the
949 operator to mount an appropriate tape.
953 It is important that the command return nonzero exit status on failure.
954 The command <emphasis>will</> be asked for log files that are not present
955 in the archive; it must return nonzero when so asked. This is not an
956 error condition. Be aware also that the base name of the <literal>%p</>
957 path will be different from <literal>%f</>; do not expect them to be
962 WAL segments that cannot be found in the archive will be sought in
963 <filename>pg_xlog/</>; this allows use of recent un-archived segments.
964 However segments that are available from the archive will be used in
965 preference to files in <filename>pg_xlog/</>. The system will not
966 overwrite the existing contents of <filename>pg_xlog/</> when retrieving
971 Normally, recovery will proceed through all available WAL segments,
972 thereby restoring the database to the current point in time (or as
973 close as we can get given the available WAL segments). But if you want
974 to recover to some previous point in time (say, right before the junior
975 DBA dropped your main transaction table), just specify the required
976 stopping point in <filename>recovery.conf</>. You can specify the stop
977 point, known as the <quote>recovery target</>, either by date/time or
978 by completion of a specific transaction ID. As of this writing only
979 the date/time option is very usable, since there are no tools to help
980 you identify with any accuracy which transaction ID to use.
985 The stop point must be after the ending time of the base backup (the
986 time of <function>pg_stop_backup</>). You cannot use a base backup
987 to recover to a time when that backup was still going on. (To
988 recover to such a time, you must go back to your previous base backup
989 and roll forward from there.)
994 If recovery finds a corruption in the WAL data then recovery will
995 complete at that point and the server will not start. In such a case the
996 recovery process could be re-run from the beginning, specifying a
997 <quote>recovery target</> before the point of corruption so that recovery
998 can complete normally.
999 If recovery fails for an external reason, such as a system crash or
1000 if the WAL archive has become inaccessible, then the recovery can simply
1001 be restarted and it will restart almost from where it failed.
1002 Recovery restart works much like checkpointing in normal operation:
1003 the server periodically forces all its state to disk, and then updates
1004 the <filename>pg_control</> file to indicate that the already-processed
1005 WAL data need not be scanned again.
1009 <sect3 id="recovery-config-settings" xreflabel="Recovery Settings">
1010 <title>Recovery Settings</title>
1013 These settings can only be made in the <filename>recovery.conf</>
1014 file, and apply only for the duration of the recovery. They must be
1015 reset for any subsequent recovery you wish to perform. They cannot be
1016 changed once recovery has begun.
1021 <varlistentry id="restore-command" xreflabel="restore_command">
1022 <term><varname>restore_command</varname> (<type>string</type>)</term>
1025 The shell command to execute to retrieve an archived segment of
1026 the WAL file series. This parameter is required.
1027 Any <literal>%f</> in the string is
1028 replaced by the name of the file to retrieve from the archive,
1029 and any <literal>%p</> is replaced by the path name to copy
1030 it to on the server.
1031 (The path name is relative to the working directory of the server,
1032 i.e., the cluster's data directory.)
1033 Write <literal>%%</> to embed an actual <literal>%</> character
1037 It is important for the command to return a zero exit status if and
1038 only if it succeeds. The command <emphasis>will</> be asked for file
1039 names that are not present in the archive; it must return nonzero
1040 when so asked. Examples:
1042 restore_command = 'cp /mnt/server/archivedir/%f "%p"'
1043 restore_command = 'copy /mnt/server/archivedir/%f "%p"' # Windows
1049 <varlistentry id="recovery-target-time" xreflabel="recovery_target_time">
1050 <term><varname>recovery_target_time</varname>
1051 (<type>timestamp</type>)
1055 This parameter specifies the time stamp up to which recovery
1057 At most one of <varname>recovery_target_time</> and
1058 <xref linkend="recovery-target-xid"> can be specified.
1059 The default is to recover to the end of the WAL log.
1060 The precise stopping point is also influenced by
1061 <xref linkend="recovery-target-inclusive">.
1066 <varlistentry id="recovery-target-xid" xreflabel="recovery_target_xid">
1067 <term><varname>recovery_target_xid</varname> (<type>string</type>)</term>
1070 This parameter specifies the transaction ID up to which recovery
1071 will proceed. Keep in mind
1072 that while transaction IDs are assigned sequentially at transaction
1073 start, transactions can complete in a different numeric order.
1074 The transactions that will be recovered are those that committed
1075 before (and optionally including) the specified one.
1076 At most one of <varname>recovery_target_xid</> and
1077 <xref linkend="recovery-target-time"> can be specified.
1078 The default is to recover to the end of the WAL log.
1079 The precise stopping point is also influenced by
1080 <xref linkend="recovery-target-inclusive">.
1085 <varlistentry id="recovery-target-inclusive"
1086 xreflabel="recovery_target_inclusive">
1087 <term><varname>recovery_target_inclusive</varname>
1088 (<type>boolean</type>)
1092 Specifies whether we stop just after the specified recovery target
1093 (<literal>true</literal>), or just before the recovery target
1094 (<literal>false</literal>).
1095 Applies to both <xref linkend="recovery-target-time">
1096 and <xref linkend="recovery-target-xid">, whichever one is
1097 specified for this recovery. This indicates whether transactions
1098 having exactly the target commit time or ID, respectively, will
1099 be included in the recovery. Default is <literal>true</>.
1104 <varlistentry id="recovery-target-timeline"
1105 xreflabel="recovery_target_timeline">
1106 <term><varname>recovery_target_timeline</varname>
1107 (<type>string</type>)
1111 Specifies recovering into a particular timeline. The default is
1112 to recover along the same timeline that was current when the
1113 base backup was taken. You would only need to set this parameter
1114 in complex re-recovery situations, where you need to return to
1115 a state that itself was reached after a point-in-time recovery.
1116 See <xref linkend="backup-timelines"> for discussion.
1127 <sect2 id="backup-timelines">
1128 <title>Timelines</title>
1130 <indexterm zone="backup">
1131 <primary>timelines</primary>
1135 The ability to restore the database to a previous point in time creates
1136 some complexities that are akin to science-fiction stories about time
1137 travel and parallel universes. In the original history of the database,
1138 perhaps you dropped a critical table at 5:15PM on Tuesday evening.
1139 Unfazed, you get out your backup, restore to the point-in-time 5:14PM
1140 Tuesday evening, and are up and running. In <emphasis>this</> history of
1141 the database universe, you never dropped the table at all. But suppose
1142 you later realize this wasn't such a great idea after all, and would like
1143 to return to some later point in the original history. You won't be able
1144 to if, while your database was up-and-running, it overwrote some of the
1145 sequence of WAL segment files that led up to the time you now wish you
1146 could get back to. So you really want to distinguish the series of
1147 WAL records generated after you've done a point-in-time recovery from
1148 those that were generated in the original database history.
1152 To deal with these problems, <productname>PostgreSQL</> has a notion
1153 of <firstterm>timelines</>. Each time you recover to a point-in-time
1154 earlier than the end of the WAL sequence, a new timeline is created
1155 to identify the series of WAL records generated after that recovery.
1156 (If recovery proceeds all the way to the end of WAL, however, we do not
1157 start a new timeline: we just extend the existing one.) The timeline
1158 ID number is part of WAL segment file names, and so a new timeline does
1159 not overwrite the WAL data generated by previous timelines. It is
1160 in fact possible to archive many different timelines. While that might
1161 seem like a useless feature, it's often a lifesaver. Consider the
1162 situation where you aren't quite sure what point-in-time to recover to,
1163 and so have to do several point-in-time recoveries by trial and error
1164 until you find the best place to branch off from the old history. Without
1165 timelines this process would soon generate an unmanageable mess. With
1166 timelines, you can recover to <emphasis>any</> prior state, including
1167 states in timeline branches that you later abandoned.
1171 Each time a new timeline is created, <productname>PostgreSQL</> creates
1172 a <quote>timeline history</> file that shows which timeline it branched
1173 off from and when. These history files are necessary to allow the system
1174 to pick the right WAL segment files when recovering from an archive that
1175 contains multiple timelines. Therefore, they are archived into the WAL
1176 archive area just like WAL segment files. The history files are just
1177 small text files, so it's cheap and appropriate to keep them around
1178 indefinitely (unlike the segment files which are large). You can, if
1179 you like, add comments to a history file to make your own notes about
1180 how and why this particular timeline came to be. Such comments will be
1181 especially valuable when you have a thicket of different timelines as
1182 a result of experimentation.
1186 The default behavior of recovery is to recover along the same timeline
1187 that was current when the base backup was taken. If you want to recover
1188 into some child timeline (that is, you want to return to some state that
1189 was itself generated after a recovery attempt), you need to specify the
1190 target timeline ID in <filename>recovery.conf</>. You cannot recover into
1191 timelines that branched off earlier than the base backup.
1195 <sect2 id="continuous-archiving-caveats">
1196 <title>Caveats</title>
1199 At this writing, there are several limitations of the continuous archiving
1200 technique. These will probably be fixed in future releases:
1205 Operations on hash indexes are not presently WAL-logged, so
1206 replay will not update these indexes. The recommended workaround
1207 is to manually <xref linkend="sql-reindex" endterm="sql-reindex-title">
1208 each such index after completing a recovery operation.
1214 If a <xref linkend="sql-createdatabase" endterm="sql-createdatabase-title">
1215 command is executed while a base backup is being taken, and then
1216 the template database that the <command>CREATE DATABASE</> copied
1217 is modified while the base backup is still in progress, it is
1218 possible that recovery will cause those modifications to be
1219 propagated into the created database as well. This is of course
1220 undesirable. To avoid this risk, it is best not to modify any
1221 template databases while taking a base backup.
1227 <xref linkend="sql-createtablespace" endterm="sql-createtablespace-title">
1228 commands are WAL-logged with the literal absolute path, and will
1229 therefore be replayed as tablespace creations with the same
1230 absolute path. This might be undesirable if the log is being
1231 replayed on a different machine. It can be dangerous even if the
1232 log is being replayed on the same machine, but into a new data
1233 directory: the replay will still overwrite the contents of the
1234 original tablespace. To avoid potential gotchas of this sort,
1235 the best practice is to take a new base backup after creating or
1236 dropping tablespaces.
1243 It should also be noted that the default <acronym>WAL</acronym>
1244 format is fairly bulky since it includes many disk page snapshots.
1245 These page snapshots are designed to support crash recovery, since
1246 we might need to fix partially-written disk pages. Depending on
1247 your system hardware and software, the risk of partial writes might
1248 be small enough to ignore, in which case you can significantly
1249 reduce the total volume of archived logs by turning off page
1250 snapshots using the <xref linkend="guc-full-page-writes">
1251 parameter. (Read the notes and warnings in <xref linkend="wal">
1252 before you do so.) Turning off page snapshots does not prevent
1253 use of the logs for PITR operations. An area for future
1254 development is to compress archived WAL data by removing
1255 unnecessary page copies even when <varname>full_page_writes</> is
1256 on. In the meantime, administrators might wish to reduce the number
1257 of page snapshots included in WAL by increasing the checkpoint
1258 interval parameters as much as feasible.
1263 <sect1 id="warm-standby">
1264 <title>Warm Standby Servers for High Availability</title>
1266 <indexterm zone="backup">
1267 <primary>warm standby</primary>
1270 <indexterm zone="backup">
1271 <primary>PITR standby</primary>
1274 <indexterm zone="backup">
1275 <primary>standby server</primary>
1278 <indexterm zone="backup">
1279 <primary>log shipping</primary>
1282 <indexterm zone="backup">
1283 <primary>witness server</primary>
1286 <indexterm zone="backup">
1287 <primary>STONITH</primary>
1290 <indexterm zone="backup">
1291 <primary>high availability</primary>
1295 Continuous archiving can be used to create a <firstterm>high
1296 availability</> (HA) cluster configuration with one or more
1297 <firstterm>standby servers</> ready to take
1298 over operations if the primary server fails. This
1299 capability is widely referred to as <firstterm>warm standby</>
1300 or <firstterm>log shipping</>.
1304 The primary and standby server work together to provide this capability,
1305 though the servers are only loosely coupled. The primary server operates
1306 in continuous archiving mode, while each standby server operates in
1307 continuous recovery mode, reading the WAL files from the primary. No
1308 changes to the database tables are required to enable this capability,
1309 so it offers low administration overhead in comparison with some other
1310 replication approaches. This configuration also has relatively low
1311 performance impact on the primary server.
1315 Directly moving WAL or "log" records from one database server to another
1316 is typically described as log shipping. <productname>PostgreSQL</>
1317 implements file-based log shipping, which means that WAL records are
1318 transferred one file (WAL segment) at a time. WAL
1319 files can be shipped easily and cheaply over any distance, whether it be
1320 to an adjacent system, another system on the same site or another system
1321 on the far side of the globe. The bandwidth required for this technique
1322 varies according to the transaction rate of the primary server.
1323 Record-based log shipping is also possible with custom-developed
1324 procedures, as discussed in <xref linkend="warm-standby-record">.
1328 It should be noted that the log shipping is asynchronous, i.e. the
1329 WAL records are shipped after transaction commit. As a result there
1330 is a window for data loss should the primary server
1331 suffer a catastrophic failure: transactions not yet shipped will be lost.
1332 The length of the window of data loss
1333 can be limited by use of the <varname>archive_timeout</varname> parameter,
1334 which can be set as low as a few seconds if required. However such low
1335 settings will substantially increase the bandwidth requirements for file
1336 shipping. If you need a window of less than a minute or so, it's probably
1337 better to look into record-based log shipping.
1341 The standby server is not available for access, since it is continually
1342 performing recovery processing. Recovery performance is sufficiently
1343 good that the standby will typically be only moments away from full
1344 availability once it has been activated. As a result, we refer to this
1345 capability as a warm standby configuration that offers high
1346 availability. Restoring a server from an archived base backup and
1347 rollforward will take considerably longer, so that technique only
1348 really offers a solution for disaster recovery, not HA.
1351 <sect2 id="warm-standby-planning">
1352 <title>Planning</title>
1355 It is usually wise to create the primary and standby servers
1356 so that they are as similar as possible, at least from the
1357 perspective of the database server. In particular, the path names
1358 associated with tablespaces will be passed across as-is, so both
1359 primary and standby servers must have the same mount paths for
1360 tablespaces if that feature is used. Keep in mind that if
1361 <xref linkend="sql-createtablespace" endterm="sql-createtablespace-title">
1362 is executed on the primary, any new mount point needed for it must
1363 be created on both the primary and all standby servers before the command
1364 is executed. Hardware need not be exactly the same, but experience shows
1365 that maintaining two identical systems is easier than maintaining two
1366 dissimilar ones over the lifetime of the application and system.
1367 In any case the hardware architecture must be the same — shipping
1368 from, say, a 32-bit to a 64-bit system will not work.
1372 In general, log shipping between servers running different major release
1373 levels will not be possible. It is the policy of the PostgreSQL Global
1374 Development Group not to make changes to disk formats during minor release
1375 upgrades, so it is likely that running different minor release levels
1376 on primary and standby servers will work successfully. However, no
1377 formal support for that is offered and you are advised to keep primary
1378 and standby servers at the same release level as much as possible.
1379 When updating to a new minor release, the safest policy is to update
1380 the standby servers first — a new minor release is more likely
1381 to be able to read WAL files from a previous minor release than vice
1386 There is no special mode required to enable a standby server. The
1387 operations that occur on both primary and standby servers are entirely
1388 normal continuous archiving and recovery tasks. The only point of
1389 contact between the two database servers is the archive of WAL files
1390 that both share: primary writing to the archive, standby reading from
1391 the archive. Care must be taken to ensure that WAL archives for separate
1392 primary servers do not become mixed together or confused.
1396 The magic that makes the two loosely coupled servers work together
1397 is simply a <varname>restore_command</> used on the standby that waits for
1398 the next WAL file to become available from the primary. The
1399 <varname>restore_command</> is specified in the <filename>recovery.conf</>
1401 server. Normal recovery processing would request a file from the
1402 WAL archive, reporting failure if the file was unavailable. For
1403 standby processing it is normal for the next file to be
1404 unavailable, so we must be patient and wait for it to appear. A
1405 waiting <varname>restore_command</> can be written as a custom
1406 script that loops after polling for the existence of the next WAL
1407 file. There must also be some way to trigger failover, which
1408 should interrupt the <varname>restore_command</>, break the loop
1409 and return a file-not-found error to the standby server. This
1410 ends recovery and the standby will then come up as a normal
1415 Pseudocode for a suitable <varname>restore_command</> is:
1418 while (!NextWALFileReady() && !triggered)
1420 sleep(100000L); /* wait for ~0.1 sec */
1421 if (CheckForExternalTrigger())
1425 CopyWALFileForRecovery();
1430 <productname>PostgreSQL</productname> does not provide the system
1431 software required to identify a failure on the primary and notify
1432 the standby system and then the standby database server. Many such
1433 tools exist and are well integrated with other aspects required for
1434 successful failover, such as IP address migration.
1438 The means for triggering failover is an important part of planning and
1439 design. The <varname>restore_command</> is executed in full once
1440 for each WAL file. The process running the <varname>restore_command</>
1441 is therefore created and dies for each file, so there is no daemon
1442 or server process and so we cannot use signals and a signal
1443 handler. A more permanent notification is required to trigger the
1444 failover. It is possible to use a simple timeout facility,
1445 especially if used in conjunction with a known
1446 <varname>archive_timeout</> setting on the primary. This is
1447 somewhat error prone since a network problem or busy primary server might
1448 be sufficient to initiate failover. A notification mechanism such
1449 as the explicit creation of a trigger file is less error prone, if
1450 this can be arranged.
1454 <sect2 id="warm-standby-config">
1455 <title>Implementation</title>
1458 The short procedure for configuring a standby server is as follows. For
1459 full details of each step, refer to previous sections as noted.
1463 Set up primary and standby systems as near identically as
1464 possible, including two identical copies of
1465 <productname>PostgreSQL</> at the same release level.
1470 Set up continuous archiving from the primary to a WAL archive located
1471 in a directory on the standby server. Ensure that <xref
1472 linkend="guc-archive-command"> and <xref linkend="guc-archive-timeout">
1473 are set appropriately on the primary
1474 (see <xref linkend="backup-archiving-wal">).
1479 Make a base backup of the primary server (see <xref
1480 linkend="backup-base-backup">), and load this data onto the standby.
1485 Begin recovery on the standby server from the local WAL
1486 archive, using a <filename>recovery.conf</> that specifies a
1487 <varname>restore_command</> that waits as described
1488 previously (see <xref linkend="backup-pitr-recovery">).
1495 Recovery treats the WAL archive as read-only, so once a WAL file has
1496 been copied to the standby system it can be copied to tape at the same
1497 time as it is being read by the standby database server.
1498 Thus, running a standby server for high availability can be performed at
1499 the same time as files are stored for longer term disaster recovery
1504 For testing purposes, it is possible to run both primary and standby
1505 servers on the same system. This does not provide any worthwhile
1506 improvement in server robustness, nor would it be described as HA.
1510 <sect2 id="warm-standby-failover">
1511 <title>Failover</title>
1514 If the primary server fails then the standby server should begin
1515 failover procedures.
1519 If the standby server fails then no failover need take place. If the
1520 standby server can be restarted, even some time later, then the recovery
1521 process can also be immediately restarted, taking advantage of
1522 restartable recovery. If the standby server cannot be restarted, then a
1523 full new standby server should be created.
1527 If the primary server fails and then immediately restarts, you must have
1528 a mechanism for informing it that it is no longer the primary. This is
1529 sometimes known as STONITH (Shoot the Other Node In The Head), which is
1530 necessary to avoid situations where both systems think they are the
1531 primary, which can lead to confusion and ultimately data loss.
1535 Many failover systems use just two systems, the primary and the standby,
1536 connected by some kind of heartbeat mechanism to continually verify the
1537 connectivity between the two and the viability of the primary. It is
1538 also possible to use a third system (called a witness server) to avoid
1539 some problems of inappropriate failover, but the additional complexity
1540 might not be worthwhile unless it is set-up with sufficient care and
1545 Once failover to the standby occurs, we have only a
1546 single server in operation. This is known as a degenerate state.
1547 The former standby is now the primary, but the former primary is down
1548 and might stay down. To return to normal operation we must
1549 fully recreate a standby server,
1550 either on the former primary system when it comes up, or on a third,
1551 possibly new, system. Once complete the primary and standby can be
1552 considered to have switched roles. Some people choose to use a third
1553 server to provide backup to the new primary until the new standby
1554 server is recreated,
1555 though clearly this complicates the system configuration and
1556 operational processes.
1560 So, switching from primary to standby server can be fast but requires
1561 some time to re-prepare the failover cluster. Regular switching from
1562 primary to standby is encouraged, since it allows regular downtime on
1563 each system for maintenance. This also acts as a test of the
1564 failover mechanism to ensure that it will really work when you need it.
1565 Written administration procedures are advised.
1569 <sect2 id="warm-standby-record">
1570 <title>Record-based Log Shipping</title>
1573 <productname>PostgreSQL</productname> directly supports file-based
1574 log shipping as described above. It is also possible to implement
1575 record-based log shipping, though this requires custom development.
1579 An external program can call the <function>pg_xlogfile_name_offset()</>
1580 function (see <xref linkend="functions-admin">)
1581 to find out the file name and the exact byte offset within it of
1582 the current end of WAL. It can then access the WAL file directly
1583 and copy the data from the last known end of WAL through the current end
1584 over to the standby server(s). With this approach, the window for data
1585 loss is the polling cycle time of the copying program, which can be very
1586 small, but there is no wasted bandwidth from forcing partially-used
1587 segment files to be archived. Note that the standby servers'
1588 <varname>restore_command</> scripts still deal in whole WAL files,
1589 so the incrementally copied data is not ordinarily made available to
1590 the standby servers. It is of use only when the primary dies —
1591 then the last partial WAL file is fed to the standby before allowing
1592 it to come up. So correct implementation of this process requires
1593 cooperation of the <varname>restore_command</> script with the data
1598 <sect2 id="backup-incremental-updated">
1599 <title>Incrementally Updated Backups</title>
1601 <indexterm zone="backup">
1602 <primary>incrementally updated backups</primary>
1605 <indexterm zone="backup">
1606 <primary>change accumulation</primary>
1610 In a warm standby configuration, it is possible to offload the expense of
1611 taking periodic base backups from the primary server; instead base backups
1612 can be made by backing
1613 up a standby server's files. This concept is generally known as
1614 incrementally updated backups, log change accumulation or more simply,
1615 change accumulation.
1619 If we take a backup of the standby server's files while it is following
1620 logs shipped from the primary, we will be able to reload that data and
1621 restart the standby's recovery process from the last restart point.
1622 We no longer need to keep WAL files from before the restart point.
1623 If we need to recover, it will be faster to recover from the incrementally
1624 updated backup than from the original base backup.
1628 Since the standby server is not <quote>live</>, it is not possible to
1629 use <function>pg_start_backup()</> and <function>pg_stop_backup()</>
1630 to manage the backup process; it will be up to you to determine how
1631 far back you need to keep WAL segment files to have a recoverable
1632 backup. You can do this by running <application>pg_controldata</>
1633 on the standby server to inspect the control file and determine the
1634 current checkpoint WAL location.
1639 <sect1 id="migration">
1640 <title>Migration Between Releases</title>
1642 <indexterm zone="migration">
1643 <primary>upgrading</primary>
1646 <indexterm zone="migration">
1647 <primary>version</primary>
1648 <secondary>compatibility</secondary>
1652 This section discusses how to migrate your database data from one
1653 <productname>PostgreSQL</> release to a newer one.
1654 The software installation procedure <foreignphrase>per se</> is not the
1655 subject of this section; those details are in <xref linkend="installation">.
1659 As a general rule, the internal data storage format is subject to
1660 change between major releases of <productname>PostgreSQL</> (where
1661 the number after the first dot changes). This does not apply to
1662 different minor releases under the same major release (where the
1663 number after the second dot changes); these always have compatible
1664 storage formats. For example, releases 7.2.1, 7.3.2, and 7.4 are
1665 not compatible, whereas 7.2.1 and 7.2.2 are. When you update
1666 between compatible versions, you can simply replace the executables
1667 and reuse the data directory on disk. Otherwise you need to back
1668 up your data and restore it on the new server. This has to be done
1669 using <application>pg_dump</>; file system level backup methods
1670 obviously won't work. There are checks in place that prevent you
1671 from using a data directory with an incompatible version of
1672 <productname>PostgreSQL</productname>, so no great harm can be done by
1673 trying to start the wrong server version on a data directory.
1677 It is recommended that you use the <application>pg_dump</> and
1678 <application>pg_dumpall</> programs from the newer version of
1679 <productname>PostgreSQL</>, to take advantage of any enhancements
1680 that might have been made in these programs. Current releases of the
1681 dump programs can read data from any server version back to 7.0.
1685 The least downtime can be achieved by installing the new server in
1686 a different directory and running both the old and the new servers
1687 in parallel, on different ports. Then you can use something like:
1690 pg_dumpall -p 5432 | psql -d postgres -p 6543
1693 to transfer your data. Or use an intermediate file if you want.
1694 Then you can shut down the old server and start the new server at
1695 the port the old one was running at. You should make sure that the
1696 old database is not updated after you run <application>pg_dumpall</>,
1697 otherwise you will obviously lose that data. See <xref
1698 linkend="client-authentication"> for information on how to prohibit
1703 In practice you probably want to test your client
1704 applications on the new setup before switching over completely.
1705 This is another reason for setting up concurrent installations
1706 of old and new versions.
1710 If you cannot or do not want to run two servers in parallel you can
1711 do the backup step before installing the new version, bring down
1712 the server, move the old version out of the way, install the new
1713 version, start the new server, restore the data. For example:
1716 pg_dumpall > backup
1718 mv /usr/local/pgsql /usr/local/pgsql.old
1719 cd ~/postgresql-&version;
1721 initdb -D /usr/local/pgsql/data
1722 postgres -D /usr/local/pgsql/data
1723 psql -f backup postgres
1726 See <xref linkend="runtime"> about ways to start and stop the
1727 server and other details. The installation instructions will advise
1728 you of strategic places to perform these steps.
1733 When you <quote>move the old installation out of the way</quote>
1734 it might no longer be perfectly usable. Some of the executable programs
1735 contain absolute paths to various installed programs and data files.
1736 This is usually not a big problem but if you plan on using two
1737 installations in parallel for a while you should assign them
1738 different installation directories at build time. (This problem
1739 is rectified in <productname>PostgreSQL</> 8.0 and later, but you
1740 need to be wary of moving older installations.)