PG_BASEBACKUP(1)
๐ pg_basebackup(1) โ PostgreSQL 18.6 Documentation ๐
okay bestie, pull up a chair, grab a snack, we're doing backups today and honestly? it's giving main character energy โจ
๐ NAME ๐
pg_basebackup โ take a base backup of a PostgreSQL cluster ๐ซถ
๐ธ SYNOPSIS ๐ธ
pg_basebackup [option...]
๐ฆ DESCRIPTION ๐ฆ
So like, pg_basebackup is the tool you use to take a base backup of a running PostgreSQL database cluster. And the whole point, the moment, is that it does this without affecting other clients of the database. Nobody else even notices you're there. Iconic behavior, no cap.
You can use the result for two big things: point-in-time recovery (peep Section 25.3), or as the starting point for a log-shipping or streaming-replication standby server (that's Section 26.2).
pg_basebackup can take a full or an incremental base backup of the database. Here's the tea on the difference:
- When it's taking a full backup, it makes an exact copy of the database cluster's files. Simple. Perfect. No notes.
- When it's taking an incremental backup, some files that would have been part of a full backup may be replaced with incremental versions of the same files โ versions containing only those blocks that have been modified since the reference backup.
โ ๏ธ and this part is important bestie: an incremental backup cannot be used directly. You have to run pg_combinebackup(1) first to combine it with the previous backups it depends on. No skipping steps.
Wanna know more about incremental backups? Section 25.3.3. Wanna know the actual steps to recover from a backup? Section 25.3.5. Go read those, I'll wait ๐
In any mode, pg_basebackup makes sure the server is put into backup mode and taken back out of it โ automatically. You don't have to do a thing. Also: backups are always taken of the entire database cluster. You literally cannot back up individual databases or database objects with this tool. If you want a selective backup you need a whole other tool, like pg_dump(1). Different vibe, different job.
The backup is made over a regular PostgreSQL connection that uses the replication protocol. Requirements, let's list them because they're not optional:
- The connection must be made with a user ID that has
REPLICATIONpermissions (see Section 21.2) or is a superuser. pg_hba.confmust permit the replication connection.- The server must be configured with
max_wal_sendersset high enough to provide at least one walsender for the backup, plus one for WAL streaming (if you're using WAL streaming).
You can run multiple pg_basebackups at the same time, but honestly? From a performance point of view it's usually better to just take one backup and copy the result. Less drama, better numbers. ๐
Oh and here's a fun one: pg_basebackup can make a base backup not only from a primary server but also from a standby. To take a backup from a standby, set up the standby so it can accept replication connections โ that means setting max_wal_senders and hot_standby, and configuring its pg_hba.conf appropriately. You'll also need to enable full_page_writes on the primary.
๐ Limitations of backing up from a standby ๐
Not everything is sunshine and roses, bestie. Here's what you can't do:
- The backup history file is not created in the database cluster that got backed up.
pg_basebackupcannot force the standby to switch to a new WAL file at the end of the backup. So when you're using-X none, and write activity on the primary is low,pg_basebackupmay need to wait a long time for the last WAL file required for the backup to be switched and archived. In that case it can be useful to runpg_switch_walon the primary to trigger an immediate WAL file switch.- If the standby gets promoted to be primary during the backup โ yeah, the backup fails. ๐
- All WAL records required for the backup must contain sufficient full-page writes, which requires you to enable
full_page_writeson the primary.
Whenever pg_basebackup is taking a base backup, the server's pg_stat_progress_basebackup view will report the progress of the backup. Yes, you can watch it live. Very satisfying. Section 27.4.6 has the details โจ
๐ OPTIONS ๐
The following command-line options control the location and format of the output:
-Ddirectory**, **--pgdata=*directory*** โ Sets the target directory to write the output to.pg_basebackupwill create this directory (and any missing parent directories) if it doesn't exist yet. But if it *does* already exist, it must be <red>empty</red>. Also, when the backup is intarformat, the target directory may be specified as-` (dash), which causes the tar file to be written to stdout. ๐ซถ oh and heads up: **this option is required. No skipping it.-Fformat**, **--format=`format โ Selects the format for the output. format can be one of the following:p,plainโ Write the output as plain files, with the same layout as the source server's data directory and tablespaces. When the cluster has no additional tablespaces, the whole database will be placed in the target directory. If the cluster does contain additional tablespaces, the main data directory will be placed in the target directory, but all other tablespaces will be placed in the same absolute path as they have on the source server. (See--tablespace-mappingif you wanna change that.)
This is the default format. ๐
t,tarโ Write the output as tar files in the target directory. The main data directory's contents will be written to a file namedbase.tar, and each other tablespace will be written to a separate tar file named after that tablespace's OID.
If the target directory is specified as - (dash), the tar contents will be written to standard output, suitable for piping to (for example) gzip. This is only allowed if the cluster has no additional tablespaces and WAL streaming is not used.
-iold_manifest_file**, **--incremental=`old_manifest_file โ Performs an incremental backup. The backup manifest for the reference backup must be provided, and it will be uploaded to the server, which will respond by sending the requested incremental backup. ๐-R,--write-recovery-confโ Creates astandby.signalfile and appends connection settings to thepostgresql.auto.conffile in the target directory (or within the base archive file when usingtarformat). This eases setting up a standby server using the results of the backup.
The postgresql.auto.conf file will record the connection settings and, if specified, the replication slot that pg_basebackup is using โ so that streaming replication and logical replication slot synchronization will use the same settings later on. The dbname will be recorded only if the dbname was specified explicitly in the connection string or environment variable. (iykyk)
- *
-t*target**, **--target=*target*** โ Instructs the *server* where to place the base backup. The default target isclient, which specifies that the backup should be sent to the machine wherepg_basebackupis running. If the target is instead set toserver:/some/path, the backup will be stored on the machine where the *server* is running, in the/some/pathdirectory. Storing a backup on the server requires <hotpink>superuser privileges</hotpink> or having privileges of thepg_write_server_filesrole. And if the target is set toblackhole`, the contents are discarded and not stored anywhere.
๐ blackhole should only be used for testing purposes, because you will not end up with an actual backup. Like. You get nothing. Zero. Nada.
Since WAL streaming is implemented by pg_basebackup rather than by the server, this option cannot be used together with -Xstream. And since -Xstream is the default, when you specify this option you must also specify either -Xfetch or -Xnone.
- *
-T*olddir=newdir**, **--tablespace-mapping=*olddir*=*newdir*** โ Relocates the tablespace in directory *olddir* to *newdir* during the backup. To actually be effective, *olddir* must <yellow>exactly match</yellow> the path specification of the tablespace as it is defined on the source server. (But it is *not* an error if there's no tablespace in *olddir* on the source server โ no stress.) Meanwhile *newdir* is a directory in the receiving host's filesystem. Same rules as the main target directory: *newdir* need not exist already, but if it does exist it must be <red>empty</red>. Both *olddir* and *newdir* must be <hotpink>absolute paths</hotpink>. And if either path needs to contain an equal sign (=`), precede that with a backslash. This option can be specified multiple times for multiple tablespaces. ๐ฅ
If a tablespace is relocated this way, the symbolic links inside the main data directory are updated to point to the new location. So the new data directory is ready to be used for a new server instance with all tablespaces in the updated locations. Chef's kiss. ๐
Currently, this option only works with plain output format; it is ignored if tar format is selected.
--waldir=waldir โ Sets the directory to write WAL (write-ahead log) files to. By default WAL files will be placed in thepg_walsubdirectory of the target directory, but this option can be used to place them elsewhere. waldir must be an absolute path. And as with the main target directory: waldir need not exist already, but if it does exist it must be empty. This option can only be specified when the backup is inplainformat.- *
-X*method**, **--wal-method=*method*** โ Includes the required WAL (write-ahead log) files in the backup. This will include <cyan>all write-ahead logs generated during the backup</cyan>. Unless the methodnone` is specified, it is possible to start a postmaster in the target directory without needing to consult the WAL archive โ which means the output is a completely standalone backup. Self-sufficient. Independent. Living its best life. โจ
The following methods for collecting the write-ahead logs are supported:
n,noneโ Don't include write-ahead logs in the backup. That's it, that's the method.f,fetchโ The write-ahead log files are collected at the end of the backup. Therefore, it is necessary for the source server'swal_keep_sizeparameter to be set high enough that the required log data is not removed before the end of the backup.
โ ๏ธ If the required log data has been recycled before it's time to transfer it, the backup will fail and be unusable. Not a vibe.
When tar format is used, the write-ahead log files will be included in the base.tar file.
s,streamโ Stream write-ahead log data while the backup is being taken. This method will open a second connection to the server and start streaming the write-ahead log in parallel while running the backup. So it requires two replication connections, not just one. As long as the client can keep up with the write-ahead log data, using this method requires no extra write-ahead logs to be saved on the source server. Slay.
When tar format is used, the write-ahead log files will be written to a separate file named pg_wal.tar (if the server is a version earlier than 10, the file will be named pg_xlog.tar).
This value is the default. ๐
and bestie, we're not done yet โ there's more coming, so don't go anywhere ๐ฆ
-z,--gzipโ turns on gzip compression for tar output, at the default compression level. ๐ Heads up tho: compression is only a thing when you're using thetarformat, and the suffix.gzgets auto-slapped onto every tar filename. No cap.-Z level,-Z [{client|server}-]method[:detail],--compress=level,--compress=[{client|server}-]method[:detail]โ bestie, this one's asking for the backup to be compressed. If you includeclientorserver, that's you saying where the compressing happens. Compressing on the server saves transfer bandwidth but eats more server CPU. The default isclient, except when--targetis in play โ because then the backup isn't even going to the client, so server compression is the only thing that makes sense. And when-Xstream(which is the default, iykyk) is used, server-side compression does not get applied to the WAL. Wanna compress the WAL? Use client-side compression, or specify-Xfetch.
The compression method can be set to gzip, lz4, zstd, none (for no compression), or an integer (0 means no compression, anything greater than 0 means gzip). You can optionally add a compression detail string. If that detail string is an integer, it's the compression level. Otherwise it should be a comma-separated list of items, each shaped like keyword or keyword=value. Right now the supported keywords are level, long, and workers. โ ๏ธ You cannot use the detail string when the compression method is given as a plain integer.
If no compression level is specified, the default compression level is used. If you only give a level and never mention an algorithm, gzip compression is used when the level is greater than 0, and no compression is used when the level is 0.
When the tar format is used with gzip, lz4, or zstd, the suffix .gz, .lz4, or .zst (respectively โจ) gets automatically added to all tar filenames. When the plain format is used, client-side compression may not be specified โ but you can still ask for server-side compression. If you do, the server compresses the backup for transmission, and the client decompresses and extracts it.
When this option is used together with -Xstream, pg_wal.tar will be compressed using gzip if client-side gzip compression is selected, but will not be compressed if any other compression algorithm is selected, or if server-side compression is selected. Periodt.
The following command-line options control the generation of the backup and the invocation of the program: ๐ฌ
-c {fast|spread},--checkpoint={fast|spread}โ sets the checkpoint mode tofast(immediate) orspread(the default). (see Section 25.3.4)-C,--create-slotโ says that the replication slot named by the--slotoption should be created before the backup starts. If the slot already exists, you get an error. ๐จ-l label,--label=labelโ sets the label for the backup. If you don't specify one, the default value is "pg_basebackup base backup". ๐ท๏ธ-n,--no-cleanโ by default, whenpg_basebackupaborts with an error, it removes any directories it might have created before finding out it couldn't finish the job (like the target directory and the write-ahead log directory). This option stops the tidying-up, which makes it genuinely useful for debugging. ๐
Note that tablespace directories are not cleaned up either way.
-N,--no-syncโ by defaultpg_basebackupwaits for all files to be written safely to disk. This option makes it return without waiting โ faster, sure, but it means a subsequent operating system crash can leave the base backup corrupt. ๐ Generally this one's for testing and should not be used when creating a production installation.-P,--progressโ enables progress reporting. Turning this on gives you an approximate progress report during the backup. Since the database may change during the backup, it's only an approximation and might not land exactly at 100%. In particular, when the WAL log is included in the backup, the total amount of data can't be estimated in advance, and in that case the estimated target size will increase once it passes the total estimate without WAL. ๐-r rate,--max-rate=rateโ sets the maximum transfer rate at which data is collected from the source server. Lowkey useful for limiting the impact ofpg_basebackupon the server. Values are in kilobytes per second. Use a suffix ofMto mean megabytes per second. A suffix ofkis also accepted and has no effect. Valid values are between 32 kilobytes per second and 1024 megabytes per second. ๐๐จ
This option always affects transfer of the data directory. Transfer of WAL files is only affected if the collection method is fetch.
-S slotname,--slot=slotnameโ this option can only be used together with-X stream. It causes WAL streaming to use the specified replication slot. If the base backup is meant to be used as a streaming-replication standby using a replication slot, the standby should then use the same replication slot name asprimary_slot_name. That way the primary server doesn't remove any necessary WAL data in the time between the end of the base backup and the start of streaming replication on the new standby. ๐
The specified replication slot has to exist unless the option -C is also used.
If this option isn't specified and the server supports temporary replication slots (version 10 and later), then a temporary replication slot is automatically used for WAL streaming.
--sync-method=methodโ when set tofsync, which is the default,pg_basebackupwill recursively open and synchronize all files in the backup directory. When the plain format is used, the search for files will follow symbolic links for the WAL directory and each configured tablespace.
On Linux, syncfs may be used instead to ask the operating system to synchronize the whole file system that contains the backup directory. When the plain format is used, pg_basebackup will also synchronize the file systems that contain the WAL files and each tablespace. See recovery_init_sync_method for info about the caveats to be aware of when using syncfs. ๐ง
This option has no effect when --no-sync is used.
-v,--verboseโ enables verbose mode. It'll output some extra steps during startup and shutdown, and it'll also show the exact file name currently being processed if progress reporting is enabled too. ๐ฃ๏ธ--manifest-checksums=algorithmโ specifies the checksum algorithm that should be applied to each file included in the backup manifest. Currently the available algorithms areNONE,CRC32C,SHA224,SHA256,SHA384, andSHA512. The default isCRC32C.
If NONE is selected, the backup manifest won't contain any checksums. Otherwise it'll contain a checksum of each file in the backup using the specified algorithm. On top of that, the manifest will always contain a SHA256 checksum of its own contents. The SHA algorithms are significantly more CPU-intensive than CRC32C, so picking one of them may increase the time needed to complete the backup. ๐
Using a SHA hash function gives you a cryptographically secure digest of each file for users who wanna verify that the backup hasn't been tampered with, while the CRC-32C algorithm gives a checksum that's much faster to calculate; it's great at catching errors from accidental changes but is not resistant to malicious modifications. ๐ Note that, to be useful against an adversary who has access to the backup, the backup manifest would need to be stored securely elsewhere or otherwise verified not to have been modified since the backup was taken.
pg_verifybackup(1) can be used to check the integrity of a backup against the backup manifest.
--manifest-force-encodeโ forces all filenames in the backup manifest to be hex-encoded. If this option isn't specified, only non-UTF8 filenames are hex-encoded. This one's mostly intended to test that tools which read a backup manifest file properly handle this case. ๐งช--no-estimate-sizeโ stops the server from estimating the total amount of backup data that'll be streamed, which results in thebackup_totalcolumn in thepg_stat_progress_basebackupview always beingNULL.
Without this option, the backup starts by enumerating the size of the entire database, then goes back and sends the actual contents. That can make the backup take slightly longer, and in particular it'll take longer before the first data is sent. This option is useful for skipping that estimation time if it's too long. โฑ๏ธ
This option is not allowed when using --progress.
--no-manifestโ disables generation of a backup manifest. If this option isn't specified, the server will generate and send a backup manifest which can be verified usingpg_verifybackup(1). The manifest is a list of every file present in the backup, with the exception of any WAL files that may be included. It also stores the size, last modification time, and an optional checksum for each file. ๐--no-slotโ prevents the creation of a temporary replication slot for the backup.
By default, if log streaming is selected but no slot name is given with the -S option, then a temporary replication slot is created (if supported by the source server).
The main purpose of this option is to let you take a base backup when the server has no free replication slots. Using a replication slot is almost always preferred, because it prevents needed WAL from being removed by the server during the backup. ๐ก๏ธ
--no-verify-checksumsโ disables verification of checksums, if they're enabled on the server the base backup is taken from.
By default, checksums are verified and checksum failures result in a non-zero exit status. However, the base backup will not be removed in such a case, as if the --no-clean option had been used. Checksum verification failures will also be reported in the pg_stat_database view. ๐
The following command-line options control the connection to the source server: ๐
-d connstr,--dbname=connstrโ specifies parameters used to connect to the server, as a connection string; these will override any conflicting command line options. ๐ซ
This option is called --dbname for consistency with other client applications, but bestie, hear me out: since pg_basebackup doesn't connect to any particular database in the cluster, any database name you shove into the connection string gets ignored by the server. However โ a database name supplied that way does override the default database name (replication) for purposes of looking up the replication connection's password in ~/.pgpass. Also, middleware or proxies used in connecting to PostgreSQL might utilize the name for stuff like connection routing. And the database name can also be used by logical replication slot synchronization. iykyk ๐
-hhost**, **--host=*host*โ tells it the host name of the machine where the server's at. If the value starts with a slash, it's used as the directory for a Unix domain socket instead. Default comes from thePGHOSTenvironment variable if it's set, and if it's not, a Unix domain socket connection is attempted. โจ-pport**, **--port=*port*โ the TCP port, or the local Unix domain socket file extension, that the server is listening on for connections. Defaults to thePGPORTenvironment variable if that's set, otherwise a compiled-in default. ๐-sinterval**, **--status-interval=*interval*โ how many seconds between status packets sent back to the source server. Smaller values = more accurate monitoring of backup progress from the server. A value of zero disables periodic status updates completely, though an update will still be sent when requested by the server, so you don't get timeout-based disconnects. Default value is10seconds. โฑ๏ธ-Uusername**, **--username=*username*โ the user name to connect as. ๐ค-w,--no-passwordโ prevents issuing a password prompt. If the server requires password authentication and a password isn't available by other means, like a.pgpassfile, the connection attempt will fail. Super useful in batch jobs and scripts where there's no human around to type a password. ๐ค-W,--passwordโ forcespg_basebackupto prompt for a password before connecting to the source server.
This option is never essential, since pg_basebackup will automatically prompt for a password if the server demands password authentication. But likeโฆ pg_basebackup will waste a whole connection attempt just finding out the server wants a password. So sometimes it's worth typing -W to skip that extra connection attempt. ๐
Other options are also available, bestie:
-V,--versionโ prints thepg_basebackupversion and exits. ๐-?,--helpโ shows help aboutpg_basebackupcommand line arguments, and exits. ๐
๐ฟ ENVIRONMENT ๐ฟ
This utility, like most other PostgreSQL utilities, uses the environment variables supported by libpq (see Section 32.15). ๐ซถ
The environment variable PG_COLOR specifies whether to use color in diagnostic messages. Possible values are always, auto and never. ๐
๐ NOTES ๐
At the beginning of the backup, a checkpoint needs to be performed on the source server. That can take some time (especially if the option --checkpoint=fast is not used), and during it pg_basebackup will justโฆ appear to be idle. ๐ด Not me staring at a frozen terminal thinking it's broken.
The backup will include all files in the data directory and tablespaces, including the configuration files and any additional files placed in the directory by third parties โ except certain temporary files managed by PostgreSQL and operating system files. But only regular files and directories are copied, except that symbolic links used for tablespaces are preserved. Symbolic links pointing to certain directories known to PostgreSQL are copied as empty directories. Other symbolic links and special device files are skipped. See Section 54.4 for the precise details. ๐
In plain format, tablespaces will be backed up to the same path they have on the source server, unless the option --tablespace-mapping is used. Without this option, running a plain format base backup on the same host as the server will not work if tablespaces are in use, because the backup would have to be written to the same directory locations as the original tablespaces. โ ๏ธ no cap
When tar format is used, it is the user's responsibility to unpack each tar file before starting a PostgreSQL server that uses the data. If there are additional tablespaces, the tar files for them need to be unpacked in the correct locations. In this case the symbolic links for those tablespaces will be created by the server according to the contents of the tablespace_map file that is included in the base.tar file. ๐ฆ
pg_basebackup works with servers of the same or older major version, down to 9.1. However, WAL streaming mode (-X stream) only works with server version 9.3 and later, the tar format (--format=tar) only works with server version 9.5 and later, and incremental backup (--incremental) only works with server version 17 and later. version vibe check โจ
pg_basebackup will preserve group permissions for data files if group permissions are enabled on the source cluster. ๐
๐ EXAMPLES ๐
To create a base backup of the server at mydbserver and store it in the local directory /usr/local/pgsql/data:
$ pg_basebackup -h mydbserver -D /usr/local/pgsql/data
To create a backup of the local server with one compressed tar file for each tablespace, and store it in the directory backup, showing a progress report while running:
$ pg_basebackup -D backup -Ft -z -P
To create a backup of a single-tablespace local database and compress this with bzip2:
$ pg_basebackup -D - -Ft -X fetch | bzip2 > backup.tar.bz2
Heads up: this command will fail if there are multiple tablespaces in the database. ๐ญ
To create a backup of a local database where the tablespace in /opt/ts is relocated to ./backup/ts:
$ pg_basebackup -D backup/data -T /opt/ts=$(pwd)/backup/ts
To create a backup of the local server with one tar file for each tablespace compressed with gzip at level 9, stored in the directory backup:
$ pg_basebackup -D backup -Ft --compress=gzip:9
obsessed with these tbh ๐
๐ SEE ALSO ๐
pg_dump(1), Section 27.4.6 ๐ฆ
Okay bestie that's the whole page!! ๐ This was PostgreSQL 18.6, dated 2026, and you just read PG_BASEBACKUP(1) โ go forth and back up those clusters, you absolute icon. ๐
โจ๐
๐ฆ where this page comes from
- opensuse-leap 16.0: postgresql18 18.6-160000.1.1 ยท PostgreSQL
- opensuse-leap 16.0: postgresql18 18.6-160000.1.1 ยท PostgreSQL
- opensuse-leap 16.0: postgresql18 18.6-160000.1.1 ยท PostgreSQL
- opensuse-leap 16.0: postgresql18 18.6-160000.1.1 ยท PostgreSQL
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms