Skip to content

Backup and Restore

Dmitri Chudinov edited this page Aug 28, 2026 · 1 revision

Backup and restore

Untested backups are not backups (ADR-0019). This page is what exists, what to verify, and how to get the farm back.

The full procedure, with every command, is docs/RUNBOOK-BACKUP-RESTORE.md.


1. What is backed up, and why twice

Covers
Logical dump (pg_dump) "Something was deleted" — restore into a scratch database and copy across. Survives a major-version change
Base backup + archived WAL "Undo the last twenty minutes", and "the box is gone". Point-in-time recovery
Blob store Model meshes and prepared plates. The database holds references; the disk holds the bytes

A logical dump alone cannot undo twenty minutes. A physical backup alone cannot restore across a major version. Hence both.

2. Verify WAL archiving on day one

This is the single most important paragraph on this page.

The archive target is mounted into a container that runs as uid 70, and the mount is owned by root until somebody changes it. The server then cannot write a single segment — and nothing surfaces. The farm runs normally, archive_command fails silently on every segment, and because a segment cannot be recycled until it is archived, pg_wal grows until the data disk fills and PostgreSQL stops. Meanwhile the recovery point does not exist.

On the development stack that ran to 1 385 consecutive failures, zero successes and 23 GB of WAL before anybody looked.

backup-init now chowns the mount before PostgreSQL starts, so a fresh deployment is correct by construction. Verify anyway. It costs one command, and it is the only thing that distinguishes a working backup from a believed one:

docker exec printorian-postgres psql -U printorian -d printorian -c "select archived_count, failed_count, last_failed_error from pg_stat_archiver;"

failed_count must be 0 and archived_count must climb. If it does not, nothing below this line will save the farm.

/health/ready also reports wal_archiving: degraded when the archive stops keeping up.

3. The schedule

Timer When
printorian-backup.timer 03:00 daily, Persistent=true
printorian-drill.timer Sundays 04:00

The dump runs inside the postgres container, so client and server versions cannot drift. pg_archivecleanup runs with it, which is what keeps archived WAL from growing without bound — it runs inside backup.sh and nowhere else.

Running it by hand on the host:

PRINTORIAN_BACKUP_ROOT=/srv/printorian/backup PRINTORIAN_DB_PORT=5433 backend/scripts/backup.sh

/backup must be on a different physical disk from the data directory. A backup that dies with the disk it is protecting against is decoration. The development docker-compose.yml uses a named volume, which is right for a laptop and wrong for the farm.

A failing timer is visible to systemctl --failed with its exit status and journal, which is half the reason these are timers rather than cron jobs. The other half is Persistent=true: a farm host is powered down more often than a server, and a backup silently skipped because the shop was closed on Monday is exactly the failure this guards against.

4. The drill

python -m scripts.restore_drill /backup/dumps/printorian-<latest>.dump

It restores last night's dump into a throwaway database, runs alembic check against it, and asserts that users, orders and payment_notifications are not empty.

That last assertion earns its place. A backup script pointed at the wrong database name produces a perfectly valid, perfectly restorable, empty dump every night, and every other check passes. It is the failure most likely to go unnoticed for months and the one most catastrophic to discover during an incident.

A failing drill is an incident in its own right — the farm is currently running without a usable backup, whatever the file listing suggests.

