Sub topic 9
Idempotent Jobs and Atomic Writes
Assume you are comfortable with shell scripts, exit codes, file permissions, and basic process behavior. This chapter focuses on two properties that make recurring jobs safe: idempotency and atomic writes.
Make repeated runs safe
An idempotent job produces the same intended result when you run it once or many times. This matters because schedulers can retry jobs, operators can start them by hand, and a missed run may be followed by a catch-up run.
For example, this command makes sure a directory exists:
install -d -m 0750 /var/lib/myapp/cacheRunning it repeatedly does not create duplicate directories or change the desired result.
By contrast, this command is not idempotent:
printf '%s\n' "$(date -Is)" >> /var/log/myapp-runs.logEvery run adds another line. That behavior may be correct for an audit log, but it is not idempotent. Decide whether the job should create an event, or reconcile a resource with a desired state.
Common idempotent patterns include:
- Set a configuration file to the desired contents.
- Create a record using a stable unique key, then update that record on later runs.
- Delete temporary files that no longer belong to the desired set.
- Replace a generated report instead of appending to it.
- Record a completed item with an identifier that prevents duplicate processing.
Use stable input identifiers. A job that sends an email each time it sees an item needs a durable record or provider-side idempotency key. A shell lock prevents simultaneous runs, but it does not prevent duplicates across later runs.
Write files atomically
A direct write can leave a partial file if the process stops midway:
generate_report > /var/lib/myapp/report.txtReaders may observe an empty or incomplete report. An atomic write creates the new contents in a temporary file and then renames that file into place. On the same filesystem, mv changes the directory entry in one operation, so readers see either the old complete file or the new complete file.
#!/usr/bin/env bash
set -euo pipefail
target=/tmp/myapp-report.txt
tmp=$(mktemp "${target}.XXXXXX")
trap 'rm -f -- "$tmp"' EXIT
printf 'kernel=%s\n' "$(uname -srm)" > "$tmp"
printf 'generated_by=recurring-job\n' >> "$tmp"
chmod 0644 "$tmp"
mv -f -- "$tmp" "$target"
trap - EXITThe temporary file is created beside the target. This is important because a rename across filesystems may fail or stop being atomic. The trap removes the temporary file if the script exits before the rename. set -euo pipefail makes failures visible instead of silently publishing bad output.
Do not use a temporary filename that multiple instances can share. mktemp creates a unique name. If two instances can run concurrently, also use a lock.
Choose the right update method
| Operation | Safe repeated result | Main concern |
|---|---|---|
| Create a directory with `install -d` | Yes | Permissions must be intentional |
| Replace a file with same-directory `mv` | Yes, if contents are deterministic | Keep temporary and target on one filesystem |
| Append to a log | No | Duplicate entries may be expected |
| Insert a database row | Depends | Use a unique key or idempotency key |
Atomic replacement protects readers from partial files. It does not make the generation itself correct. Validate data before the rename, and do not rename a file when validation fails.
Exercise
Why should an atomic-write script create its temporary file in the target file's directory?
Show answer
The final rename should stay on the same filesystem, where it can replace the directory entry atomically. A temporary file in another filesystem may make the rename fail or require a non-atomic copy.