Operations runbook
What to do to keep the deployed app safe, in plain steps for the person who runs it. Today this covers the nightly backup. Nothing here goes in a pull request, a commit or an issue with real values in it: <bucket>, <day> and the like below are placeholders.
The restore drill has not been run on a real account
The backup code is built and tested, and the local version of the drill (below) was run once on the fictional household. The real drill, against a real Cloudflare account, has not been run. Until someone runs it and it passes, treat the backups as unproven. Lines marked (unconfirmed) are checked against the documentation or the command's help, not run on an account.
The nightly backup, in short
| Question | Answer |
|---|---|
| What is saved | Every row of every data table, as one plain SQL text file, compressed (gzip) and then encrypted. |
| When | Once a day, at backup_hour (a Setting, default 04:00 household time), by the hourly job runner (Hourly jobs). A failed try is repeated at each hourly tick for up to 6 hours after backup_hour. |
| Where | An R2 bucket: home-budget-demo-backups (demo) or home-budget-backups (production). It is bound to the Worker as BACKUPS. |
| Names | backups/daily/<day>.hbb, and a second copy backups/weekly/<day>.hbb of the first backup of each Monday-to-Sunday week. <day> is YYYY-MM-DD. |
| Kept | The newest 14 daily copies and the newest 8 weekly copies (about eight weeks). Counted by copies, so a stretch of missed nights never empties the bucket. |
| Deleted | Only objects whose names match the two patterns above, beyond those counts, and only after the new backup was written. Anything else in the bucket is never touched. |
| Encrypted with | AES-256-GCM, a fresh random nonce for every object, using the secret BACKUP_KEY (32 random bytes in base64). A wrong key or a changed byte makes it fail to open. The backup's day is part of what is checked, so a file can't be passed off as another day's. |
| Storage class | Standard (no minimum storage period, nothing extra to read it back). |
| Already there for today | Skipped: running it twice in a day changes nothing. |
| If the key is missing | The job fails with a plain message and writes nothing. It never writes an unencrypted copy. |
| Size limit | A dump over 24 MiB (as text, before compression) is refused (the Worker holds it in memory). See how big it gets. |
The file holds the data tables only. The tables themselves come from the migrations, so a restore is "make an empty database with the migrations, then load the file".
How the dump is made
A Worker can't run a command line tool, and D1's own export (wrangler d1 export, or the REST export the Cloudflare Workflows backup example uses) needs a separate account API token and hands back a plaintext file. D1Database.dump() is marked deprecated in the Workers types and only works for the old alpha databases. So the job reads the tables through its own DB binding: the list of tables and one SELECT * per table in a single batch(). D1 documents a batch as one SQL transaction, so every table is read from the same moment. A table in the database that the backup's list doesn't name stops the backup with a message instead of being silently left out.
The text is then compressed (gzip) and encrypted, in that order (encrypted bytes can't be compressed). Compression shows a little about the data to someone who holds the object (its size); the object's size already did.
Nothing in the logs holds a key or a row: the job logs one plain sentence on a problem, and the audit log keeps only the error's class and a short code. A good night's line in the audit log gives counts and sizes only: tables, rows, bytes of dump and bytes stored.
How big it gets
- Measured: the fictional demo household (17 tables, 92 rows, as seeded in the tests) is about 25 KB of dump and about 3.5 KB stored.
- Unmeasured: a real household's size. Nobody has run this against real data. Read it off the first real night's line in the audit log (
bytes of dump,bytes stored) and write it here. - It only grows.
audit_logandpull_logare append-only and are never trimmed, so the dump grows every day. At 24 MiB the job fails withtoo_large(see below) until the job streams the dump; that is a code change.
D1 Time Travel is a second layer, not a replacement
D1 keeps its own point-in-time history for 30 days on the Workers Paid plan (7 on Free). It is in the same account as the database, so it doesn't protect against losing the account. The encrypted copies are the ones you can take out of Cloudflare (see the monthly copy).
Setting it up (once)
The commands are in Deploying: create the bucket (step 3), set the key (step 5), then deploy (step 9). In short:
- Create the bucket, Standard storage:
npx wrangler r2 bucket create <bucket> --storage-class Standard. - Make the key:
openssl rand -base64 32. It prints 44 characters ending in=. Put it in your password manager now, before the next step (see key custody). - Give it to the Worker before the first deploy:
npx wrangler secret put BACKUP_KEY -c wrangler.generated.jsonc, and paste it when asked. Whetherwrangler secret putworks for a Worker that hasn't been deployed yet is unconfirmed (the documentation search found nothing either way). If it refuses, deploy first and run the same command straight away. - Deploy. The generated config carries the hourly Cron Trigger, so the first deploy starts it.
- Check on the next night (or the day after, at
backup_hour): the bucket holdsbackups/daily/<day>.hbb.
A first tick without the key fails
The backup is due once a day, from backup_hour (04:00 household time) until 6 hours after. A tick in that window without a key fails and writes nothing. It does not use the day up: the next hourly ticks try again, so setting the key within those hours still gives that night's backup. Past the window the night is lost (the next night is unaffected). A failed night looks like this: a failed invocation in the Worker's Issues with the text Scheduled job failed: backup (BackupError: key_missing), a failed@backup@... line in the audit log (see When a backup fails), and no new file in the bucket.
Key custody
- Lose the key and every backup is unreadable. There is no recovery and no copy of the key anywhere in the app, the repository or Cloudflare (a Worker secret can be replaced but not read back).
- Where the key is kept is the owner's call. It must not be in the repository, an issue, a pull request, a chat or the same place as the off-site copies. Keep it in at least two places that fail independently (for example a password manager and a printed copy in a safe place), so the key and a backup can be brought together on the day you need them.
- Changing the key: a new
BACKUP_KEYapplies to the next backup only. Older objects stay under the key that wrote them, so keep every old key until the last object written under it has aged out (up to eight weeks, the weekly copies). The decrypt script takes one key per run. - A leaked key doesn't expose past data unless someone also gets the objects (they are in your Cloudflare account), but treat it as exposed: make a new key, set it, and keep the old one until its backups age out.
The restore drill
Do this once after the first deploy, then after any change to the backup code, and about twice a year. It proves three things: you can find a backup, you hold a key that opens it, and what comes out is a complete household.
It only ever reads the backup and writes to a scratch database that you create for the drill. Never run the load step against the live database.
You need: the repository on your computer with npm ci done, Node 24, a bash or zsh shell, npx wrangler login done, and the key from your custody place.
Make a folder outside the repository for the files (they hold your household's data): mkdir -p ~/restore-drill.
Find a backup. In the Cloudflare dashboard, open R2 object storage, the backup bucket, and its objects (unconfirmed: the exact tabs). ✅ You should see
backups/daily/with up to 14 files andbackups/weekly/with up to 8, the newest daily dated today or yesterday. Pick one<day>.Download it (from the
apps/workerfolder; use your own bucket name):shnpx wrangler r2 object get <bucket>/backups/daily/<day>.hbb --remote --file ~/restore-drill/<day>.hbb✅ You should see
Download complete.and a file of some kilobytes. (unconfirmed on a real account; the command and its--remoteand--fileoptions are fromwrangler r2 object get --help.)Decrypt it on your computer. The key is read from an environment variable, never from the command line. The first line waits for you to paste the key and press Enter (nothing is shown):
shread -rs BACKUP_KEY && export BACKUP_KEY npm run backup:decrypt -w @home-budget/worker -- ~/restore-drill/<day>.hbb ~/restore-drill/restore.sql unset BACKUP_KEY✅ You should see
Decrypted ... (readable by you only), the backup day, "Migrations in force then", and a list of every table with its row count, ending in a total. Check the printed day: the line readsBackup day <day> ... It matches the date in the file name (expected day <day>), with the day you picked in step 1. Write the row list down: step 7 compares against it. ❌ If you see "the key is wrong, or the file is damaged", you used the wrong key or the file was changed: nothing was written. ❌ "The file name says X but this genuine backup is for Y" means the file was renamed or is another day's: nothing was written; go back to step 2. ❌ "The rows in the file don't match its header" means the file is incomplete: nothing was written. If the file name has no date, the script says nothing checked the day: compare the printed day with the one you meant.Make a scratch database and write its config (use your own team name; the audience tag isn't needed for this):
shnpx wrangler d1 create home-budget-restore-drill D1_DATABASE_ID=<the id it printed> TEAM_DOMAIN=https://<team>.cloudflareaccess.com POLICY_AUD=pending \ npm run config:generate -w @home-budget/worker -- --mode demo --out restore-drill.generated.jsonc✅ The first prints a database id; the second says
Wrote restore-drill.generated.jsonc. If it offers to add the binding to a config file, answer no.Create the empty tables in the scratch database (it asks you to confirm), from
apps/worker:shnpx wrangler d1 migrations apply DB --remote -c restore-drill.generated.jsonc✅ You should see the migrations listed with a tick, as many as "Migrations in force then" in step 3 (unconfirmed: if the app has gained a migration since that backup, there is one more, and that is fine).
Load the backup:
shnpx wrangler d1 execute DB --remote -c restore-drill.generated.jsonc --file ~/restore-drill/restore.sql✅ It finishes without an error. (unconfirmed: how a real D1 database takes a file this size, and the file's
--comment lines and its firstPRAGMA defer_foreign_keysline. If it refuses the PRAGMA line, delete that one line fromrestore.sql: the rows are written parents first, so it isn't needed. If it stops partway, delete the scratch database (step 8) and start again at step 4: a half-loaded database is not a result.)Compare the row counts. The file
apps/worker/scripts/backup-counts.sqlhas one count per table:shnpx wrangler d1 execute DB --remote -c restore-drill.generated.jsonc --file scripts/backup-counts.sql✅ Every table's
row_countequals the number you wrote down in step 3, all 17 of them (unconfirmed: that a real D1 prints every statement's result for a file; if it doesn't, run each count with--command "SELECT count(*) FROM <table>"). ❌ Any difference means the drill failed: don't delete anything yet and tell the person who maintains the backup.Clean up. The scratch database and the decrypted file hold your household's data:
shnpx wrangler d1 delete home-budget-restore-drill rm ~/restore-drill/restore.sql ~/restore-drill/<day>.hbb cd apps/worker rm restore-drill.generated.jsoncThe last two lines run in the
apps/workerfolder (from the repository root, that iscd apps/worker): that is where step 4 wrote the config file, which holds the scratch database's id. It is gitignored, but delete it anyway. ✅ The database is gone fromnpx wrangler d1 list, and no file namedrestore.sqlorrestore-drill.generated.jsoncis left anywhere.Write down the date, which backup you used and that it passed. A drill that nobody wrote down didn't happen.
The same drill on your own computer (checked)
Steps 2 to 7 also work against the local simulation, with no Cloudflare account. This is how the drill was checked, on the fictional household (all 17 tables matched). From apps/worker, with BACKUP_KEY in a git-ignored .dev.vars file:
Reset the local database (it has the fictional household):
shnpm run db:reset:local -w @home-budget/workerStart the local server in a second terminal, leave it running, and ask it to run the hourly job for 2026-12-03 at 14:00 UTC (the backup is due then):
shnpx wrangler dev --test-scheduled curl "http://localhost:8787/cdn-cgi/handler/scheduled?time=1796306400000"Download the backup it wrote, then decrypt it as in step 3 above:
shnpx wrangler r2 object get home-budget-backups-local/backups/daily/2026-12-03.hbb --local --file ~/restore-drill/2026-12-03.hbbLoad it into a second, empty local database: the same
migrations applyandexecute --filecommands as steps 5 and 6, with--localin place of--remote,--persist-to <a new folder>on both, and no-coption. Then run step 7's count file the same way.
The monthly off-site copy
Everything above lives in one Cloudflare account. If the account were lost, locked or taken over, the database and its backups would go together. So once a month, on the 1st:
- Download the newest daily backup as in drill step 2 (the file stays encrypted: don't decrypt it).
- Store it somewhere that isn't Cloudflare (an external disk, or another cloud storage account), not in the same place as the key. Keep at least the last three months.
- While you are there, look at the bucket: ✅ the newest daily file is dated today or yesterday. A bucket that stopped filling is the one failure no alert reports (an alert needs something to fail).
Alerts
Both are set by hand in the Cloudflare dashboard, once, by the account owner.
- Billing alert at $1. Manage Account, Billing, Billable Usage, Set Budget Alert, enter
1, Create (or Notifications, Add, Budget Alert). It emails when the projected spend for the month reaches the amount; it is checked daily, fires once per billing cycle, counts usage-based products only (not the Workers Paid plan fee) and does not stop anything. Cloudflare may already have created a default alert at a higher amount: that doesn't replace this one. This path is from the Cloudflare changelog and billing documentation. - Worker errors. The generated config turns on Workers Issues (
observability.issues.enabled), which records a failed invocation, an uncaught exception, a 5xx answer or an error-level log. A failed backup does all of those: the job logs one plain sentence and the hourly trigger then fails. In the dashboard: Workers & Pages, the Worker, Issues, Automations, Add automation, an occurrence threshold of1, a destination, turn on Enabled, Create. ✅ The first failure of each kind then notifies you. Which destinations Cloudflare offers (the documentation names a webhook, a chat service, an incident tool or a coding agent) and whether plain email is one is unconfirmed; pick one that reaches you. Issues is in open beta and free during it.
When a backup fails
A failed night shows up as an Issue (above) and as a line in the audit log.
To read the last few failures, from
apps/worker. This is a read-onlySELECTagainst the live database (--remotemeans the real one): it changes nothing, so keep it exactly as written and don't swap in another statement:shnpx wrangler d1 execute DB --remote -c wrangler.generated.jsonc \ --command "SELECT record_id, at, after FROM audit_log WHERE table_name = 'scheduled_job' AND record_id LIKE 'failed@%' ORDER BY id DESC LIMIT 5"The
aftercolumn holds the job and one code. The fix for each:
| Code | What it means | What to do |
|---|---|---|
key_missing | The BACKUP_KEY secret isn't set on this Worker. | Set it (setup step 3). If it was lost, make a new one: old backups stay readable only with the old key. |
key_invalid | The secret isn't 32 random bytes in base64 (or is a placeholder). | Make a new one with openssl rand -base64 32 and set it again. |
bucket_missing | No bucket is connected to the Worker. | The bucket wasn't created before the deploy, or the config is old: create it and deploy again. |
table_list_changed | A new table exists that the backup's list doesn't name. | A code change is needed (TABLES in src/db/schema.ts). Until it ships, the nightly backup stops. |
too_large | The dump is over 24 MiB. | A code change is needed (stream the dump). Take a manual copy in the meantime (wrangler d1 export). |
unsupported_value | A value of a kind the file format can't write (never seen). | A code change is needed. |
| another error name | R2 or D1 refused something (a permission, a quota, an outage). | Check the Cloudflare status page and the Worker's logs; the next night tries again. |
A failed backup is tried again at each hourly tick, until 6 hours after backup_hour: the hourly runner leaves the day unclaimed until the backup has succeeded, so fixing the cause inside that window still saves the night (the backup is safe to run twice: it checks for today's object first and never overwrites one). Every failed try is its own failed invocation (so up to seven Issues for one bad night) and its own failed@backup@<slot>@<time> line. Past the window the night is lost; the next night's backup runs as usual. If you can't wait, take a manual export: npx wrangler d1 export <database> --remote --output=<file> — that file is plaintext: keep it as carefully as the household's data and delete it after.
What is checked, and what isn't
- Checked by tests: the encryption (round trip, wrong key, every single byte changed, a short or cut-off file, a fresh nonce each time); the compression (a gzip bomb is refused at the size cap) and the day being part of what is authenticated (an edited day fails; a renamed or swapped file is named by the script); a failed backup being tried again the next hour and the day claimed only once it worked (the other jobs claim first, as before); the names and the retention rules (14 and 8, only its own names, never a stray file, never a future-dated one); the whole job against a simulated bucket (one object per day, idempotent, weekly copy, nothing written with a missing or bad key, nothing deleted after a failed write, no key or row in the logs); the dump loading into a second empty database with identical rows; the decrypt script's refusals; this page's bucket names and the counts file against the code.
- Checked locally, once: the drill above against the local simulation.
- Not checked: anything against a real Cloudflare account (R2 write and conditional write, the real D1 file load, the Issues automation, the billing alert), that the hourly trigger fires, and a real household's size.
Known gaps
- Nothing tells you if the backup silently doesn't run. The Issues alert needs something to fail. If the Cron Trigger is removed, the Worker is deleted, or the dispatcher stops picking the job, no job fails and nothing is sent. The job-health check that would notice is still a stub. Until it is real, the monthly check (look at the bucket for a file dated today or yesterday, below) is the only detection.
- The restore drill has not been run on a real account; the billing and Issues alerts are set by hand and checked by nothing here; the monthly off-site copy is manual.
audit_logandpull_loggrow without limit, and so does the dump (see how big it gets).