Write the core of a Postgres backup that streams `pg_dump` through gzip to S3 and never uploads an empty dump.
IntermediateScenarioScenarios: backups, log rotation and housekeeping
Answer
Situation read → In pg_dump | gzip, a failed pg_dump still produces a small valid gzip file, and without pipefail the job reports success.
What I'd do →
set -Eeuo pipefail
out="/var/backups/pg/app-$(date -u +%Y%m%dT%H%M%SZ).sql.gz"
tmp=$(mktemp "${out}.XXXXXX"); trap 'rm -f -- "$tmp"' EXIT
pg_dump --format=plain --no-owner -h "$PGHOST" -U backup app | gzip -6 > "$tmp"
gzip -t "$tmp"
(( $(stat -c %s "$tmp") > 1024 )) || { echo "dump suspiciously small" >&2; exit 1; }
mv -- "$tmp" "$out"
aws s3 cp --only-show-errors --sse aws:kms "$out" "s3://$BUCKET/pg/"
pipefailmakes the pipeline fail ifpg_dumpfails.- Credentials come from
~/.pgpass(mode 0600) orPGPASSWORDfrom a secret, not argv. - For large databases use
--format=custom(compressed, parallel restore withpg_restore -j).
Why → Empty backups are the most common way teams discover they had no backup.
Interview tip → Mention a size sanity check, and a scheduled test restore, as two separate guards.
More on Scenarios: backups, log rotation and housekeeping
Design a nightly backup of `/etc` and application data to S3 with retention.IntermediateBackups have "succeeded" every night for a year, but the first real restore failed. How do you make backups trustworthy?Advanced`/var` is 100% full because an app's logs were never rotated, and the app now fails to start. What do you do now, and what do you set up after?BeginnerShould you use `copytruncate` or a `postrotate` signal for an application's logs? How do you decide?Intermediate`/srv/app/releases` has 300 old release directories. Write a cleanup that keeps the newest 5 and never deletes the current release.BeginnerA Docker host keeps filling its disk. Write a safe cleanup approach.Beginner