Sub topic 15
Controlling Cost and Rate Limits
An unattended agent has no person watching its spend. A loop, a large repository, or a schedule that fires too often can use a lot of tokens before anyone notices. This chapter covers the controls you can apply around the agent.
This chapter assumes you have read the earlier chapters on timeouts, exit codes, and logging, because those are the tools used here.
Where cost comes from
Cost in a scheduled job comes from three sources:
- Frequency. Each run costs money, so an hourly schedule costs 24 times as much as a daily one.
- Size per run. A longer prompt, more files read, and more tool calls each add tokens.
- Retries. A failed run that is retried automatically pays again.
Apply limits at several layers
No single control is enough. Use more than one, and let the outer layers catch what the inner ones miss.
| Layer | Control | What it stops |
|---|---|---|
| Provider account | Spend cap or budget alert | A bill that grows without bound |
| Scheduler | Fewer runs, `timeout`, CI `timeout-minutes` | Runaway duration |
| Wrapper script | Daily run counter | Accidental extra runs |
| Prompt | Narrow scope, such as "only files changed since yesterday" | Large inputs |
Set the provider-level cap first. It is the only layer that still works if your own script is buggy. Check your provider's console for budget and usage alerts, and check your agent's documentation for any per-run limits it offers, such as a maximum number of turns.
A run counter in the wrapper
The wrapper can refuse to start once a daily cap is reached. Run this guard before the agent command in your wrapper script.
#!/usr/bin/env bash
# budget-guard.sh: refuse to start if today's run count has reached the cap.
set -eu
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=0
[ -f "$COUNT_FILE" ] && count=$(cat "$COUNT_FILE")
if [ "$count" -ge "$MAX_RUNS_PER_DAY" ]; then
echo "daily run cap of $MAX_RUNS_PER_DAY reached, not starting" >&2
exit 75
fi
echo $((count + 1)) > "$COUNT_FILE"Exit status 75 is the conventional "temporary failure" code (EX_TEMPFAIL). Your alerting can treat it differently from a real agent failure. The counter file is not protected by a lock, so run the guard after the flock step from the overlap chapter.
Handling rate limits
A rate limit is a cap on requests or tokens per time window. When the provider rejects a request, the agent may fail or retry on its own.
- Do not retry in a tight loop. Wait and try again later, with increasing delays.
- Cap the number of retries. Two or three is usually enough for a nightly job.
- Spread out jobs. If several scheduled agents share one account, give them different start times rather than all running at 02:00.
- Prefer failing the run to retrying for hours. The next scheduled run is a natural retry.
Record usage
Use the logging you already have. Write the start time, the duration, and the exit status of each run to a log. If your agent reports token usage in its output, extract it and append one line per run to a file. A weekly look at that file shows trends before the invoice does.
Exercise
A nightly agent job is retried automatically up to five times on failure, and the provider is returning rate-limit errors. Name two controls that limit the cost, and say which layer each belongs to.
Show answer
A daily run counter in the wrapper script limits how many attempts start, and a spend cap or budget alert on the provider account limits total cost even if the script misbehaves. Reducing the retry count, adding delays between retries, or using a scheduler timeout are also valid answers.