0019. Nightly backup: read through the binding, encrypt in the Worker, keep by count
- Status: Accepted
- Date: 2026-12-03
Context
The household's money history lives in one D1 database. A bad migration, a bug, a deleted database or a lost account would take it. The app needs a copy it can restore from, written without anyone remembering to do it, that doesn't leave a readable copy of the household's data lying in storage.
Decision
- A job body behind the hourly dispatcher. The backup is the
backupjob, once a day atbackup_hour, idempotent per household day (an object for the day already there means done). - The dump is read through the
DBbinding, in onebatch()(a single SQL transaction, so one consistent moment): the table listing and aSELECT *per table, written as plain SQLINSERTlines. A Worker can't shell out; D1's export needs a separate account API token (a second, stronger secret) and returns a plaintext file;D1Database.dump()is deprecated and only for alpha databases. A table that isn't in the schema'sTABLESlist stops the job rather than being left out, and a test fails first when a migration adds one. - Compressed, then encrypted in the Worker before anything is stored: the dump is gzipped (
CompressionStream), then sealed with AES-256-GCM, a fresh random 96-bit nonce per object. The object isHBB2+ the backup's day (YYYY-MM-DD) + the nonce + the ciphertext, and the first 14 bytes (format and day) are the authenticated data, so editing the day fails to decrypt, and the restore script, which knows the day from the file name, names a renamed or swapped file.HBB2replaces an unreleasedHBB1. The restore script expands the gzip with a size cap (the job's own limit), so a bomb can't fill its memory. Compression ahead of encryption leaks the compressed size; the object's size already said as much, and nobody chooses part of the data. The key is a second Worker secret (BACKUP_KEY, 32 random bytes in base64). A missing or bad key fails the job before the database is read, so no plaintext is ever written. The samecrypto.tsis used by the restore script, so the two can't drift. - R2, Standard storage, one bucket per mode (named in the generated config), objects
backups/daily/<day>.hbbplus a weekly copy of the first backup of each Monday-to-Sunday week. - Retention counts copies, not age: the newest 14 daily and 8 weekly copies. The job deletes only keys that match its own two patterns exactly, only after a successful write, and never a copy dated after today. A missed stretch can't empty the bucket.
- A failure is loud, and tried again: one plain sentence in the logs (no key, no row), a
failed@backup@<slot>@<time>audit line with the error's class and code, and thescheduledhandler throws after the tick so Workers Issues can alert. The backup (and only it) claims its slot after it succeeds instead of before, so a failure leaves the day free and the next hourly ticks inside the catch-up window try again: it is safe to run twice (head, then a conditional write that never replaces an object). A transient R2 or D1 error, or a key set a little late, no longer costs the night. The price is up to seven failed invocations for one bad night. - The Cron Trigger is in the generated config for both modes (
0 * * * *), not in the localwrangler.jsonc: the demo is the one place the backup and the restore drill can run on a real bucket and database, so it needs the trigger too. - The restore is a runbook drill (
docs/ops-runbook): download, decrypt on the owner's computer with a script that reads the key from the environment only, load into a scratch database after the migrations, compare row counts.
Consequences
- The restore needs two things only the owner holds: the key (lose it and the backups are unreadable, by design) and a scratch database. Key custody is the owner's job and nothing checks it.
- The whole dump is held in memory (and its compressed and sealed copies), so a dump over 24 MiB is refused until the job streams it. The fictional demo household dumps to about 25 KB (about 3.5 KB stored); a real household has not been measured.
audit_logandpull_logare append-only and never trimmed, so the dump only grows. - Backups live in the same Cloudflare account as the database. Time Travel is in that account too. The monthly off-site copy of an encrypted object is a manual step.
- Nothing alerts if the backup silently doesn't run (the trigger removed, the Worker deleted): the job-health check that would notice is still a stub, so the monthly look at the bucket is the only detection.
- Adding a table means adding it to
TABLESand toscripts/backup-counts.sql; tests fail until both are done. - The job's behaviour against real R2 and D1 (the conditional write, a large file load) and the restore drill on a real account are not covered by the local tests.