A backup job sometimes runs twice at the same time and the archives are corrupted. How do you prevent it?
BeginnerScenarioScenarios: backups, log rotation and housekeeping
Answer
Situation read → A slow run overlaps with the next scheduled one, or someone ran it manually during the scheduled run.
What I'd do →
- Take an exclusive lock at the top of the script:
exec 9>/run/lock/backup.lock flock -n 9 || { echo "backup already running, skipping" >&2; exit 0; } - Write to unique temp names and
mvinto place, so even an unexpected overlap cannot interleave writes. - If migrating to systemd timers, systemd will not start a service that is already running.
Why → flock locks are released by the kernel when the process dies, so there are no stale lock files after a crash.
Interview tip → Explain why PID files are worse: they go stale after kill -9, and PIDs get reused.
More on Scenarios: backups, log rotation and housekeeping
Design a nightly backup of `/etc` and application data to S3 with retention.IntermediateWrite the core of a Postgres backup that streams `pg_dump` through gzip to S3 and never uploads an empty dump.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.Beginner