Skip to content

Reduce DB backup costs: monthly dumps + expire dumps older than 1 year - #24

Merged
atalyaalon merged 9 commits into
mainfrom
claude/laughing-galileo-165xk1
Nov 30, 2026
Merged

atalyaalon merged 9 commits into
mainfrom
claude/laughing-galileo-165xk1

Conversation

@atalyaalon

@atalyaalon atalyaalon commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

📍 Status (2026-11-30)

  • Backup schedule:
    • Monthly went live early on both servers on 2026-11-28, from a branch push (details). There were no dumps on Nov 29–30.
    • Merging #27 (merged 2026-11-30) redeployed main, so both servers are on daily again for now.
    • Merging this PR makes them monthly for good.
  • Local restores: until anyway#2965 reaches master, a local restore needs a dump dated today. On a day without one, set DBRESTORE_FILE_NAME to an existing dump, e.g. 2026-11-28_anyway_partial.pgdump. This doesn't block merging this PR: it only affects developers' local restores.
  • Nothing else is live: no terraform apply has been run, and no dumps were deleted.
  • Going back to daily later: how.

💰 Estimated saving: ~$85–265+/month on S3

  • Assumes 5 GB of dumps per day per server. The real size is unknown; the Thin DB dumps dry run shows the real numbers.
  • If we don't merge: every daily dump is kept forever, so the bill keeps growing: ~$89/month once a year of dumps has piled up, ~$268/month after 3 years.
  • With this PR: ~$3/month, and it stays flat.
  • S3 only: no Savings Plan is involved (those only apply to EC2). Details in Estimated cost saving.

Related PRs

# PR What
✅ dfc-iac#27 Deploy only from main (merged). This PR adds stronger guards on top: change 4.
— anyway#2965 Local dev restore uses the latest complete dump. Independent; not a blocker.
1 This PR, dfc-iac#24 Monthly backups, 1-year S3 expiry, a one-time clean-up of daily dumps, deploy guards, and Ziv's manual access in code
2 dfc-iac#25 Free uptime and DB backup monitoring. Stacked on this PR.
3 dfc-iac#28 Plan to shut down the dfc server (stacked on #25)
4 dfc-iac#26 dfc2 instance type, once the measurements allow it
5 dfc-iac#29 Smaller dfc2 data disk

Why

Both servers (dfc and dfc2) dump the Anyway DB to S3 every day (a full dump and a partial dump), and the dumps are never deleted. That adds about 1,460 files a year, and the S3 bill keeps growing. This PR cuts how often dumps are made, cleans up the daily dumps already there, and caps how long dumps are kept.

Changes

1. DB backups run monthly instead of daily

Files: apps/anyway/compose.yaml, apps-dfc2/anyway/compose.yaml

db-backup-cronjob schedule: 10 0 * * * (daily) → 10 0 1 * * (1st of each month at 00:10, server time). This one job writes both the full and partial dumps.

When it takes effect: on merge. The deploy workflows redeploy both servers and rewrite /etc/cron.d/anyway-db-backup-cronjob.

Trade-off: if the DB is lost, up to a month of data could be lost with it (it was up to a day before). One failed monthly run also means no backup that month. The backup monitor in #25 alerts on that.

2. Delete DB dumps older than 1 year

File: modules/anyway/aws_s3_buckets.tf

Adds an aws_s3_bucket_lifecycle_configuration to these 4 buckets:

  • dfc-anyway-full-db-dumps
  • dfc-anyway-partial-db-dumps
  • dfc2-anyway-full-db-dumps
  • dfc2-anyway-partial-db-dumps

Rule 1, expire-old-db-dumps:

  • Objects expire after 365 days.
  • If versioning is on, old versions are removed 1 day after becoming noncurrent.
  • Unfinished multipart uploads are cleaned up after 7 days.

Rule 2, remove-expired-delete-markers: if versioning is on, delete markers left with no versions are removed. AWS doesn't allow this in the same rule as expiration.days.

⚠️ Scope: the rules cover every object in these 4 buckets, not only dumps. Expiry goes by each object's S3 upload time, not the date in its file name.

