Database Backup & Restore
For an operator backing up or recovering Canopy’s PostgreSQL databases. The database inventory and topology are owned by Deployment Guide › Data tier; this page is the procedure. The devstack’s cargo xtask migrate snapshot / rollback pair is developer tooling, not this procedure (Devstack Migration Snapshot & Rollback).
Inventory
Eighteen logical databases (DATABASES in xtask/src/cmd/migrate.rs) on up to six instances; the instance-to-database map is Deployment Guide › Data tier. The array below repeats it in the form the commands need.
canopy_tanf and canopy_medicaid contain Federal Tax Information (fti_audit_log, fti_audit_log_archive, fti_audit_log_v2, fti_tax_data — services/canopy-{tanf,medicaid}/migrations/). Their dumps and WAL archives follow FTI data handling.
Backup
Preconditions: pg_dump at the target’s major version (19); disk for the dumps; the FTI encryption tooling below. PGHOST/PGPORT/PGUSER are your environment’s; the loop keys each database to its instance so a hand-maintained per-instance script cannot drift from the inventory.
#!/usr/bin/env bash
set -euo pipefail
TIMESTAMP=$(date -u +%Y%m%dT%H%M%SZ)
BACKUP_DIR="/backups/${TIMESTAMP}"; mkdir -p "$BACKUP_DIR"
# instance:database — the isolated topology; under --shared-db every instance is "postgres".
DATABASES=(
postgres:canopy_rules postgres:canopy_persons postgres:canopy_applications
postgres:canopy_eligibility postgres:canopy_verification postgres:canopy_enrollment
postgres:canopy_renewals postgres:canopy_notices postgres:canopy_exchange
postgres:canopy_appeals postgres:canopy_reporting postgres:canopy_security
postgres:canopy_web
postgres-snap:canopy_snap postgres-tanf:canopy_tanf postgres-medicaid:canopy_medicaid
postgres-caps:canopy_caps postgres-wic:canopy_wic
)
for ENTRY in "${DATABASES[@]}"; do
HOST=${ENTRY%%:*}; DB=${ENTRY#*:}
pg_dump --host="$HOST" --port=5432 --username=canopy \
--format=custom --compress=9 --file="${BACKUP_DIR}/${DB}.dump" "$DB"
echo "backed up ${DB} from ${HOST}"
done
Encrypt canopy_tanf.dump and canopy_medicaid.dump immediately (below); the unencrypted files must not persist.
FTI data handling
IRS Publication 1075 controls apply to every artifact holding canopy_tanf or canopy_medicaid data — dumps, base backups and WAL archives (Pub 1075 §4.7):
-
Encryption at rest: AES-256 (or an equivalent FIPS 140-2 validated algorithm) immediately after creation.
-
Access: storage reachable only by personnel with a current IRS background investigation.
-
Audit: every FTI backup and restore is recorded in the canopy-security audit trail (Post-recovery validation, last step).
-
Retention and destruction: destroy when no longer needed, never past the IRS-mandated period; log the destruction.
-
Transport: TLS 1.2+ for any transfer.
for DB in canopy_tanf canopy_medicaid; do
gpg --symmetric --cipher-algo AES256 --output "${BACKUP_DIR}/${DB}.dump.gpg" "${BACKUP_DIR}/${DB}.dump"
shred -u "${BACKUP_DIR}/${DB}.dump"
done
# restore side: gpg --decrypt --output "${BACKUP_DIR}/${DB}.dump" "${BACKUP_DIR}/${DB}.dump.gpg"; delete after the restore.
Restore from dumps
-
Stop every service that reads or writes the target databases (devstack:
cargo xtask dev stop; production: scale the services to zero). -
Restore each dump into its instance with the same
instance:databasetable;--clean --if-existsdrops existing objects first:for ENTRY in "${DATABASES[@]}"; do HOST=${ENTRY%%:*}; DB=${ENTRY#*:} pg_restore --host="$HOST" --port=5432 --username=canopy --dbname="$DB" \ --clean --if-exists --no-owner "${BACKUP_DIR}/${DB}.dump" done -
Start the services. Each one applies any migrations the dump predates during boot (
crates/canopy-api/src/bootstrap.rs); a deployment that runs withCANOPY_<SVC>__SKIP_MIGRATIONS=truerunscanopy-manage migrate apply --service canopy-<svc>first (Deployment Guide › Migrations). Devstack:cargo xtask dev start(add--shared-dbif that is how it was running).
Rollback of a restore is another restore, from the dump you took before starting (take one).
Point-in-Time Recovery
Configure continuous WAL archiving on every instance. PITR is the production rollback path for schema regressions (ADR-016); migrations are forward-only and there are no down files.
When PITR is the right answer
| Situation | Right tool |
|---|---|
A migration shipped with a wrong default, a bad index or an added column — no data lost |
Forward-fix migration. PITR would also discard every legitimate commit since; the forward fix does not. |
A migration dropped a populated column or deleted rows it should not have |
PITR. A forward fix cannot recover data the WAL already shipped a destructive change for. Restore the base backup and replay to the moment before the statement. |
An application bug wrote bad data in a known window (no schema change) |
PITR if the volume is large, a corrective |
The cluster is compromised; every write since time T is suspect |
PITR to T; everything after is treated as compromised. |
One database must return to a known-good moment for incident reproduction |
PITR of that database’s instance only, the others keep running. |
Pre-PITR checklist
-
Recovery target: the latest moment before the destructive event. Round down if unsure — over-rolling is recoverable, under-rolling silently keeps the bad state.
-
Communicate: PITR is a service-down operation. Post in the incident channel, freeze deploys, notify stakeholders.
-
Preserve the broken state: a final
pg_basebackuptaggedpre-pitr-broken-<timestamp>before the data directory is touched. -
WAL coverage: a continuous sequence from the most recent base backup through the target time. A gap means no PITR — only a plain base-backup restore.
ls /wal_archive/ | grep -v '\.backup$' | sort | head -3 ls /wal_archive/ | grep -v '\.backup$' | sort | tail -3 -
Stop the services that touch the target database; confirm zero connections:
SELECT count(*) FROM pg_stat_activity WHERE datname = '<db>' AND pid <> pg_backend_pid(); -
Record the operator, target and motivation in the incident log; the last validation step writes them into the audit chain.
Single-database PITR
For one program instance (postgres-snap here; a devstack container is <project>-postgres-snap-1, project = the compose project name). Stopping it does not affect the other instances.
-
Stop the instance:
docker stop <project>-postgres-snap-1 -
Move — do not delete — the data directory so the broken state stays available for forensics:
docker run --rm -v canopy_postgres_snap_data:/data --user 0 alpine \ sh -c "mv /data/18/docker /data/18/broken-$(date -u +%Y%m%dT%H%M%SZ)" -
Restore the most recent base backup taken before the target time (
70:70is the alpine postgres image’spostgresuser):# canopy_postgres_snap_base stands for the volume or path holding your base backup (not a compose volume) docker run --rm -v canopy_postgres_snap_base:/base -v canopy_postgres_snap_data:/dst --user 0 alpine \ sh -c "mkdir -p /dst/18/docker && cp -a /base/. /dst/18/docker/ && \ touch /dst/18/docker/recovery.signal && chown -R 70:70 /dst/18" -
Append the recovery configuration to the restored
postgresql.auto.conf:restore_command = 'cp /wal_archive/%f %p' recovery_target_time = '<RECOVERY_TARGET_UTC>' recovery_target_action = 'promote' -
Start the instance and watch it replay to the target, then promote:
docker start <project>-postgres-snap-1 docker logs -f <project>-postgres-snap-1 | grep -E 'recovery|consistent'Expect
starting point-in-time recovery to <target>,consistent recovery state reached,recovery stopping before commit of transaction <xid>, time <stop-time>,archive recovery complete. The "stopping before commit" line confirms replay halted at the requested target. -
Run Post-recovery validation before any service comes back.
Cross-service PITR
When several databases must return to the same wall-clock moment (a cross-service migration ran in parallel):
-
Run the checklist for every affected database, WAL coverage included.
-
Stop every affected instance at once — a partially rolled fleet is worse than total downtime:
docker stop <project>-postgres-1 <project>-postgres-snap-1 <project>-postgres-tanf-1 \ <project>-postgres-medicaid-1 <project>-postgres-caps-1 <project>-postgres-wic-1 -
Repeat the single-database procedure per instance with the same
recovery_target_time. -
Bring the shared instance up first (persons, applications and the other shared services), then the program instances — the order
cargo xtask dev start's health gates follow. -
Run the cross-service validation before any application restart: the ADR-014 audit chain spans services and a break is reportable under Pub 1075 §9.
Post-recovery validation
Run all of it before re-enabling traffic; any failure means the recovery is not safe to bring online.
Hash-chain integrity (ADR-014)
Chain validation goes through the unified /v1/security/chain/* routes (crates/canopy-contracts-security/src/paths.rs; canopy-security API) with a service-or-admin token. SECURITY_URL below is canopy-security’s base URL (container port 8012; on a devstack read the host port from .ports.env).
CANOPY_SECURITY__CHAIN_V2_VERIFY_ENABLED is false (the default), chain/status reports unknown → 503 and chain/verify returns 503 verifier_unavailable. That is not a restore failure; with the verifier off, chain validation is the manual re-hash of the affected window in Security Operations. The steps below apply with the verifier on.
-
Trigger a full verification per family — a durable job, never a synchronous walk:
curl -sf -X POST -H "Authorization: Bearer $ADMIN_TOKEN" -H "Content-Type: application/json" \ -d '{"family":"audit","loop":"family-full"}' "$SECURITY_URL/v1/security/chain/verify" | jq . # FTI families: -d '{"family":"fti","service":"canopy-tanf","loop":"family-full"}' and canopy-medicaid likewiseCLI equivalent:
canopy security chain-verify --family audit --wait(tools/canopy-cli/src/main.rs;--family fti --service canopy-tanffor an FTI family). -
Poll each job (
GET $SECURITY_URL/v1/security/chain/verify-jobs/$JOB_ID) tostate: "done"with runoutcome: "ok".state: "error"withintegrity_rejectedmeans a finding latched an incident — escalate per ADR-014 §7 and the chain-v2 incident-resolution runbook in Security Operations; never re-run to green. -
Confirm status per family:
GET $SECURITY_URL/v1/security/chain/status?family=audit(and?family=fti&service=canopy-tanf|canopy-medicaid).healthyorverifying(200) is acceptable; any 503 state (unknown,stale,error,breached) blocks bringing traffic back.
Signed-determination integrity
PITR can stop before a transaction that wrote a signed determination. Compare each program’s _determinations table between the broken (forensic) copy and the recovered one — for example SELECT count(), max(created_at) FROM snap_determinations; in both. The recovered count must be ≤ the broken count and max(created_at) ≤ recovery_target_time; anything else means the target overshot.
Spot checks
-
Every restarted service answers 200 on
/readyz(Deployment Guide › Health). -
Row counts in
canopy_persons,canopy_applicationsand the program databases are within the expected pre-incident range. -
A known-good fixture evaluates as expected through canopy-rules (
POST /v1/evaluate). -
On a devstack,
cargo xtask test --integrationpasses against the recovered stack.
Record the recovery in the audit chain
Do not INSERT into audit_events by hand: event_id has no default and the hash chain is computed in application code at insert time (services/canopy-security/migrations/20260326000000_create_security_tables.sql, 20260402000001_add_hash_chain.sql, 20260603120000_audit_events_append_only_guard.sql), so a raw row either fails or creates the very chain break you are checking for. Post the marker through the ingest route instead, which mints the id and chains the row like any other event (POST /v1/security/audit/ingest, service-class token required — canopy-security API):
curl -sf -X POST -H "Authorization: Bearer $SERVICE_TOKEN" -H "Content-Type: application/json" \
"$SECURITY_URL/v1/security/audit/ingest" -d '{
"event_type": "pitr.recovery_completed",
"source_service": "canopy-security",
"action": "recovered_to_point_in_time",
"resource_type": "database_cluster",
"resource_id": "postgres-snap",
"user_id": "<operator-username>",
"metadata": {"recovery_target": "<target-utc>", "incident_ticket": "<ticket-id>",
"broken_state_snapshot": "pre-pitr-broken-<timestamp>"},
"programs": []
}'
A 202 means the marker is chained; a later chain/status returning to healthy then carries an operator-attributable recovery record instead of an unexplained gap.
postgres:18-alpine container on 2026-05-03 (#353); the cross-service, encrypted-WAL and FTI arms have not been exercised and should be rehearsed against staging when the production WAL archive lands.