Sub topic 10
Timeouts and Bounded Retries
Assume you are comfortable with shell scripts, exit codes, processes, and reading service logs. This chapter shows how to stop a scheduled job that hangs and how to retry failures without creating an endless loop.
Why Jobs Need Time Limits
A process can wait forever for a network connection, a locked database, or a broken remote service. A scheduler usually sees this process as still running. It will not know that the job has made no progress.
A timeout is a maximum amount of time allowed for an operation. When the limit expires, the operation is stopped and returns a failure status. Use timeouts at more than one level:
| Boundary | What it limits | Example |
|---|---|---|
| Network command | One connection or request | `curl --max-time 30` |
| Shell command | One external program | `timeout 30s backup-step` |
| Service unit | The complete scheduled job | `TimeoutStartSec=3min` |
The limit should match the operation. A quick health check may need 10 seconds. A database export may need several minutes. A limit that is too short causes false failures, while a limit that is too long delays alerts.
With cron, wrap a job in the timeout command:
*/15 * * * * /usr/bin/timeout 10m /usr/local/bin/sync.sh >> /var/log/sync.log 2>&1The timeout command returns status 124 when it stops a command because the limit expired. The redirected output and nonzero status make the failure visible to your logging and monitoring system.
Retrying Transient Failures
Some failures are temporary. A service may reject a request during a restart, or a network route may recover shortly. A retry repeats an operation after a failure.
Retries should be bounded. Set all of these values deliberately:
- The maximum time for one attempt.
- The maximum number of attempts.
- The delay between attempts.
- The total time allowed for the whole job.
Exponential backoff increases the delay after each failure. This reduces pressure on an unhealthy service.
#!/usr/bin/env bash
set -u
attempt=1
max_attempts=4
delay=5
while (( attempt <= max_attempts )); do
if /usr/bin/timeout --foreground 30s \
/usr/local/bin/publish-report
then
echo "publish succeeded on attempt $attempt"
exit 0
fi
status=$?
echo "publish failed on attempt $attempt with status $status" >&2
if (( attempt == max_attempts )); then
echo "publish failed after $max_attempts attempts" >&2
exit 1
fi
sleep "$delay"
delay=$((delay * 2))
attempt=$((attempt + 1))
doneThis script allows four attempts. The delays are 5, 10, and 20 seconds. Each attempt can run for up to 30 seconds, so the maximum planned time is 155 seconds, not including small process overhead.
Do not retry every failure automatically. Invalid credentials, malformed input, and permission errors usually need correction rather than repetition. Retry temporary network or service errors when the operation is safe to repeat.
Bounding a systemd Job
A systemd timer starts a service unit. Put the overall limit in the service unit, even when the script has its own per-command timeout.
# /etc/systemd/system/publish-report.service
[Unit]
Description=Publish report with bounded retries
[Service]
Type=oneshot
User=reporter
ExecStart=/usr/local/bin/publish-with-retries
TimeoutStartSec=3minTimeoutStartSec limits the service startup operation. If the retry script exceeds three minutes, systemd stops it and records a failure. Inspect the result with:
sudo systemctl start publish-report.service
systemctl status publish-report.service
journalctl -u publish-report.service --since todayThe outer timeout protects the server from a bug in the script. The inner timeout protects each individual command. Both should be present when a command can hang.
Make Retries Safe
A retry can run after the first attempt changed part of the system. For example, a file may have been uploaded even though the client timed out before receiving the response.
Design the operation to be idempotent. An idempotent operation produces the same intended result when repeated. Use a stable job identifier, a destination-specific temporary file, or a remote API request ID. Write files to a temporary path and rename them only after the complete operation succeeds.
Exercise
A job may take 40 seconds when successful, but sometimes hangs. It has three allowed attempts with 10-second delays. What should you change first?
Show answer
Set an attempt timeout longer than the normal 40-second runtime, then set an outer job timeout that covers three attempts and both delays. Also verify that repeating the operation is safe.