When it takes effect: not on merge. Someone must run a targeted terraform apply: see Rollout. Expiry then runs within ~24–48 hours, and it's permanent.

3. One-time clean-up: keep only one dump per month

Files: bin/thin_db_dumps.py (new), .github/workflows/thin-db-dumps.yml (new)

How it decides what to keep:

  • Dumps are grouped by series: the file name without its date. anyway.pgdump.gz, anyway_partial.pgdump.gz (together with its _partial_schema file) and e.g. testing_anyway_partial.pgdump.gz are each handled separately, so one series can never cause another series' dumps to be deleted.
  • A dump counts as complete when all its parts are there (partial + schema) and each is at least 1 KB. A gzipped empty file is a few dozen bytes.
  • For each bucket, series and month, it keeps the earliest complete dump and deletes the other dates.
  • If a month has no complete dump, it keeps the one with the most non-empty parts. If every dump that month is empty, it keeps the whole month. It never keeps an empty dump in place of a good one. Either case prints a WARNING.

It never touches:

  • files whose names don't start with YYYY-MM-DD_
  • anything from the last 30 days (keep_recent_days, minimum 1)

Because of the 30-day window, a run today keeps all the daily dumps from the last 30 days. Run it again in about a month to get down to one dump per month there too, or set a smaller keep_recent_days.

What it prints: each bucket's versioning status, the months kept per series, files and GB to keep or delete, warnings, and the AWS error message if a call fails. The workflow doesn't list individual file names; run the script locally with --verbose for that.

How to run it: Actions → Thin DB dumps → Run workflow, on main.

  • With delete unchecked (the default), it's a dry run.
  • Re-run with delete checked to really delete.
  • It uses the same Vault approle and AWS user (aws_prod_app_user, admin) as Reboot EC2.
  • Runs can't overlap, and each has a 60-minute limit.
  • It appears in Actions only after this PR is merged.

Tested against a fake AWS CLI, not real AWS. Covered:

  • 9 months of daily dumps
  • testing_ series
  • a partial dump without its schema, and empty schemas
  • empty dumps on the 1st
  • months where every dump is empty
  • versioned buckets and non-dump files
  • invalid input
  • batch deletes
  • AccessDenied

4. Deploy guards on the anyway deploy workflows

Files: .github/workflows/anyway.yml, .github/workflows/anyway-dfc2.yml

  • branches: [main] on the push trigger: the same change as Only deploy the anyway apps from main (stop deploys from any branch push) #27, already merged, so it's identical and conflict-free.
  • New, job-level if: github.ref == 'refs/heads/main': a manual Run workflow on another branch now skips the deploy; the run shows green but does nothing.
  • New, concurrency per server: two pushes in a row can no longer run deploy_app at the same time. That caused the two failed dfc2 runs on 2026-11-27.
  • Automations: the ones that push to main (anyway, anyway-etl, safety-data-client, anyway-reports) aren't affected.

5. Keep the manual AWS access in Terraform

File: modules/anyway/aws_db_dumps_users.tf

The problem: dfc2-anyway-db-dumps-reader was given two things by hand in AWS:

  • read (list) access to the dfc-anyway-cbs bucket
  • a tag noting whose keys these are ("Ziv keys to create local db volume")

Before this change, any terraform apply would have removed both.

The change:

  • adds the dfc-anyway-cbs bucket ARN to the policy, exactly as it is in AWS
  • adds lifecycle { ignore_changes = [tags, tags_all] }, so the hand-added tag is kept. It isn't copied into code, because the tag's name is an access key ID and this repo is public.

The CI plan now shows no change for this user.

