Sub topic 10
Timeouts and Bounded Retries
This chapter assumes you can write shell scripts, read exit codes, and have a cron or systemd timer job running. It also assumes you know what flock does from the chapter on overlapping runs. Here you will deal with two failure modes: a job that hangs forever, and a job that fails for a reason that will go away on its own.
Why a job needs a time limit
A scheduled job can fail in a way that never produces an error: it never finishes. Typical causes are a network connection that stalls, a database lock that is never released, or a remote server that accepts a connection and then sends nothing.
A hung job causes three problems:
- It holds its lock, so every later run exits immediately because of
flock -n. The schedule looks healthy, but no work is done. - It holds resources such as database connections, file handles, and memory.
- It produces no exit status. Failure alerts that depend on a non-zero exit never fire, because the process never exits.
A timeout turns "never finishes" into "failed". A failure is something your logging and monitoring can already handle.
Pick a limit from real run times
Set the timeout above the longest normal run and well below the schedule interval. Measure first. If a job usually takes 4 minutes and runs every 15 minutes, a limit of 10 minutes leaves room for slow days and still ends before the next run starts.
A limit that is too tight kills healthy runs. A limit that is too loose lets a hung run block the next several runs. When a job's run time grows, raise the limit on purpose, and treat the growth as a signal worth investigating.
Timeouts in a shell script with `timeout`
The timeout command from GNU coreutils runs a command and kills it after a duration.
timeout 10m /usr/local/bin/sync.sh
echo "exit status: $?"If the limit is reached, timeout sends SIGTERM and exits with status 124. If the command ignores SIGTERM, add -k to follow up with SIGKILL after a grace period:
timeout --kill-after=30s 10m /usr/local/bin/sync.shWith -k, a command killed by SIGKILL makes timeout exit with status 137. A plain SIGTERM timeout still reports 124.
| Exit status | Meaning |
|---|---|
| 0 | The command finished successfully |
| 1–123 | The command failed with its own status |
| 124 | The time limit was reached and the command was stopped |
| 125 | `timeout` itself failed |
| 126 | The command was found but could not be run |
| 127 | The command was not found |
| 137 | The command was killed with SIGKILL |
Distinguishing 124 from an ordinary failure lets a script log "timed out" instead of "failed".
A gotcha: `timeout` and pipelines
timeout wraps one command. In pg_dump mydb | gzip > out.gz, writing timeout 5m pg_dump mydb | gzip limits only pg_dump. Wrap the part that can hang, or wrap the whole pipeline in a shell:
timeout 5m bash -c 'set -o pipefail; pg_dump mydb | gzip > /tmp/db.sql.gz'Child processes are another gotcha. If a script starts children, timeout signals only its direct child by default. Use --foreground carefully, and prefer a systemd limit (below) when the job spawns many processes, because systemd tracks the whole control group.
Timeouts in systemd
A service unit can set its own limit. In the backup example from earlier chapters, the service already had:
[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh
TimeoutStartSec=1hFor a Type=oneshot service, TimeoutStartSec limits how long the start phase may run, which is the whole job. When it expires, systemd stops the service and marks it failed. It sends SIGTERM to the processes in the unit's control group, waits TimeoutStopSec, and then sends SIGKILL.
A more explicit option for jobs is RuntimeMaxSec, which limits total run time for any service type:
[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh
RuntimeMaxSec=45min
TimeoutStopSec=30sAfter a timeout, systemctl status backup.service shows a result of timeout, and journalctl -u backup.service records the stop. Because the unit is marked failed, you can hook alerting to it with OnFailure=.
Why retries need care
Some failures are temporary: a DNS lookup that fails once, an API that returns 503, a database that restarts for a minute. Trying again fixes these. Other failures are permanent: a wrong password, a missing file, a bug. Trying again never fixes them.
An unbounded retry loop is dangerous:
- It can run forever and hold the lock, which is the hang problem again.
- It can hammer a struggling server and make the outage longer.
- It hides permanent failures behind a job that always looks busy.
A bounded retry has three parts: a maximum number of attempts, a delay between attempts that grows, and a total time limit.
A bounded retry in shell
This function tries a command up to a fixed number of times, doubles the wait each time, and returns the last exit status.
#!/usr/bin/env bash
set -euo pipefail
retry() {
local max=$1 delay=$2
shift 2
local attempt=1 status=0
while true; do
status=0
"$@" || status=$?
if [ "$status" -eq 0 ]; then
return 0
fi
if [ "$attempt" -ge "$max" ]; then
echo "giving up after $attempt attempts (status $status): $*" >&2
return "$status"
fi
echo "attempt $attempt failed (status $status), retrying in ${delay}s" >&2
sleep "$delay"
delay=$((delay * 2))
attempt=$((attempt + 1))
done
}
retry 4 5 timeout 2m curl -fsS -o /tmp/data.json https://api.example.com/dataWorth noting in this script:
- The
|| status=$?form keepsset -efrom ending the script when the command fails, so the function can decide what to do. - Each attempt has its own
timeout, so one stalled attempt cannot use up the whole budget. - With 4 attempts and a 5-second starting delay, the waits are 5, 10, and 20 seconds. Worst-case run time is the sum of the waits plus 4 times 2 minutes. Check that this total is below the job's overall limit and its schedule interval.
- The function returns the last non-zero status, so the job still fails loudly if every attempt fails.
Add random jitter to the delay if many machines run the same job at the same minute. Otherwise, they all retry together and can overload the service again.
Retry only what is safe to repeat
Retrying runs the same step again, possibly after it partly succeeded. This is only safe if the step is idempotent, as covered in the previous chapter. A retry of "append a row" can create duplicates. A retry of "write to a temporary file and rename it" cannot.
Also retry only errors that can be temporary. For curl, the --retry option retries on timeouts and on HTTP 408, 429, 500, 502, 503, and 504, but not on other 4xx errors. That is a sensible default. Other tools may not make that distinction, so decide it yourself: retry on a connection failure, but give up at once on an authentication failure.
Retries built into curl
The heartbeat call in the backup script uses curl's own options:
curl -fsS -m 10 --retry 3 --retry-delay 2 --retry-max-time 40 \
-o /dev/null https://hc.example.com/ping/your-check-idHere -m 10 limits each attempt to 10 seconds, --retry 3 allows three more attempts, and --retry-max-time 40 stops retrying after 40 seconds in total. Using the tool's built-in retry is simpler than writing a loop, so prefer it when it exists.
Retries with systemd: `Restart=` is for services, not jobs
systemd can restart failed services, and it is tempting to use Restart=on-failure on a job. Be careful. Restarting a Type=oneshot unit is restricted: Restart=always and Restart=on-success are not allowed for it, and only Restart=on-failure is accepted in recent versions. If you do use it, bound it:
[Unit]
StartLimitIntervalSec=30min
StartLimitBurst=3
[Service]
Type=oneshot
ExecStart=/usr/local/bin/sync.sh
Restart=on-failure
RestartSec=2minStartLimitBurst=3 within StartLimitIntervalSec=30min means that after three starts in 30 minutes, systemd refuses further starts and the unit enters a failed state until the window passes or you reset it with systemctl reset-failed. Note that the unit-level start limit applies to every start, including starts from the timer. Check the effective behavior on your systemd version with a test run before relying on it.
For most jobs, retrying inside the script, where you control which errors are retried, is easier to reason about than systemd restarts.
Putting limits together
The pieces fit as layers, from the inside out.
The diagram below shows the layers.
Rules that keep the layers consistent:
- Each attempt limit is shorter than the whole-job limit.
- The whole-job limit is shorter than the schedule interval.
- Worst-case retry time, including waits, fits inside the whole-job limit.
- If the job exits non-zero after the last attempt, nothing reports success to the heartbeat service.
Common errors
- No timeout on network calls.
curlwithout-m, or a database client without a connect timeout, can wait for a very long time. - Retrying a permanent error. A job that retries a bad password for ten minutes only delays the alert.
- Retry budget longer than the interval. The next run starts while the retry loop is still working, and either overlaps or, with
flock -n, is skipped. - Swallowing the final status. A loop that ends with
trueor anechomakes a failed job exit 0. - A timeout that does not reach child processes. Use systemd limits for jobs that start workers.
Exercises
Exercise
A job runs every 10 minutes and normally takes 2 minutes. It calls a flaky API with a retry function that makes 5 attempts, each limited to 3 minutes, with waits of 10, 20, 40, and 80 seconds between attempts. Is this retry budget safe? What would you change?
Show answer
No. The worst case is 5 x 3 minutes plus 150 seconds of waiting, which is 17.5 minutes. That is longer than the 10-minute interval, so the next run would start while this one is still going (or be skipped by flock). Reduce the per-attempt limit (for example 60 seconds), reduce the attempts (for example 3), and add a whole-job limit such as RuntimeMaxSec=8min so the total stays below the interval.
Exercise
A script runs timeout 5m pg_dump mydb | gzip > out.gz. The database hangs. What does the timeout cover, and how would you make the command safer?
Show answer
The timeout covers only pgdump, because the pipe splits the line into two commands. Wrap the whole pipeline, for example `timeout 5m bash -c 'set -o pipefail; pgdump mydb | gzip > tmp.gz'`, write to a temporary file, and rename it only on success. Also check the exit status so status 124 is reported as a timeout.