Sub topic 9
Idempotent jobs and atomic writes
This chapter assumes you can write a basic shell script, know what set -e and exit codes do, and have seen a cron or systemd timer job run. Earlier chapters covered overlap prevention with flock. Locking keeps two runs from executing at once. It does not make a run safe to repeat after a crash, a retry, or a catch-up. This chapter covers the job's own design for that.
What idempotent means
A job is idempotent if running it once and running it five times leave the system in the same final state. "Ensure the backup for 2026-11-28 exists" is idempotent. "Append a line to the report" is not, because every run adds another line.
Scheduled jobs get repeated more often than people expect:
- A timer with
Persistent=trueruns a missed activation after boot, which can land close to a normal one. - A retry wrapper reruns a job after a transient failure.
- An administrator runs the job by hand to test a fix, and the schedule then fires as usual.
- A lock timeout or a hung run gets killed halfway, and the next run starts on the leftovers.
A job that is safe to repeat is also safe to stop. You can kill it, reboot the machine, or rerun it without first working out how far it got.
Two separate properties
Idempotency and atomicity are different, and a reliable job needs both.
| Property | Question it answers | Typical technique |
|---|---|---|
| Idempotent | What happens if this runs again? | Deterministic names, "ensure" semantics, upserts, marker files |
| Atomic | What does a reader see if this stops halfway? | Write to a temporary file, then rename |
A job can be idempotent but not atomic. It might always overwrite /var/backups/db.sql.gz with the same content, but a reader that opens the file mid-write sees a truncated archive. A job can also be atomic but not idempotent, for example one that atomically replaces a counter file with old + 1.
Atomic writes: write aside, then rename
The rename system call, rename(2), replaces the target name in one step. A process that opens the target sees either the complete old file or the complete new file, never a mixture. A plain > redirect does not behave this way. It truncates the file immediately and fills it gradually, so a crash leaves a partial file under the real name.
The pattern is to write the full result to a temporary file in the same directory, then rename it over the final name.
#!/usr/bin/env bash
set -euo pipefail
out=/var/backups/db.sql.gz
tmp=$(mktemp "${out}.XXXXXX")
trap 'rm -f "$tmp"' EXIT
pg_dump mydb | gzip > "$tmp"
mv "$tmp" "$out"
# Report success only after everything above worked
curl -fsS -m 10 --retry 3 -o /dev/null https://hc.example.com/ping/your-check-idEach line does a specific job:
set -euo pipefailstops on the first failure. Withpipefail, a failingpg_dumpfails the whole pipeline even thoughgzipexits cleanly. Without it, the script would rename an empty archive into place.mktempcreates a unique file that did not exist before. Two overlapping runs cannot write to the same temporary file.trap ... EXITdeletes the temporary file when the script exits for any reason, including a failed command underset -e. After a successfulmvthe file no longer exists, sorm -fdoes nothing.- The
curlping comes last, so a failed run never reports success.
Gotchas with rename
Keep the temporary file on the same filesystem
rename(2) only works within one filesystem. When mv crosses filesystems, it copies the data and then deletes the source. The copy is not atomic, and readers can see a partial file. This is why the script creates the temporary file next to the target, using "${out}.XXXXXX", and not under /tmp. Many systems mount /tmp as a separate tmpfs, so the mistake is easy to make and hard to notice in testing.
Temporary files can outlive the job
The EXIT trap does not run if the process receives SIGKILL, for instance from an out-of-memory kill or a systemd timeout that escalates to kill. The result is a stray db.sql.gz.Ab12Cd in the backup directory. Two habits limit the damage:
- Give temporary files a suffix that your consumers' globs do not match. A file named
db-2026-11-28.sql.gz.Ab12Cddoes not matchdb-*.sql.gz, so a restore script will not pick it up. - Remove old strays at the start of the run, for example
find /var/backups -name '*.sql.gz.??????' -mmin +120 -delete. Choose an age longer than any legitimate run.
Permissions and durability
mktemp creates files with mode 0600. If other users or services must read the result, run chmod on the temporary file before the rename, so the file is never visible with the wrong mode.
Rename guarantees what readers see while the system is running. After a power loss, the rename can survive while the file's data blocks do not, which leaves an empty or short file. If the result must survive a crash, call sync "$tmp" before the mv. GNU coreutils 8.24 and later accept file arguments, and sync then flushes just that file.
Swapping a directory or symlink
You cannot atomically replace a non-empty directory. Build the new tree in a fresh directory, then switch a symlink to it:
release=/srv/reports/2026-11-28
mkdir -p "$release"
# ... generate files into "$release" ...
ln -s "$release" /srv/reports/current.new
mv -T /srv/reports/current.new /srv/reports/currentThe -T option tells mv to treat the destination as a plain name. Without it, if current is already a symlink to a directory, mv moves the new link inside that directory and nothing is replaced. ln -sfn does the same job, but it removes and recreates the link in two steps, so a reader can briefly find no current.
Making the work itself idempotent
Atomic writes protect readers. Idempotency protects the data and the system from repeated runs. The main techniques:
- Name outputs by what they represent. A backup named
db-2026-11-28.sql.gzis the same artifact however many times the job runs. A name built from the current time, such asdb-$(date +%s).sql.gz, makes every rerun a new artifact. - Declare a desired state instead of an action.
mkdir -p,ln -sfn,rsync, and SQLINSERT ... ON CONFLICT DO UPDATEall say "make it look like this," and they are safe to repeat. Appending with>>, incrementing a counter, andINSERTwithout a uniqueness constraint are not. - Record completion with a marker. If the work is expensive, check for the result first and skip when it is already there.
- Process each input at most once. When a job handles files from a spool directory, move each input to a
done/directory only after it has been handled. A rerun after a crash then reprocesses the one unfinished file and no others.
Here is the backup job from earlier, made idempotent with a dated name and a skip check:
#!/usr/bin/env bash
set -euo pipefail
day=$(date +%F)
out="/var/backups/db-${day}.sql.gz"
if [[ -s $out ]]; then
echo "backup for ${day} already exists, nothing to do"
exit 0
fi
tmp=$(mktemp "${out}.XXXXXX")
trap 'rm -f "$tmp"' EXIT
pg_dump mydb | gzip > "$tmp"
chmod 640 "$tmp"
mv -T "$tmp" "$out"The check works because the final name appears only after a complete rename. A file at $out is always a finished backup. Had the script written directly to $out, a crashed run would leave a partial file that the next run mistook for a success.
Choosing what a rerun should do
Skipping is not always right. Sometimes a rerun should refresh the result, such as a "latest metrics" file that must reflect current data. In that case the job overwrites the target atomically each time. Decide per job which kind it is:
- Skip if done suits results tied to a period (a day's backup, a month's invoice run).
- Rebuild and replace suits derived data that is always meant to be current.
Both are idempotent. Neither is safe without the atomic write.
Exercise
A job writes its report to /tmp/report.csv and then runs mv /tmp/report.csv /srv/reports/report.csv. Another service reads /srv/reports/report.csv every minute and sometimes finds it truncated. /tmp is a tmpfs and /srv is on a disk partition. What is wrong, and how do you fix it?
Show answer
The mv crosses filesystems, so it copies the data and then deletes the source. The copy is not atomic, and the reader can open the destination while it is half written. Create the temporary file in the destination directory instead, for example tmp=$(mktemp /srv/reports/report.csv.XXXXXX), write the report there, and then mv -T "$tmp" /srv/reports/report.csv. The rename then happens within one filesystem and is atomic.
Exercise
A nightly job runs echo "$(date +%F) processed" >> /var/log/nightly-summary.txt after its work. A timer with Persistent=true sometimes triggers it twice in one day. Name the problem and give one way to make the job safe to repeat.
Show answer
The >> append is not idempotent, so every extra run adds a duplicate line. One fix is to write the summary to a per-day file, such as /var/log/nightly-summary-2026-11-28.txt, using an atomic temp-file-and-rename write, so a repeated run replaces identical content. Another fix is to check whether a line for today already exists (for example with grep -q) and skip the append if it does. Wrap the job in flock -n as well, so the check and the append cannot race.