Sub topic 8
Speeding up large dumps and restores with parallel jobs
A single-threaded pg_dump or pg_restore uses one CPU core and one connection, however large the server is. On a multi-hundred-gigabyte database this can turn a restore into an overnight job. The -j option runs several workers at once. This chapter covers how it works, what it needs, and where it stops helping.
It assumes you can already run pg_dump -Fc and pg_restore, and that you know the dump formats from the earlier chapters.
What `-j` parallelizes
Both tools accept -j N (or --jobs=N), but they parallelize different work.
| Tool | Formats that work with `-j` | Unit of parallel work |
|---|---|---|
| `pg_dump` | Directory (`-Fd`) only | One table's data per worker |
| `pg_restore` | Custom (`-Fc`) and directory (`-Fd`) | Table data loads, index builds, constraint creation |
Plain SQL dumps are a single text stream, so neither tool can split them. Tar format cannot be restored in parallel. Custom format can be restored in parallel but not dumped in parallel, because the dump is written as one sequential file.
Parallel dump
A parallel dump needs the directory format. pg_dump writes one compressed file per table, plus a table of contents file named toc.dat.
pg_dump -U postgres -Fd -j 4 -f mydb_dir mydbThe target directory must not exist, or must be empty. pg_dump creates it.
With -j 4, pg_dump opens five connections: one leader and four workers. Check that max_connections has room for them, along with your normal traffic.
Workers must all see the same data, or the dump would be inconsistent between tables. The leader exports a snapshot, and each worker imports it. You can see the connections while the dump runs:
SELECT pid, application_name, state, left(query, 60) AS query
FROM pg_stat_activity
WHERE datname = 'mydb'
AND application_name = 'pg_dump';Limits of parallel dump
- One table is one job. A single 400 GB table is dumped by one worker, however many you ask for.
pg_dumpstarts the largest tables first so that big ones do not finish last, but it cannot split a table. A database dominated by one huge table gains little. - Locks can make the dump fail. The leader takes
ACCESS SHARElocks on every table it will dump. Each worker then requests the same lock again. If another session has queued anACCESS EXCLUSIVElock in between (fromALTER TABLE,TRUNCATE,VACUUM FULL, orDROP), the worker's request would deadlock, so the dump fails instead. Avoid schema changes and table rewrites while a parallel dump runs. - Standbys. Dumping from a hot standby works with parallel jobs on PostgreSQL 10 and later. On older servers you need
--no-synchronized-snapshots, which gives up the consistency guarantee. - Disk and network. Several workers can saturate the disk or the network before they saturate the CPU. If the dump writes to the same disk the database reads from, more jobs may slow both.
Parallel restore
Restore from the directory (or custom) format with -j:
createdb -U postgres mydb_restored
pg_restore -U postgres -j 4 -d mydb_restored mydb_dirRestoring is where parallelism pays off most, because loading data is only part of the work. After the rows are in, PostgreSQL must build every index, validate every constraint, and create every foreign key. These steps are CPU heavy, and pg_restore spreads them across workers. It reads the dependency information in the table of contents, so a worker never builds an index before its table has loaded.
Rules and restrictions:
- No
--single-transaction. A single transaction needs one connection, sopg_restorerejects-jcombined with--single-transaction. You choose between speed and all-or-nothing behavior. - Custom format needs a seekable file. Workers read different parts of the file at once, so you cannot pipe a custom dump into
pg_restore -jfrom standard input. The directory format has no such limit. - Errors do not stop the restore by default. Without
--exit-on-error(-e),pg_restorelogs errors and carries on. Add-eif you want it to stop at the first failure, and check the output either way. --createneeds a different connection database. With-C, connect to an existing database such aspostgreswith-d postgres.pg_restorethen creates the target database and reconnects to it.
pg_restore -U postgres -j 4 -C -d postgres --no-owner mydb_dirDump and restore job counts are independent
You do not have to use the same -j value for both steps. A dump made with -j 2 can be restored with -j 8 on a bigger machine. Pick each value for the machine and load it will run under.
Choosing the number of jobs
A starting point is the number of CPU cores on the machine doing the work, then adjust by measurement.
| Situation | Suggested start |
|---|---|
| Dump from a busy production primary | 2 to 4. Leave capacity for normal queries. |
| Dump from a replica or an idle server | Number of cores, limited by disk throughput |
| Restore into a new server with no other load | Number of cores |
| Restore with many large indexes | Number of cores, with a raised `maintenance_work_mem` |
Time a few runs with different values on a representative copy. Going from 1 to 4 jobs often helps a lot. Going from 8 to 16 may not help at all if the disk is the bottleneck.
Server settings that help a large restore
A restore into a new, empty database does not need to be careful about durability, because you can rerun it if it fails. These settings are common on the target server for the duration of a restore:
maintenance_work_mem = 2GB
max_wal_size = 32GB
checkpoint_timeout = 30min
synchronous_commit = offmaintenance_work_memis the memory each index build can use. Each worker may use that much, so size it as the memory budget divided by-j.- A larger
max_wal_sizeand a longercheckpoint_timeoutmean fewer forced checkpoints during the bulk load. synchronous_commit = offavoids waiting for WAL flushes on each commit. It risks losing the last few commits on a crash, which does not matter for a restore you would rerun.
Do not disable fsync on a server that will hold real data afterward. Return the other settings to their normal values when the restore is finished, and run ANALYZE on the restored database, since a dump does not carry planner statistics.
Worked example: measure the difference
This script dumps and restores the same database serially and in parallel, so you can compare the times on your hardware. It assumes a database named mydb and a role postgres that can connect without a password prompt.
#!/usr/bin/env bash
set -euo pipefail
DB=mydb
JOBS=4
rm -rf /tmp/dump_serial /tmp/dump_parallel
echo "Serial dump (directory format, -j 1)"
time pg_dump -U postgres -Fd -j 1 -f /tmp/dump_serial "$DB"
echo "Parallel dump (-j $JOBS)"
time pg_dump -U postgres -Fd -j "$JOBS" -f /tmp/dump_parallel "$DB"
for j in 1 "$JOBS"; do
dropdb -U postgres --if-exists "${DB}_test"
createdb -U postgres "${DB}_test"
echo "Restore with -j $j"
time pg_restore -U postgres -j "$j" -e -d "${DB}_test" /tmp/dump_parallel
done
dropdb -U postgres "${DB}_test"Use -e here so a failed restore does not produce a misleadingly fast time.
Common mistakes
- Using
-jwith-Fconpg_dump. The tool exits with an error saying parallel backup is only supported by the directory format. - Setting
-jhigher thanmax_connectionsallows, which makes workers fail to connect. - Running a parallel dump during a migration that alters tables.
- Expecting a speedup on a database with one dominant table.
- Forgetting
ANALYZEafter restore, then blaming the restore for slow queries.
Exercise
You run pg_dump -U postgres -Fc -j 4 -f mydb.dump mydb and it fails. What is the cause, and what two changes would let you dump in parallel and restore in parallel?
Show answer
Parallel dump supports only the directory format, so -Fc with -j is rejected. Change the format to -Fd and give -f a directory path that does not exist yet, for example pg_dump -U postgres -Fd -j 4 -f mydb_dir mydb. Restore it with pg_restore -U postgres -j 4 -d mydb_restored mydb_dir.
Exercise
A colleague wants a parallel restore that rolls back everything if any statement fails. They run pg_restore -j 8 --single-transaction. Why does this not work, and what do they give up by choosing each option?
Show answer
A single transaction runs on one connection, so pg_restore does not allow --single-transaction together with -j. With -j you get speed but no all-or-nothing behavior, so a failed restore can leave a partly loaded database (use -e to stop early and drop the database to retry). With --single-transaction you get a clean rollback on failure but only one worker.
Exercise
A database has one table of 500 GB and fifty tables of 1 GB each. Will pg_dump -Fd -j 8 take about one eighth of the serial time? Explain.
Show answer
No. Each table's data is dumped by a single worker, so the 500 GB table takes as long as one worker needs for it. The other workers finish the small tables early and then sit idle. The total time is close to the time for the large table alone.