# Respect API Rate Limits from a Hosted Mac Agent

Canonical: https://figment.so/blog/mac-agent-api-polling

Read the Retry-After header on every 429 and set your launchd interval from the API's published limit. A polling agent like this runs on a Figment Intel Mac VM ($25 a month).

When a polling agent keeps getting 429 responses, read the `Retry-After` header the server already sent, and set your launchd interval from the API's published rate window instead of guessing a sleep. This page gives you a complete agent for a hosted Mac and a worksheet that picks the interval. A network-only polling agent runs on Figment's Intel Mac VM at $25 a month.

## Which Figment plan fits a polling agent?

The [Intel Mac VM](/mac-hosting#intel-vm) ($25 a month, $2 a day, $0.15 an hour) fits pure API polling with `curl`, `requests` or a Node client. It has 4 shared vCPUs, 4GB of RAM and an 80GB SSD, and runs macOS Sequoia, so launchd, `security` and Homebrew-installed clients all work. Reach it over SSH, encrypted remote desktop or the browser. A network-bound poller does not need more.

Choose another plan when the workload needs more than network calls:

- **[Apple Silicon Mac VM](/mac-hosting#apple-silicon-vm)** ($39 a month, $6 a day): arm64-only tools, Xcode 26.4 or later, or visionOS tooling. It has 4 shared vCPUs and 4GB of RAM.
- **[Dedicated M4 Pro 48 GB](/mac-hosting#dedicated-m4-pro)** ($349 a month, or $299 a month on a 12-month term): a heavy production agent that should not share hardware (M4 Pro, 48GB RAM, 512GB SSD).

A two-week project does not need a month: the daily Intel plan covers 14 days for 14 × $2 = $28, and a monthly plan renews until you cancel. Billing does not pause while the agent is idle; stop an hourly or daily Mac in Figment to end it. Figment runs the Mac and network layer; the agent, its schedule and its monitoring are yours.

## What do I need to decide before writing the poller?

Document the agent's contract first, because a missing input fails silently inside a launchd job.

| Input | Where it lives |
|---|---|
| API base URL | `EnvironmentVariables` in the launchd plist |
| Auth token | macOS Keychain via `security add-generic-password` |
| Poll interval | `StartInterval` (seconds) |
| Output path | Local path or mounted volume |
| Rate-limit budget | From your API provider's docs |

Keep the token out of the plist and out of shell history. Add it once from an SSH or desktop terminal session, then read it at runtime:

```bash
TOKEN="$(security find-generic-password -a poll-agent -s api-token -w)"
```

If the API uses OAuth, run the one-time browser authorization on the Mac, write the refresh token to Keychain, and let the agent refresh headlessly from then on.

## How do I handle a 429 response?

Wait for the number of seconds in `Retry-After`, and fall back to exponential backoff when the header is missing or date-formatted. [RFC 6585](https://datatracker.ietf.org/doc/html/rfc6585) defines `429 Too Many Requests` and notes the response MAY include a `Retry-After` header. `Retry-After` can be an integer number of seconds or an HTTP-date (see [RFC 7231 §7.1.3](https://datatracker.ietf.org/doc/html/rfc7231#section-7.1.3)). The script parses the integer form. Extend it with `date -j -f` if your provider uses HTTP-dates.

```bash
#!/usr/bin/env bash
set -euo pipefail

API_URL="${API_BASE_URL:?API_BASE_URL not set}"
TOKEN="$(security find-generic-password -a poll-agent -s api-token -w)"
LOG="$HOME/Library/Logs/poll-agent.log"
BODY="$(mktemp -t poll-body)"
HEADERS="$(mktemp -t poll-headers)"
trap 'rm -f "$BODY" "$HEADERS"' EXIT

MAX_RETRIES=5
BACKOFF=10
attempt=0

while (( attempt < MAX_RETRIES )); do
  HTTP_CODE=$(curl -sS \
    -o "$BODY" -D "$HEADERS" -w "%{http_code}" \
    -H "Authorization: Bearer $TOKEN" \
    "$API_URL")

  case "$HTTP_CODE" in
    200)
      printf '%s OK\n' "$(date -u +%FT%TZ)" >> "$LOG"
      # Hand "$BODY" to your own processor here.
      exit 0
      ;;
    429)
      RA=$(awk 'BEGIN{IGNORECASE=1} /^Retry-After:/ {gsub(/\r/,""); print $2; exit}' "$HEADERS")
      if [[ "$RA" =~ ^[0-9]+$ ]]; then
        printf '%s 429 Retry-After=%ss\n' "$(date -u +%FT%TZ)" "$RA" >> "$LOG"
        sleep "$RA"
      else
        printf '%s 429 backoff=%ss\n' "$(date -u +%FT%TZ)" "$BACKOFF" >> "$LOG"
        sleep "$BACKOFF"
        BACKOFF=$(( BACKOFF * 2 ))
      fi
      ;;
    *)
      printf '%s HTTP %s abort\n' "$(date -u +%FT%TZ)" "$HTTP_CODE" >> "$LOG"
      exit 1
      ;;
  esac
  attempt=$(( attempt + 1 ))
done

printf '%s max retries exceeded\n' "$(date -u +%FT%TZ)" >> "$LOG"
exit 1
```

This is an untested example, not a benchmark. Save it as `~/bin/poll-agent.sh`, run `chmod +x`, then test it once by hand against your real endpoint before letting launchd run it.

## What interval should I set?

Use `interval >= ceil(window / limit) * 1.1`, so clock drift does not push you over the limit. Fill the right-hand column for your API, then copy the value into the plist's `StartInterval`.

| API documented limit | Window | Safe `StartInterval` (s) | Retry-After behaviour |
|---|---|---|---|
| 60 req/min | 60 s | 66 | Use header; fall back to 60 s |
| 1,000 req/day | 86,400 s | 95 | Use header; fall back to 300 s |
| 100 req/hour | 3,600 s | 40 | Use header; fall back to 120 s |
| 5 req/sec burst | 1 s | 5 | Header is mandatory |
| Undocumented | n/a | 300 | Header is mandatory |

At `StartInterval=66` the agent makes about 1,309 calls per day, inside a 60/min quota with headroom for the occasional retry.

## How do I install the launchd agent?

Save this to `~/Library/LaunchAgents/com.example.poll-agent.plist`. Apple defines the key semantics in [Creating launchd Jobs](https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html).

```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
  "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key><string>com.example.poll-agent</string>
  <key>ProgramArguments</key>
  <array>
    <string>/bin/bash</string>
    <string>/Users/agent/bin/poll-agent.sh</string>
  </array>
  <key>StartInterval</key><integer>66</integer>
  <key>StandardOutPath</key><string>/Users/agent/Library/Logs/poll-agent.out</string>
  <key>StandardErrorPath</key><string>/Users/agent/Library/Logs/poll-agent.err</string>
  <key>EnvironmentVariables</key>
  <dict>
    <key>API_BASE_URL</key><string>https://api.example.com/v1/items</string>
  </dict>
</dict>
</plist>
```

Load it with `launchctl bootstrap gui/$UID ~/Library/LaunchAgents/com.example.poll-agent.plist`. Omit `KeepAlive`: the job should exit after each run and let launchd relaunch it on the interval, so a bad call never trips the "respawning too fast" throttle.

## What should I check after the first day?

Review these after the first 24 hours:

- **Log pattern.** `tail -50 ~/Library/Logs/poll-agent.log` should be mostly `OK`. More than 10% `429` rows means the window is too tight.
- **Auth expiry.** A run of `HTTP 401` means the refresh failed. Re-run the Keychain read by hand to separate a token problem from a network problem.
- **Missed runs after sleep.** launchd fires one catch-up invocation after wake, not a queue. For strict schedules, keep the Mac awake with `pmset`.
- **Log growth.** `poll-agent.log` is append-only. Add a `newsyslog.d` rule or truncate in the script above a size threshold.
- **5xx responses.** These are server-side. Use a flat 30-second retry rather than burning rate-limit budget.

## How do I start, or move an existing poller?

Pick the Intel Mac VM on the [Mac hosting plans](/mac-hosting) for a network-only agent, connect over SSH, create `~/bin`, save the script, store the token in Keychain, drop the plist in `~/Library/LaunchAgents`, and bootstrap it.

To migrate from another host, copy the script and plist, re-add secrets directly on the new machine (never copy a Keychain database between hosts), bootstrap the agent, and confirm one clean `OK` in the log before you decommission the old runner. Keep the old runner's schedule off while both exist, so the two do not poll against the same rate limit.

**Related guides**
- [Download completion handling on a Mac agent](/blog/mac-agent-download-completion)
- [Network recovery for Mac automation agents](/blog/mac-agent-network-recovery)
- [GitHub Actions self-hosted runner on a Mac](/blog/mac-github-actions-self-hosted-runner)