Rollout

  1. Before you start:
    • Use Terraform 1.2.9 exactly (check with terraform version). CI uses 1.2.9 and no lock file is committed. A newer Terraform can rewrite the shared state in a format CI can't read.
    • Don't merge while another deploy is running, e.g. Only deploy the anyway apps from main (stop deploys from any branch push) #27's. Wait for both deploy runs to be green.
    • Avoid having a deploy running around 00:10 server time (backup time).
  2. Merge this PR: Ready for review → Squash and merge → click "Delete branch" on this PR page.
  3. Clean-up dry run (read-only): Actions → Thin DB dumps → Run workflow on main, with delete unchecked. Check the sizes, versioning and warnings.
  4. Before applying:
    • Download any dump you want to keep. Deletion is permanent. For example, the commented-out restore line in apps/anyway/compose.yaml refers to 2024-01-24_anyway.pgdump.
    • Check that the buckets have no hand-made lifecycle rules. This resource replaces a bucket's whole lifecycle configuration:
      for b in dfc-anyway-full-db-dumps dfc-anyway-partial-db-dumps dfc2-anyway-full-db-dumps dfc2-anyway-partial-db-dumps; do
        echo "== $b"; aws s3api get-bucket-versioning --bucket $b; aws s3api get-bucket-lifecycle-configuration --bucket $b
      done
      NoSuchLifecycleConfiguration means there are no existing rules, which is safe.
  5. Apply only the S3 rules:
    terraform init "-backend-config=$(bin/get_backend_config.py)"
    eval "$(bin/get_secret_envvars.py)"
    ·t·erraform a·pply -target='module.anyway.aws_s3_bucket_lifecycle_configuration.db_dumps'
    • The plan must say 4 to add, 0 to change, 0 to destroy, plus the usual "resource targeting" warnings. If it shows anything else, answer no.
    • Don't run an untargeted terraform apply. The full plan also contains 3 DKIM Route53 records (*._domainkey.anyway.co.il) that differ from the code: a trailing dot and TTL 1800 vs 300. That's harmless, but unrelated, so decide on it separately.
    • Afterwards, a full terraform plan should show only those 3 DKIM changes. Some provider 4.x versions may also show a lasting diff on filter {}.
  6. Clean-up for real: run Thin DB dumps again with delete checked. Run it once more in about a month, because of the 30-day window.

Result

Once the second clean-up run is done, each bucket has about 13 dumps per series: one a month for a year, plus the last 30 days. Before, it was one a day, forever.

Estimated cost saving

This is an estimate: I don't have the real bucket sizes. It uses S3 Standard in eu-central-1 at about $0.0245 per GB-month. Upload requests and data coming into S3 cost close to nothing.

Let D = GB written per day by one server (full + partial gzipped dumps). There are 2 servers.

Without this PR (daily, kept forever) With this PR (monthly, kept 1 year)
Data added per year 2 × 365 × D = 730·D GB 2 × 12 × D = 24·D GB
Total stored keeps growing every year stays at ~24·D GB
Monthly cost once 1 year of dumps has piled up ~$17.9 × D ~$0.6 × D
Monthly cost once 3 years of dumps have piled up ~$53.7 × D ~$0.6 × D (unchanged)

Example, D = 5 GB/day per server:

  • Without this PR: ~$89/month after 1 year of dumps, ~$268/month after 3 years, and still growing.
  • With this PR: ~$3/month, flat.
  • Saving: roughly $85–265+/month, depending on how many years of daily dumps are already in the buckets.

For the real sizes, see the Thin DB dumps dry run, or check each bucket:

aws s3 ls s3://dfc-anyway-full-db-dumps --recursive --summarize --human-readable | tail -2

Reviews

Four review rounds by separate agents, all read-only, the last one by a different model. All findings are fixed, and the last round confirmed the code is ready. Its description corrections are applied above.

