# Set Retry Limits for Automation on a Hosted Mac

Canonical: https://figment.so/blog/mac-agent-retry-budget

Set a fixed attempt limit per error class, back off with jitter, honor Retry-After, stop at once on terminal errors, and leave process crashes to launchd. A Figment Intel Mac VM ($25 a month) runs the loop.

Give every error class a fixed attempt limit, back off exponentially with jitter, honor the server's `Retry-After` header, stop immediately on errors that retrying cannot fix, and leave process crashes to launchd. An agent that retries forever wastes resources and can flood a downstream API. One that never retries drops work on the first network blip. The retry loop sleeps between attempts, so a Figment Intel Mac VM ($25 a month) runs it comfortably.

## Which Figment Mac plan fits a retry loop?

Retry logic runs wherever the job runs, so the plan follows the job. Prices are USD before tax.

| Job profile | Figment plan | Price |
|---|---|---|
| HTTP calls, git, shell, file processing, Xcode 26.0 to 26.3 builds | [Intel Mac VM](/mac-hosting#intel-vm), 4 shared vCPUs, 4GB, 80GB, macOS Sequoia | $25 a month, $2 a day, $0.15 an hour |
| arm64-only binaries, Xcode 26.4 or later, the Apple silicon Simulator | [Apple Silicon Mac VM](/mac-hosting#apple-silicon-vm), 4 shared vCPUs, 4GB, 65GB | $39 a month, $6 a day, $0.40 an hour |
| GPU-heavy or memory-heavy tasks, or a Mac no other customer shares | [Dedicated M4 Pro 48 GB](/mac-hosting#dedicated-m4-pro), M4 Pro, 48GB, 512GB | $349 a month ($299 on a 12-month term) |

For a self-managed retry loop that drives HTTP APIs or shell work, the Intel VM is enough. It runs macOS, so `launchd`, `bash`, `curl` and `plutil` work as on any other Mac. VisionOS and arm64-only binaries need an Apple silicon plan. The Intel Mac VM and the Dedicated M4 Pro include SSH, encrypted remote desktop and browser access; the Apple Silicon Mac VM has the browser desktop and SSH.

## What does a retry budget look like?

Write it down before you write code. This table covers the error classes that appear most often in API-backed agents.

| Error class | Trigger | Retry? | Max attempts | Base delay | Max delay | Notes |
|---|---|---|---|---|---|---|
| Transient network | Timeout, DNS failure, connection reset | Yes | 5 | 2s | 60s | Exponential backoff with jitter |
| Rate limit | HTTP 429 | Yes | 5 | Honor `Retry-After`, else 10s | 120s | Server hint overrides calculated delay |
| Server error | HTTP 500, 502, 503, 504 | Yes | 3 | 5s | 60s | Fewer attempts, because upstream may be degraded |
| Auth failure | HTTP 401, 403 | No | n/a | n/a | n/a | The same token keeps failing. Alert the operator |
| Client error | HTTP 400, 422 | No | n/a | n/a | n/a | Input is invalid. Fix the data, do not retry |
| Not found | HTTP 404 | No | n/a | n/a | n/a | Resource does not exist |
| Conflict | HTTP 409 | Conditional | 1 | 1s | n/a | Re-fetch state, then decide |
| Agent crash or non-zero exit | Signal or unhandled exception | Delegated to launchd | See plist | n/a | n/a | `KeepAlive` with `SuccessfulExit = false` restarts only on non-zero exit |

Terminal errors must stop the job on the first occurrence. Retrying a 401 with the same credentials only burns budget and risks a lockout. Retrying a 400 means the payload is wrong, and more attempts will not fix it.

## How do I implement backoff with jitter in shell?

Use a reusable function that takes the attempt limit, base delay, max delay and the command.

```bash
#!/usr/bin/env bash
# retry.sh — reusable retry with exponential backoff + jitter.
# Usage: retry <max_attempts> <base_delay_s> <max_delay_s> <command> [args...]
set -euo pipefail

retry() {
  local max_attempts="$1" base_delay="$2" max_delay="$3"
  shift 3
  local cmd=("$@") attempt=1 delay exit_code jitter sleep_time

  while (( attempt <= max_attempts )); do
    printf '[%s] attempt %d/%d: %s\n' \
      "$(date -u +%FT%TZ)" "$attempt" "$max_attempts" "${cmd[*]}" >&2

    if "${cmd[@]}"; then
      return 0
    fi
    exit_code=$?

    if (( attempt == max_attempts )); then
      printf '[%s] exhausted after %d attempts, last exit %d\n' \
        "$(date -u +%FT%TZ)" "$max_attempts" "$exit_code" >&2
      return "$exit_code"
    fi

    delay=$(( base_delay * (1 << (attempt - 1)) ))
    (( delay > max_delay )) && delay=$max_delay
    jitter=$(( RANDOM % (delay / 4 + 1) ))
    sleep_time=$(( delay + jitter ))

    printf '[%s] sleeping %ds before retry\n' \
      "$(date -u +%FT%TZ)" "$sleep_time" >&2
    sleep "$sleep_time"
    (( attempt++ ))
  done
}
```

This is an untested reference example. Run it against your own command with the parameters above and keep the timings in your own log. `set -euo pipefail` makes a failed command inside the retried function surface its exit code instead of counting as success.

## How do I handle the Retry-After header?

Prefer it over the calculated delay, because the server knows better than the client when it will accept work again. Per the [MDN `Retry-After` reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After), the value is either a non-negative integer number of seconds or an HTTP-date, and it is defined for 429, 503 and some redirect responses.

```bash
call_api() {
  local body_file headers_file http_code retry_after
  body_file=$(mktemp -t agent_body.XXXXXX)
  headers_file=$(mktemp -t agent_hdr.XXXXXX)
  trap 'rm -f "$body_file" "$headers_file"' RETURN

  http_code=$(curl --silent --max-time 30 \
    --output "$body_file" --dump-header "$headers_file" \
    --write-out '%{http_code}' \
    -H "Authorization: Bearer ${API_TOKEN}" \
    -H "Content-Type: application/json" \
    -X POST "${API_ENDPOINT}" --data "$1")

  case "$http_code" in
    2*) cat "$body_file"; return 0 ;;
    429|503)
      retry_after=$(awk 'tolower($1)=="retry-after:"{print $2}' "$headers_file" | tr -d '\r')
      printf 'RATE_LIMITED:%s\n' "${retry_after:-}" >&2
      return 2 ;;
    *) printf 'HTTP_ERROR:%s\n' "$http_code" >&2; return 1 ;;
  esac
}
```

The caller inspects exit code 2. If `Retry-After` is a plain integer, it sleeps that many seconds before the next attempt. If it is an HTTP-date, parse it with `date -j -f` on macOS and compute the difference.

## Who restarts the agent after a crash?

launchd does, not the retry function. Apple's [Creating Launchd Jobs guide](https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html) says a job that exits within 10 seconds of launch may be treated as misbehaving and throttled, so your agent must stay up at least that long before it exits, even on failure.

```xml
<key>KeepAlive</key>
<dict>
    <key>SuccessfulExit</key>
    <false/>
</dict>
<key>ThrottleInterval</key>
<integer>30</integer>
```

With `SuccessfulExit = false`, launchd restarts the job only when it exits non-zero, so a clean exit after a drained queue does not relaunch forever. `ThrottleInterval` sets a minimum spacing between relaunches. Apple does not publish a hard maximum restart count, so watch your own logs.

## What is the backoff schedule?

With `base_delay = 2s`, `max_delay = 60s` and no jitter:

| Attempt | Delay before this attempt | Cumulative wait |
|---|---|---|
| 1 | 0s | 0s |
| 2 | 2s | 2s |
| 3 | 4s | 6s |
| 4 | 8s | 14s |
| 5 | 16s | 30s |

Five attempts use up the budget in about 30 seconds, which usually rides out a brief upstream problem without running long enough to miss a cron window.

## How do I test the retry budget?

Run these five checks:

- Point `call_api` at a sink that returns 500 and confirm the loop fires exactly `max_attempts` times, then exits non-zero.
- Return 401 once and confirm the script exits on attempt one with a single log line.
- Return 429 with `Retry-After: 15` and confirm the caller waits about 15 seconds, not the calculated delay.
- Kill the agent with `SIGKILL` and confirm launchd relaunches it after `ThrottleInterval`, and that a clean `exit 0` does not relaunch.
- After the budget is exhausted, write a terminal status to your idempotency ledger so a redelivery does not start a fresh retry cycle under the same key.

## What does the retry loop cost?

Almost nothing extra, because the agent sleeps between attempts. The plan price is the cost: $25 a month on the Intel VM, or $2 for a day of testing. Move to an Apple silicon plan only if the job needs arm64-only execution or Xcode 26.4 or later. See all [Mac hosting plans](/mac-hosting).

Related: [Run Mac Shortcuts from the command line](/blog/mac-shortcuts-command-line) · [Batch rename files in Finder on a hosted Mac](/blog/mac-finder-batch-rename) · [GitHub Actions self-hosted runner on a Mac](/blog/mac-github-actions-self-hosted-runner)
