Sub topic 15
Controlling cost and rate limits
An unattended agent job spends money and provider quota every time it runs, and nobody is watching the meter. This chapter covers how to bound that spending and how to behave when the provider pushes back.
It assumes you have read the chapters on timeouts and exit codes and on logging and run records. You should be comfortable with the wrapper script from earlier in this tutorial, which uses flock, timeout, and a timestamped log file.
Where the money goes
Agent cost is usually driven by tokens. A token is a small chunk of text that the model reads or writes. A run costs roughly the tokens sent to the model plus the tokens it produces, summed over every step of the agent loop. Billing details differ by provider and plan, so check yours. The levers below apply either way.
A headless job has several ways to spend more than you expected:
- A loop. The agent retries a failing test again and again, and each pass re-sends a growing conversation.
- Large context. The prompt tells the agent to "review the whole repository", so it reads far more files than needed.
- Overlap or double triggers. Cron and a CI schedule both fire, or a manual run happens during the scheduled one.
- Retries. A wrapper that restarts a failed run pays for the failed attempt and the new one.
- Drift. The job quietly grows. Someone adds three more tasks to the prompt, and the bill triples.
Each cause maps to a control, summarized here.
| Cause | Control | Where it lives |
|---|---|---|
| Runaway loop | Wall-clock timeout | `timeout`, `timeout-minutes`, `TimeoutStartSec` |
| Large context | Narrow prompt and scoped inputs | Prompt file |
| Overlap | Lock, CI `concurrency` | `flock`, workflow config |
| Repeated triggers | Daily run counter | Wrapper script |
| Retry storms | Capped attempts with backoff | Wrapper script |
| Drift | Per-run usage recorded in logs | Log or run record |
Layered limits
No single limit is enough, so stack them. The timeout stops one run from lasting forever. The run counter stops many runs from stacking up in a day. A provider-side spending cap, if your account supports one, stops everything else. Set the provider cap even if you trust the wrapper, because a wrapper bug is exactly the failure you are insuring against.
A daily run budget
The lock from the earlier chapter prevents two runs at the same moment. It does not stop a job that is triggered ten times sequentially. A small counter file does. Add this to the wrapper after the flock check. Because the lock is held, two runs cannot update the counter at once.
# Daily run budget. Place after the flock check in nightly-agent.sh.
MAX_RUNS_PER_DAY="${MAX_RUNS_PER_DAY:-3}"
STATE_DIR="$HOME/agent-state"
mkdir -p "$STATE_DIR"
COUNT_FILE="$STATE_DIR/runs-$(date -u +%Y%m%d).count"
count=$(cat "$COUNT_FILE" 2>/dev/null || echo 0)
if [ "$count" -ge "$MAX_RUNS_PER_DAY" ]; then
echo "daily run budget reached ($count of $MAX_RUNS_PER_DAY), skipping" >> "$LOG_DIR/skipped.log"
exit 0
fi
echo $((count + 1)) > "$COUNT_FILE"The file name includes the UTC date, so the counter resets itself at midnight UTC. Old count files are tiny, but remove them with a cleanup job so the directory does not grow forever.
Exiting with status 0 on a skip is deliberate. A skip is expected behavior, not a failure. But a job that skips every night is silently doing nothing, so the alerting chapter's "alert on silence" check should notice it.
Rate limits
A rate limit is a cap the provider places on how many requests or tokens you can use in a time window. When you exceed it, the provider rejects requests, commonly with HTTP status 429, and may say how long to wait. Related errors, such as "overloaded" responses, call for the same handling.
Unattended jobs hit rate limits in a few typical ways:
- Several scheduled jobs start at the same minute, such as
0 2 * * *, and share one account. - The job runs on the same API key as people working interactively.
- A retry loop sends requests faster than the window refills.
The fixes, in order of preference:
- Spread start times. Move one job to 02:07 and another to 02:23.
- Give scheduled jobs their own credentials or project, so a human's work cannot starve them and a runaway job cannot starve humans.
- Retry a small, fixed number of times with exponentially growing delays.
Retrying is only safe for rate-limit style failures. If the agent exited because of a timeout, a bad prompt, or a failed test, retrying repeats the same cost for the same result. The wrapper below retries only when the log mentions a rate-limit signal and the status is not 124.
# Retry only on rate-limit style failures, with doubling delay.
# How an agent reports a rate limit is tool-specific. Check your agent's
# output and adjust the grep pattern to match what it actually prints.
max_attempts=3
attempt=1
delay=60
while :; do
echo "=== attempt $attempt at $(date -u +%FT%TZ) ===" >> "$LOG"
timeout 20m $AGENT_CMD < prompts/nightly.md >> "$LOG" 2>&1
status=$?
[ "$status" -eq 0 ] && break
[ "$status" -eq 124 ] && break
[ "$attempt" -ge "$max_attempts" ] && break
tail -n 50 "$LOG" | grep -qiE 'rate.?limit|429|overloaded' || break
echo "rate limited, sleeping ${delay}s" >> "$LOG"
sleep "$delay"
delay=$((delay * 2))
attempt=$((attempt + 1))
doneThe log is opened with >> so every attempt is preserved, and each one starts with a header line. The loop checks only the last 50 lines, so a rate-limit message from an earlier attempt cannot trigger a retry for an unrelated failure.
This loop can run for up to three 20-minute attempts plus sleeps. If your scheduler enforces its own ceiling, such as TimeoutStartSec=30min or timeout-minutes: 30, the outer limit will kill the wrapper mid-retry. Size the outer limit to cover the worst case, or reduce max_attempts.
Keep each run small
The cheapest token is the one never sent. The prompt is your main cost control inside a run:
- Name the files or directories to look at, not "the repository".
- State a stopping condition, such as "Stop after at most 5 findings."
- Ask for one task per job. Two small jobs with separate budgets are easier to reason about than one large one.
- Make the job incremental. Process only what changed since the last successful run, using a commit hash or timestamp stored in the state directory.
Incremental runs help twice. They cost less, and they fail less often, because a smaller task has fewer chances to loop.
Recording usage
Control needs measurement. At minimum, write one line per run to a run record: start time, duration, exit status, attempt count, and the log path. If your agent prints token counts or a cost summary at the end, capture that line too. The format varies by tool, so find out what yours emits before writing a parser.
printf '%s status=%s attempts=%s duration=%ss log=%s\n' \
"$(date -u +%FT%TZ)" "$status" "$attempt" "$SECONDS" "$LOG" \
>> "$LOG_DIR/runs.log"SECONDS is a bash variable holding the seconds since the script started. Review runs.log weekly. A rising duration or attempt count is an early sign of drift, visible before the invoice arrives.
Common mistakes
- Retrying on every nonzero exit. This multiplies cost for failures that retrying cannot fix.
- Retrying without a cap, or without delay. This turns one rate-limit response into a burst of rejected requests.
- Setting
cancel-in-progress: trueon a CI job and then re-triggering it often. Cancelled runs may already have spent tokens. - Putting every scheduled job at minute
0. Many teams do this, so the provider's traffic is also heaviest then. - Counting runs but never reading the counter. Alert when the budget is reached, not only when a run fails.
Exercise
The nightly wrapper retries up to 3 times with delays of 60 and 120 seconds, and each attempt has a 20-minute timeout. The systemd unit has TimeoutStartSec=30min. What goes wrong in the worst case, and what are two ways to fix it?
Show answer
The worst case is 3 x 20 minutes of agent time plus 3 minutes of sleep, about 63 minutes, which exceeds the 30-minute unit limit. systemd would stop the job during a retry, so the wrapper never reaches its final logging and exit-status handling. Fixes: raise TimeoutStartSec to cover the worst case (for example 70min), or lower max_attempts or the per-attempt timeout so the total fits within 30 minutes.
Exercise
Why does the retry loop skip retrying when the status is 124, even if the log contains the word "overloaded"?
Show answer
Status 124 means the timeout killed the run, so the agent was working (or stuck) for the full 20 minutes. Retrying would pay for another full attempt with no sign that the outcome would differ. Rate-limit retries are only useful for failures that happen quickly and are caused by the provider's request limits.