Scope: PostgreSQL database backup, restore, and disaster recovery for NukeLab
Tables: Includes partitioned time-series tables (activity_logs,server_metrics,request_metrics)
# Full backup (schema + data + partitions)
./nukelabctl backup
# Restore from backup (drops and recreates the database — asks for
# confirmation; pass --yes to skip the prompt, e.g. in scripts)
./nukelabctl restore backups/nukelab_backup_YYYYMMDD_HHMMSS.sql
# Verify after restore
./nukelabctl exec backend python scripts/db_profiler.py table-sizes
./nukelabctl exec backend python scripts/db_profiler.py partitions --table activity_logsUses pg_dump — includes schema, partitions, extensions, and data.
# Full backup (postgres container must be running)
# Using nukelabctl:
./nukelabctl backup
# Or directly with your container engine:
docker exec -i nukelab-postgres pg_dump \
-U nukelab -d nukelab --clean --if-exists --create \
> nukelab-backup-$(date +%Y%m%d).sqlWhat --clean --if-exists does: Adds DROP IF EXISTS before CREATE, so restore is idempotent.
Verification:
# Check file size
ls -lh nukelab-backup-*.sql
# Count tables in backup
grep -c "^CREATE TABLE" nukelab-backup-*.sqlFor large datasets, back up only recent partitions + full schema.
BACKUP_FILE="nukelab-recent-$(date +%Y%m%d).sql"
# 1. Schema only (parent tables, extensions, indexes)
docker exec -i nukelab-postgres pg_dump \
-U nukelab -d nukelab --schema-only > "$BACKUP_FILE"
# 2. Append recent partitions (last 3 months)
THIS_MONTH=$(date +%Y%m)
for m in 0 1 2; do
ym=$(date -d "+$m month" +%Y%m)
for table in activity_logs server_metrics request_metrics; do
part="${table}_y${ym:0:4}m${ym:4:2}"
echo "-- Backing up partition: $part" >> "$BACKUP_FILE"
docker exec -i nukelab-postgres pg_dump \
-U nukelab -d nukelab \
--data-only --table="$part" >> "$BACKUP_FILE"
done
done
# 3. Append non-partitioned tables
for tbl in users servers volumes shared_workspaces notifications; do
docker exec -i nukelab-postgres pg_dump \
-U nukelab -d nukelab \
--data-only --table="$tbl" >> "$BACKUP_FILE"
doneFor point-in-time recovery (PITR), enable WAL archiving in compose.yml:
# In compose.yml, postgres service command:
- -c
- archive_mode=on
- -c
- archive_command='cp %p /backups/wal/%f'
- -c
- wal_level=replicaStorage requirement: WAL files are ~16 MB each. A busy system generates ~1 GB/hour.
./nukelabctl restore drops and recreates the database with WITH (FORCE),
restores the dump, and stamps the current image's Alembic head.
Before restoring, stop workers/Beat or enable maintenance mode so no writes
occur during the drop/recreate. Keep Postgres and the backend container running;
restore uses the backend image for the Alembic stamp.
# 1. Ensure the stack is running (Postgres and backend are required)
./nukelabctl start
# 2. Restore; the command asks for confirmation unless --yes is supplied
./nukelabctl restore backups/nukelab_backup_YYYYMMDD_HHMMSS.sql
# 3. Restart so the backend reconnects cleanly
./nukelabctl restart
# 4. Verify
./nukelabctl exec backend python scripts/db_profiler.py table-sizes
./nukelabctl exec backend python scripts/db_profiler.py partitions --table activity_logs
curl -s -H "Authorization: Bearer $ADMIN_TOKEN" \
http://localhost:8080/api/admin/health/monitoring \
| jq '.system.services.partitions'For a rollback to an older release, use --stamp <previous-revision> with the
revision recorded in the pre-migration snapshot filename; see the rollback
runbook in PRODUCTION-DEPLOYMENT.md.
# 1. Install the stack and start it with the same pinned release
./nukelabctl start
# 2. Copy the dump to the new host, then restore it
./nukelabctl restore backups/nukelab_backup_YYYYMMDD_HHMMSS.sql
# 3. Ensure partitions exist for the current month
./nukelabctl exec backend python scripts/db_profiler.py ensure-partitions --months-ahead 3
# 4. Restart and verify
./nukelabctl restartThe restore command creates the database and applies the current image's
Alembic head, so do not pre-create the database/user with POSTGRES_* values.
# Extract a single table from the backup
sed -n '/^CREATE TABLE activity_logs/,/^CREATE TABLE /p' nukelab-backup.sql > activity_logs_schema.sql
# Restore just that table
docker exec -i nukelab-postgres psql -U nukelab -d nukelab < activity_logs_schema.sqlPostgreSQL requires the parent table to exist before any child partitions can be restored.
pg_dump --clean --if-exists handles this automatically — it creates parent tables first, then partitions. But if you're doing manual restores, follow this order:
-- 1. Parent table (with PARTITION BY)
CREATE TABLE activity_logs (
id UUID NOT NULL,
actor_id UUID,
...
created_at TIMESTAMP NOT NULL,
PRIMARY KEY (id, created_at)
) PARTITION BY RANGE (created_at);
-- 2. Extensions
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
-- 3. Indexes (inherited by partitions)
CREATE INDEX ix_activity_logs_created_at ON activity_logs (created_at);
-- 4. Partitions
CREATE TABLE activity_logs_y2026m06 PARTITION OF activity_logs
FOR VALUES FROM ('2026-06-01') TO ('2026-07-01');
-- 5. Data
INSERT INTO activity_logs (...) VALUES (...);If you previously ran db_profiler.py drop-old and detached partitions, those partition tables are not in pg_dump output unless you explicitly back them up.
# List detached partitions (orphaned tables)
# (Piping stdin to a container requires direct docker/podman exec)
docker exec -i nukelab-postgres psql -U nukelab -d nukelab -c "
SELECT relname FROM pg_class WHERE relkind = 'r'
AND relname LIKE 'activity_logs_y%';
"
# Back up detached partitions separately
for part in activity_logs_y2025m01 activity_logs_y2025m02; do
docker exec -i nukelab-postgres pg_dump \
-U nukelab -d nukelab --data-only --table="$part" >> detached_partitions.sql
doneThe supported backup entry point is ./nukelabctl backup, which writes to the
repository's backups/ directory through the running Postgres container. Run it
from a host timer, not from a Celery task.
# /etc/cron.d/nukelab-backup
0 2 * * * root cd /opt/nukelab && ./nukelabctl backup >> /var/log/nukelab-backup.log 2>&1Copy completed dumps off-host with your normal backup tooling. A database dump inside the same host failure domain is not sufficient disaster recovery.
./nukelabctl backup writes backups/nukelab_backup_*.sql; pre-migration
snapshots are backups/pre-migrate-*.dump. Retain both patterns and keep an
off-host copy:
# Example: keep the last 30 days of routine and pre-migration backups
find /opt/nukelab/backups -type f \
\( -name "nukelab_backup_*.sql" -o -name "pre-migrate-*.dump" \) \
-mtime +30 -deleteUser-volume recovery retention is separate and controlled by
VOLUME_BACKUP_RETENTION_DAYS and VOLUME_BACKUP_MAX_PER_VOLUME in
.env.example.
After any restore, verify:
-
./nukelabctl exec backend python scripts/db_profiler.py table-sizesshows expected tables -
./nukelabctl exec backend python scripts/db_profiler.py partitions --table activity_logsshows partitions - Admin monitoring endpoint shows healthy partitions:
curl -s -H "Authorization: Bearer $ADMIN_TOKEN" http://localhost:8080/api/admin/health/monitoring | jq '.system.services.partitions.status' -
./nukelabctl exec backend alembic currentshows the current head - Application starts without errors
- Login works (verifies users table)
- Server list loads (verifies servers + cache)
| Scenario | Recovery Time | Procedure |
|---|---|---|
Accidental DELETE without WHERE |
Minutes | Restore from last night's backup |
| Corrupted partition | Minutes | Drop partition, restore from backup |
| Full database loss | 10–30 min | Full restore from backup + restart services |
| Host failure | 30–60 min | Restore backup to new host, update DNS |
| Ransomware / encryption | 30–60 min | Restore from off-site backup |
| Data Size | Backup File Size | Storage (30 days retention) |
|---|---|---|
| 1 GB | ~200 MB | ~6 GB |
| 10 GB | ~2 GB | ~60 GB |
| 100 GB | ~20 GB | ~600 GB |
| 1 TB | ~200 GB | ~6 TB |
Tip: Use pg_dump --format=custom + pg_restore for large databases. Custom format is compressed and supports parallel restore.
# Custom format (compressed)
docker exec -i nukelab-postgres pg_dump -U nukelab -d nukelab -Fc > backup.dump
# Parallel restore (4 jobs)
docker exec -i nukelab-postgres pg_restore -U nukelab -d nukelab -j 4 < backup.dumpThe Volumes page provides owner backup history and restoration into a new private volume. Sources must be private, unassociated with any workspace, and detached from every runtime container, including stopped or unmanaged containers. Stop and remove attachments explicitly before requesting a backup. Capture never changes source permissions. Shared/live backups, archive upload/download and remote backup storage are outside this workflow.
Recovery is disabled until both storage paths in .env.example
are configured and the trusted helper image is available. Release images are
published as ghcr.io/nukehub-dev/nukelab-volume-helper:<version> and tagged
latest; a pull-based deployment can set VOLUME_BACKUP_HELPER_IMAGE to that
image and run ./nukelabctl pull (or update). For a local source build, build
the helper using
the helper instructions. Provision
an absolute artifact directory owned by UID/GID 65532 with mode 0700; configure
VOLUME_BACKUP_HOST_PATH as its daemon-host path and
VOLUME_BACKUP_STORAGE_PATH as the path inside API and worker containers. These
must name the same bind mount. API, worker and scheduler receive the configuration
through Compose. The service resolves the helper to a local immutable image ID;
it never pulls an image during admission. Rootless runtimes must map the storage
ownership correctly for container UID 65532.
API and worker containers may bind the private backup storage root itself; those trusted platform mounts are not treated as workload attachments. User runtime containers that mount the volume, or a parent/child path aliasing it, still block backup and deletion. Artifact cleanup also ignores the platform storage-root bind, so retained and corrupted backups remain deletable through the owner API.
Storage admission reserves conservative archive and staging space against owner,
global and physical-free-space limits before work begins. The estimate includes
three copies of the bounded logical input plus per-member overhead; a source's
configured size limit can therefore require a larger owner budget even when its
current contents are small. Defaults and limits are documented in .env.example.
Incomplete artifacts cannot be restored. Completed copies expire under the
configured retention policy; active or uncertain restores pin the archive.
A restore reserves ordinary volume quota immediately. Its new volume remains inaccessible until archive validation and runtime completion are verified. A failed destination remains protected and can be explicitly deleted; it is never published as a complete restore. Completed copies remain available after source volume deletion. Account deletion requires cleanup of volumes, servers, backups and outstanding recovery operations first.
Pending work survives broker delivery failure and is scanned for redelivery.
Backup and restore execution refreshes the fenced operation heartbeat. A worker
that dies after claiming a delete:<uuid> artifact cleanup leaves the row in
deleting; the durable dispatcher does not blindly retry it. A bounded
maintenance pass clears the claim only after the claimant is proven stopped, then
rechecks workload mounts and either removes the artifact or records
delete_failed. Proof-backed completion is applied by the recovery reconciler
only after completion metadata, archive checksum and helper termination are
verified. A restoring destination is
activated from the verified metadata; an already-active destination must match the
recorded size. The volume service still owns the completion primitive.
recovery_required means runtime termination or cleanup could not be proved.
Retain the artifact, destination and operation guard while investigating. Admin →
Recovery Operations can rerun the read-only inspector and reconcile only a
proof-backed outcome; volume success still completes through the recovery
service's artifact hooks, and the console never activates a destination itself. An
ambiguous result returns conflict and changes nothing. There is no force path,
admin cancel/retry, TTL takeover or automatic source stop. Do not clear guards,
delete operation rows, reuse helper names or treat elapsed time as proof of
termination. Stop and inspect the operation-labelled helper and verify
attachments/storage before any operator repair. Owners receive deduplicated
attention/completion notices after an applied transition, plus a bounded daily
reminder while work remains unresolved. See
recovery operations.
These local recovery copies share the host's failure domain. Keep database backups and an independently managed off-host storage backup policy as well.