The drill runs, and a failing drill still reaches nobody. There is no alerting (#22). Somebody has to look.

5. The WAL archive is gzipped — your restore_command must know

restore_command = 'gunzip -c /backup/wal/%f.gz > %p'

A restore_command that copies %f finds nothing, and PostgreSQL reports the recovery as complete at the last segment it could read rather than failing. This is a mistake that looks like success and loses everything after the base backup.

Why it is worth the extra step: compression measured 27× over a real archive — 80 MiB of segments to 2.95 MiB — and near-empty segments (most of them, because archive_timeout=1min switches on time rather than on fullness) go from 16 MiB to about 16 KiB. At this farm's idle rate that is the difference between filling a 98 GiB backup disk in 22 days and in over a year.

The archive command writes to %f.tmp and renames, so a segment interrupted by a full disk never appears under its final name.

Migrating an existing archive. Turning compression on leaves a mix, and pg_archivecleanup -x .gz prunes only the compressed half — the legacy segments sit there for ever. After the first successful base backup under the new setting, gzip the stragglers or delete those preceding that backup.

6. Restoring

Wrong data, right disk

Restore into a scratch database and copy across. Do not restore over the live one.

createdb -U printorian printorian_recovered
pg_restore -U printorian -d printorian_recovered --no-owner /backup/dumps/printorian-<stamp>.dump

Point in time — "undo the last twenty minutes"

  1. Stop the API and the workers. New writes racing a recovery is bad; the workers are the ones that matter, because the scheduler will happily dispatch against a half-restored queue.
  2. Move the current data directory aside — do not delete it. If the recovery target turns out wrong you will want it back, and it is the only remaining copy of anything written after the last archived segment.
  3. Restore the most recent base backup into a clean data directory.
  4. postgresql.auto.conf:
    restore_command = 'gunzip -c /backup/wal/%f.gz > %p'
    recovery_target_time = '2026-08-11 14:20:00+03'
    recovery_target_action = 'promote'
    
  5. touch recovery.signal, start PostgreSQL, watch the log until it reports consistent recovery.
  6. Verify before letting anything write. Check the row you know was lost is back and the row you know was bad is gone. Then start the API, then the workers — in that order, so a human sees the state before the scheduler acts on it.

The box is gone

  1. Install PostgreSQL of the same major version. A physical backup will not restore across major versions — that is exactly the case the logical dump covers.
  2. Restore the base backup and replay all WAL, with no recovery target.
  3. Restore the blob store to the path PreparedPlate.storage_path refers to.
  4. Restore PRINTORIAN_SECRET_KEY from escrow — see §7.
  5. Run alembic check before starting the application. Drift means the backup predates a migration, and alembic upgrade head comes first.

7. Backups are secret material

The dump contains password_hash for every account and access_code_encrypted for every printer.

  • Encrypt at rest and in transit. Anyone who can read the archive can attack every password in it offline. restic encrypts by default; rclone needs crypt configured.

  • Escrow PRINTORIAN_SECRET_KEY separately from the backups. Printer access codes are encrypted with it (ADR-0014), so a restored database without that key gives back every order, every price and every job — and a fleet that cannot be driven until somebody walks to each machine and reads its code off the panel. That is a half-restore, and it is discovered during the incident.

    Escrow it somewhere that does not depend on the farm: a password manager, a sealed envelope, anywhere that is not the box being restored.

8. Blobs and database must stay consistent

A restored database naming a plate that is not in the restored blob store is a broken cache — discovered at dispatch, silently, when a job uploads nothing to a printer.

Two cheap rules:

  1. Write the blob before the row. Then a row can only ever reference a blob that already existed.
  2. Snapshot the blobs before the database. Combined with (1), the database can only reference blobs already in the snapshot. The reverse order guarantees the opposite.

Content addressing makes the blob sync cheaply incremental and a partial sync detectable: the name is the checksum.

9. The largest remaining gap

Off-site. Every copy of the farm's data is on one machine (#16). The recipe exists; the destination and its credentials are farm-specific and not committed:

restic -r <remote> backup /backup/dumps /backup/base /backup/wal

Compression buys time on the local disk. It does nothing about fire, theft, or that VM being deleted.

10. On-prem PostgreSQL settings

docker-compose.yml carries dev-scale numbers because developers run it too. On the farm's dedicated box, derive from its RAM:

Setting Value Why
shared_buffers 25 % of RAM The rest is left to the OS page cache
effective_cache_size 60–75 % of RAM Not an allocation — it tells the planner how much cache to assume, and getting it wrong makes it choose sequential scans over index scans
work_mem RAM ÷ (max_connections × 3) Per sort, per node — a generous value times a busy moment is how a box runs out of memory
maintenance_work_mem 512 MB – 2 GB Index builds and autovacuum
max_connections pool + overflow per process, plus headroom Must exceed what the application can open, or the pool exhausts against the server rather than against itself

The application's own guards — statement_timeout, lock_timeout, idle_in_transaction_session_timeout — are set per connection in core/db.py, so a restore onto a fresh box inherits them without anyone remembering to.

11. Degraded mode

Printers keep printing while the server is down, and reconcile on reconnect. Worth confirming during any recovery: a job the database believes is printing may have finished an hour ago, and the reconnect has to absorb that rather than treat it as an impossible transition.


A note on one stale line. The runbook's §9 still says telemetry_retention_days defaults to 0 (retention off). It does not — the default is 90, because rollups now summarise every closed hour before anything is dropped and the drop cutoff is clamped to what has actually been summarised. The code is the authority.

Clone this wiki locally