Not in this PR (follow-ups)

  • anyway#2965: needed for local restores. When merging it, put --no-deploy in the squash commit title. Otherwise anyway's deploy workflow builds new images and redeploys dfc2.
  • Shut down the duplicate dfc server: #28.
  • A smaller machine (#26), a smaller disk (#29), and later a Savings Plan.

🤖 Generated with Claude Code

https://claude.ai/code/session_01XtN7GhfRRihvBTHsWxGZoV

Reduces the number of full and partial DB dumps written to S3 from
both environments to save on storage costs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XtN7GhfRRihvBTHsWxGZoV
Adds S3 lifecycle rules to the full and partial DB dump buckets of both
environments so old dumps are deleted automatically.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XtN7GhfRRihvBTHsWxGZoV
Removes the extra daily dumps from the anyway DB dump buckets, keeping
the earliest dump of every month and everything from the last 30 days.
Dry run by default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XtN7GhfRRihvBTHsWxGZoV
@atalyaalon
atalyaalon requested review from tkalir and ziv17 November 28, 2026 06:12
Manually triggered, dry run by default. Uses the same Vault login and
AWS user as the Reboot EC2 workflow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XtN7GhfRRihvBTHsWxGZoV
Review fixes:
- group dumps by series (date prefix stripped, partial + partial_schema
  together) so a testing_ or other series can't cause a month of real
  dumps to be deleted
- only keep a date if all its parts exist and are non-empty; warn when
  a month has no complete dump
- report bucket versioning status and per-series month counts
- reject --keep-recent-days below 1, also in the workflow
- pass delete batches via a file and log which batch failed
- don't allow two cleanup workflow runs at once

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XtN7GhfRRihvBTHsWxGZoV
- when no dump in a month is complete, keep the most complete non-empty
  one, and keep the whole month if every dump is empty
- treat dumps under 1 KB as empty (a gzipped empty file isn't 0 bytes)
- group incomplete-month warnings into one line per series
- show the AWS CLI error message when a call fails
- add a lifecycle rule removing expired delete markers on versioned buckets
- cron comment: the schedule runs in server time

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XtN7GhfRRihvBTHsWxGZoV
atalyaalon pushed a commit to data-for-change/anyway that referenced this pull request Nov 28, 2026
DB dumps are moving from daily to monthly (data-for-change/dfc-iac#24),
so a dump dated today usually won't exist. When DBRESTORE_FILE_NAME is
not set, list the bucket and restore the newest date that has both the
partial and the partial_schema dump, each at least 1 KB. If none is
found, warn and skip the restore, like the missing-credentials case.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XtN7GhfRRihvBTHsWxGZoV
The anyway and dfc2 anyway workflows deployed to the production servers
on a push to any branch that touched the app folders, so pushing a PR
branch deployed it before review. Restrict the push trigger to main;
manual runs (workflow_dispatch) are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XtN7GhfRRihvBTHsWxGZoV

Copy link
Copy Markdown
Contributor Author

⚠️ @tkalir @ziv17: the monthly backup schedule from this PR is already live on both production servers, before review.

What happened

What changed on the servers: only the backup schedule

  • main hadn't moved, so the deployed app files equal main, except the schedule line.
  • Same images: dfc anyway:sha-c56bf7f, dfc2 anyway:sha-3403cdc.
  • No container was restarted: all show their old uptimes in the logs.

Impact

  • The last daily dumps were taken on 2026-11-28 at 00:10. There will be no dumps on Nov 29–30, and the next dump is Dec 1.
  • Local dev restores: until anyway#2965 lands, restore_db.sh looks for today's dump and fails. Workaround for anyone restoring locally:
    DBRESTORE_FILE_NAME=2026-11-28_anyway_partial.pgdump
  • Decision: we decided to keep monthly rather than redeploy main to bring daily backups back.

Fix: commit 8f36f2d in this PR restricts both workflows' push trigger to branches: [main]. Manual runs are unchanged. Pushes after that commit, at 07:08 UTC, ran only the terraform plan CI and no deploy.


Generated by Claude Code

atalyaalon pushed a commit to data-for-change/anyway that referenced this pull request Nov 28, 2026
DB dumps moved from daily to monthly (data-for-change/dfc-iac#24), so a
dump dated today usually won't exist. When DBRESTORE_FILE_NAME is not
set, list the bucket and restore the newest date that has both the
partial and the partial_schema dump, each at least 1 KB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XtN7GhfRRihvBTHsWxGZoV

Copy link
Copy Markdown
Contributor Author

@tkalir @ziv17: how to bring backups back to daily, if we decide monthly isn't enough.

While this PR is NOT merged (fastest, no code change)

main still has the daily schedule, so redeploying main restores it on both servers:

  1. Actions → anyway CI → Run workflow → branch main → Run. This is the dfc server.
  2. Actions → dfc2 anyway CI → Run workflow → branch main → Run. This is the dfc2 server.
  3. Check each run's log for this line:
    10 0 * * * ubuntu cd ~/apps/anyway && docker compose run --rm db-backup-cronjob
    

That only rewrites the cron entry. No containers restart and no images change, since everything else on the servers already matches main. Then either close this PR, or remove change 1 from it before merging (step 1 of the next part).

After this PR is merged

main then has the monthly schedule, so change it back in code:

  1. In apps/anyway/compose.yaml and apps-dfc2/anyway/compose.yaml, set the db-backup-cronjob schedule back to:
    schedule: "10 0 * * *"
  2. Open a PR and merge it to main. The deploy workflows redeploy both servers on merge. Check the same cron line in their logs.

Middle ground: weekly backups, schedule: "10 0 * * 0" (Sundays at 00:10).

A single extra backup right now, without changing the schedule (e.g. to fill the Nov 29–30 gap):

bin/apps-dfc2.py compose anyway run --rm db-backup-cronjob
bin/apps.py compose anyway run --rm db-backup-cronjob

What still works if we go back to daily

  • The 1-year expiry rule (change 2), the backup monitor in Free uptime + DB backup monitoring, remove paid Route53 health checks #25, and the restore fix in anyway#2965 all work with any schedule.
  • Only the saving is smaller. With daily dumps kept for 1 year, S3 stays at about $17.9 × D a month, where D = GB of dumps per server per day: about $89/month at 5 GB. Monthly is about $0.6 × D, around $3.
  • If we go back to daily, skip the "Thin DB dumps" clean-up, which keeps one dump per month, or run it only for dumps older than what we want to keep.

Generated by Claude Code

Copy link
Copy Markdown
Contributor Author

@tkalir @ziv17: correction to my earlier comment. The monthly schedule probably won't stay until Dec 1.

Why it will revert

  • main still has the daily schedule.
  • Every push to main that touches apps/anyway/** or apps-dfc2/anyway/** redeploys main to that server, which writes the daily schedule back. That includes:
    • the image-update automations (Anyway CI, Anyway ETL CI, safety-data-client, anyway-reports), which push several times a day
    • merging #27, because it changes the workflow files, which are in the trigger paths
  • So daily backups will most likely come back by themselves within hours or days, possibly on one server before the other. They stay daily until this PR is merged.

What this means

  • Nothing breaks: only the cron entry changes, and no containers restart.
  • Dumps may be missing for a day or two after 2026-11-28, depending on when each server gets redeployed.
  • Local restores: until anyway#2965 lands, restore needs a dump dated today. If none exists, set DBRESTORE_FILE_NAME to an existing date, e.g. 2026-11-28_anyway_partial.pgdump.
  • To keep monthly for good: merge this PR. It also contains Only deploy the anyway apps from main (stop deploys from any branch push) #27's fix.
  • To go back to daily on purpose: see this comment.

Generated by Claude Code

@ziv17 ziv17 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good initiative. I think monthly backups with last 30 days suffice.

@ziv17

ziv17 commented Nov 28, 2026

Copy link
Copy Markdown

@atalyaalon , we still need you ;)

- job-level if: github.ref == 'refs/heads/main', so "Run workflow" on
  another branch can't deploy it either
- concurrency group per server, so two pushes in a row don't run
  deploy_app at the same time

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XtN7GhfRRihvBTHsWxGZoV
- dfc2-anyway-db-dumps-reader: add the dfc-anyway-cbs bucket access that
  was granted by hand, and ignore its hand-added tags, so a terraform
  apply no longer removes them
- thin-db-dumps workflow: 60 minute timeout, don't persist the GitHub
  token in the checkout

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XtN7GhfRRihvBTHsWxGZoV
@atalyaalon
atalyaalon marked this pull request as ready for review November 30, 2026 00:26
@atalyaalon
atalyaalon merged commit 6b50d46 into main Nov 30, 2026
1 check passed
@atalyaalon
atalyaalon deleted the claude/laughing-galileo-165xk1 branch November 30, 2026 00:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants