Sub topic 1
What You Need to Recover from: RPO, RTO, and Failure Scenarios
Prerequisites
This chapter assumes you can run basic SQL in psql, use the Linux command line, and know that a PostgreSQL server holds several databases in one cluster. You should also know what a transaction is.
Recovery Goals
Two numbers drive every backup decision. The recovery point objective (RPO) is the most data you can afford to lose, measured as time. An RPO of 24 hours means a nightly backup is acceptable. The recovery time objective (RTO) is the longest you can afford to be down while restoring.
Common failure scenarios include:
- A developer runs an accidental DROP TABLE.
- The disk holding the data directory fails.
- Data is corrupted, and the problem is found days later.
- The whole server or data center is lost.
Each scenario favors a different backup method, so list the likely failures before you choose one.
Logical versus Physical Backups
A logical backup stores database contents as SQL or as a custom archive. The pg_dump tool creates it. Logical backups can restore one table or one database, and they can move data across PostgreSQL versions. They cannot replay changes made after the dump, and restoring large databases is slow.
A physical backup copies the files in the data directory. The pg_basebackup tool creates it. Physical backups restore a whole cluster quickly. Paired with WAL archiving (a stored log of every change), they allow point-in-time recovery. They cannot restore a single table without restoring the whole cluster.
Dumping a Single Database with pg_dump
The pg_dump program connects to the server and writes one database to a file. This command writes the database mydb in custom format:
pg_dump -h localhost -U postgres -Fc -f mydb.dump mydbThe -Fc option selects custom format, -f names the output file, and the final argument names the database. pg_dump does not save roles or tablespaces. You handle those separately.
Choosing a Dump Format
| Format | Flag | Restore tool | Notes |
|---|---|---|---|
| Plain | -Fp | psql | Readable SQL text, default format |
| Custom | -Fc | pg_restore | Compressed, allows selective restore |
| Directory | -Fd | pg_restore | Allows parallel jobs |
| Tar | -Ft | pg_restore | Uncompressed archive |
Exercise
Exercise
A database must be back within 30 minutes, and you need only one table restored. Which dump format do you choose, and which tool restores it?
Show answer
Choose custom format (-Fc) and restore with pg_restore. Its -t option restores a single named table without loading the whole dump. Plain SQL would require editing the file by hand.