Retries are where Token budgets are most easily breached: a timeout retry can be billed again for partially generated output, and unlimited retries can multiply cost during upstream jitter. This article provides a deployable configuration method: first define single-call, daily, and monthly budget boundaries, then use a budget-gated call wrapper to limit retries, with exponential backoff, retryable error allowlists, and three-tier degradation, and finally use load-test cases to verify the budget is enforced.

Key takeaways
- 1. Define budgets in three layers: single-call Token limit, daily-window cumulative limit, and monthly total limit; post-bill accounting is not a constraint.
- 2. Retry only for timeout, 429, and 5xx errors; parameter errors and business validation failures must return immediately, otherwise invalid requests are repeatedly billed.
- 3. Recheck remaining budget before each attempt, not only at request entry; output already generated during a timeout may still be billed.
- 4. Use three degradation tiers: constrain output length, switch to a lighter model, return cache or explicit failure; each tier needs observable trigger conditions.
- 5. Before launch, prove the gate works with 4 load-test cases: normal, continuous timeout, burst traffic, and budget exhaustion; missing one case means validation is incomplete.
- Audience
- Backend engineers, platform engineers, and SREs integrating large model APIs in production
- Estimated time
- About 90 minutes to configure and load test (example estimate, depending on existing logging and monitoring systems)
- Prerequisites
- API keys, call log persistence, configurable retry middleware, and the ability to query usage by model
First define budget boundaries: single-call, daily, and monthly three-tier limits
When designing retries by Token budget, the first step is to write 'budget' as three executable numbers: single-call Token limit, daily-window cumulative limit, and monthly total limit. The three tiers prevent three classes of incidents: the single-call limit prevents one request from spiraling out of control, the daily limit prevents program defects or retry storms, and the monthly limit prevents slow cost drift. Looking at the bill only at month end is post-hoc accounting and is not a constraint. This article's scope is as of December 2, 2026; specific limit values should be set according to business volume, and model parameters and unit prices are based on AGTCloud Model Library for real-time display.
Tier | What it constrains | Example configuration (assumed values) | Over-limit action |
Per request | Input and output tokens for a single request | max_input_tokens=4000, max_output_tokens=800 | Truncate input and tighten output format |
Per day | Cumulative usage within a fixed window | Set at 1.5 times the historical peak; use a 5-minute sliding window for early warning | Trigger level-1 degradation and alerting |
Per month | Periodic total usage and call count | Derive from the budget; also limit monthly calls to 200,000 | Freeze non-critical tasks and perform manual review |
The three-level cap must be enforced on the same shared counter, not stored separately in each service instance. In multi-instance deployments, use atomic counters or a centralized quota service; otherwise, 10 instances may each think they still have quota, making the actual total 10 times the cap.
Why the per-request output cap must be set separately
The input segment can usually be controlled during request assembly, while the output segment is decided by the model. If max_output_tokens is not set, an unexpected repetitive generation may consume thousands of tokens, and the output segment usually has a higher unit price. Writing it as a hard parameter in every request is the configuration line with the highest cost-benefit ratio.
But the cap should not be as small as possible: setting it too low will truncate normal answers and instead trigger user retries, creating new amplification. It is recommended to first use real samples to estimate the distribution of output tokens, take a quantile that covers the vast majority of requests as the starting point, and then review the truncation rate every 2 weeks.
Why retries can break the budget: error type comparison
Not every failure is worth retrying. Dividing errors into two categories by 'whether retrying is meaningful' is the first gate for cost control. Retrying a parameter error 3 times only produces 3 invalid billings; retrying a timeout 3 times at least has a chance to get a result, but the generated portion is still billed.
Error type | Retry? | Budget impact | Handling action |
Timeout / connection interruption | Retryable | The generated portion may be billed; repeated requests are billed separately | Retry with backoff and recheck the budget each time |
429 rate limiting | Retryable | Without backoff, requests will continue to be rejected and billed repeatedly | Longer backoff with jitter; consider degradation |
5xx server error | Retryable | Controllable within the attempt cap | Degrade after at most 2 retries |
400 parameter error | Do not retry | Purely invalid billing | Return immediately and log |
Business validation failure | Do not retry | Purely invalid billing | Return immediately without consuming budget |
Content policy rejection | Do not retry | Purely invalid billing | Return a clear message |
Budget exhausted | Do not retry | Continuing calls will only expand overspend | Use degradation or return an explicit failure |
Why timeout retries can cause duplicate billing
Client timeout does not mean the server did no work. The request may have completed inference, with only the response timing out on the way back; at that point, usage for that call has already been generated. If the client sends again, the bill shows two charges. Therefore timeout retries must be paired with two things: strictly cap the number of attempts, and record the usage of each attempt separately; otherwise, during review it is impossible to distinguish which charge corresponds to a valid call.
Streaming output can mitigate but not eliminate this problem: streaming lets the client see progress earlier and stop in time, but tokens already produced are still counted. Treat it as a way to reduce losses, not as a guarantee of no billing.
Runnable example 1: call wrapper with a budget gate
Below is a Python wrapper that can be directly adapted. The key points are rechecking the budget before each attempt, using an error-type allowlist, and recording the usage of each attempt separately. The numbers in the example are demo configuration and do not represent the actual parameters of any platform.
RETRYABLE = {'timeout', 'rate_limit', 'server_error'}
def call_with_budget(client, messages, model, quota):
for attempt in range(1, quota.max_attempts + 1):
# 关键:每次尝试前重新读预算,而不是只在入口读一次
if not quota.reserve(estimate_input_tokens(messages)):
return budget_exhausted()
try:
resp = client.chat.completions.create(
model=model,
messages=messages,
max_tokens=quota.max_output_tokens,
timeout=quota.timeout_seconds,
)
except APIError as err:
usage_log.record(attempt=attempt, kind=err.kind, tokens=0)
if err.kind not in RETRYABLE or attempt == quota.max_attempts:
return fallback(messages, reason=err.kind)
sleep(backoff(attempt)) # 1s -> 2s -> 4s,带抖动
continue
u = resp.usage
quota.commit(u.prompt_tokens + u.completion_tokens)
usage_log.record(attempt=attempt, kind='ok',
input_tokens=u.prompt_tokens,
output_tokens=u.completion_tokens)
return resp
return fallback(messages, reason='budget')Three easily missed details are all included:reserve inside the loop, failed attempts must also be recorded, settle usage using the returned value rather than an estimate. The second point especially: many teams' usage logs only record successful calls, so retry cost is completely invisible in monitoring.
How to configure exponential backoff and jitter
The purpose of backoff is to avoid synchronized retry storms when upstream is jittery. Recommended configuration: 3 attempts, base delay 1 second, exponential growth, random jitter, and a longer base delay specifically for 429. The following is a configuration example corresponding to the wrapper above.
budget:
max_attempts: 3
timeout_seconds: 30
max_input_tokens: 4000
max_output_tokens: 800
daily_window: fixed_24h_business_tz
burst_window: 5m
monthly_call_limit: 200000
retry:
backoff: exponential
base_delay_seconds: 1 # 1s -> 2s -> 4s
jitter: full
retry_on: [timeout, 429, 5xx]
never_retry_on: [400, 422, content_policy]
fallback:
level_1: tighten_output # 收紧 max_output_tokens 与输出格式
level_2: downgrade_model # 切换到更轻的模型
level_3: cached_or_fail # 返回缓存或明确失败
mark_response: degraded=trueParameter | Example value | What happens if misconfigured | Verification method |
max_attempts | 3 | Too large → cost amplification; too small → availability decreases | Stress-test consecutive timeout cases |
base_delay_seconds | 1 | 0 → retry storm | Observe request distribution during 429 |
jitter | full | No jitter → synchronized retries across instances | Check whether retry timestamps cluster |
timeout_seconds | 30 | Too long → connections are occupied and duplicate billing risk is high | Compare timeout rate with average latency |
max_output_tokens | 800 | Too small → truncation triggers user retries | Monitor truncation rate |
Jitter is often omitted, but it is the most cost-effective item in multi-instance deployments. Without jitter, a single upstream failure can make all instances retry in the same millisecond, creating a second wave of impact, and the actual amplification can far exceed the configured 3 attempts.
How to design a three-level degradation strategy
When the budget is exhausted or retries fail, do not only have the action 'return an error'. Rank three levels by impact on user experience from small to large, and give each level clear trigger conditions and observable markers.
Level | Trigger condition | Action | User-perceivable change | Monitoring field |
Level 1 | Daily usage reaches 80% of the threshold | Tighten max_output_tokens and require structured short output | Shorter answers | degraded=1 |
Level 2 | Still over threshold after Level 1 or 2 consecutive retry failures | Switch to a lighter model | Quality may decrease | degraded=2, model |
Level 3 | Budget exhausted or fallback also unavailable | Return cached results or an explicit failure response | Explicitly prompt to retry later | degraded=3, reason |
Using an 80% threshold instead of 100% leaves headroom for the degradation actions themselves. If you wait until the budget is fully exhausted before switching, the last batch of requests fails outright, and monitoring curves show spikes.
Why degradation markers should be written into responses
If degraded responses look the same as normal responses, success-rate metrics stay artificially good and cost anomalies are completely masked. Including a degraded field in response metadata lets the frontend optionally show a prompt and lets monitoring aggregate degraded requests separately. This way, 'cost is contained but experience degrades' becomes visible instead of an ambiguous ledger.
How to implement usage accounting and monitoring
Budget gates depend on accurate usage data. A minimally useful log structure should include model, attempt number, error type, input and output tokens, and degradation level; failed attempts must also be logged, with tokens recorded as 0 and the error type retained.
usage_log = {
'ts': now_iso(),
'model': model,
'task': task_name,
'attempt': attempt,
'result': 'ok' or 'timeout' or '429' or '5xx',
'input_tokens': u.prompt_tokens if ok else 0,
'output_tokens': u.completion_tokens if ok else 0,
'degraded': degraded_level,
'request_id': request_id,
}
# 每日聚合:按 model / task / result 分组求和
# 重点看:失败尝试占比、单请求平均尝试次数、降级触发次数、峰均比Metrics | Calculation | Health signal | First check on anomalies |
Failed attempt ratio | Failed attempts / total attempts | Low and stable | Whether the error-type allowlist is missing entries |
Average attempts | Total attempts / requests | Close to 1 | Backoff and timeout settings |
Degradation trigger count | Count grouped by degraded | Appears only during peak periods | Whether the budget threshold is too low |
Input/output token ratio | Sum each separately, then divide | Matches the workload pattern | Whether output limits are ineffective |
Peak-to-average ratio | 5-minute peak / daily average | Consistent with history | Whether there is a retry storm |
Among them, 'average attempts' is the most intuitive: a value close to 1 indicates a healthy retry policy. A slow rise above 1.5 often means the upstream is becoming unstable, while billing usually has not yet shown anomalies, leaving a processing window.
Load testing to verify the budget actually takes effect
Writing configuration is not the same as it taking effect. Before launch, run at least 4 types of test cases and archive the results as a baseline for future tuning. The table below gives each case's construction and expected result; example numbers are used to illustrate magnitude.
Test case | How to construct | Expected result | Explanation when it fails |
Normal calls | Send 1000 valid requests consecutively | Attempts are all 1, no degradation | Budget-check logic triggers incorrectly |
Consecutive timeouts | Inject a timeout into every request | Attempts capped at 3, cumulative usage ≤ 3 times the per-request limit | reserve placed outside the loop or backoff ineffective |
Burst traffic | Inject 10 times the normal peak within 5 minutes | Triggers level-1 degradation, no overspend | Shared counter not effective |
Budget exhausted | Temporarily set the daily limit to a very small value | Return degraded or explicit failure, no further upstream calls | Degradation branch missing |
Especially the 'budget exhausted' case: many implementations only alert without blocking, and load testing reveals requests are still sent after the budget has reached zero. If this case fails, no matter how well the other three cases are done, the budget cannot be considered effective.
Pre-launch checklist
Confirm that per-request, per-day, and per-month limits all have corresponding configuration and over-limit actions, and share the same atomic counter.
Confirm the error-type allowlist: timeouts, 429, and 5xx are retryable; 400, business validation failures, and content-policy rejections are not retried.
Confirm that budget is re-reserved before every attempt, failed attempts are also written to usage logs, and usage is settled from returned values rather than estimates.
Confirm backoff includes jitter, timeout is set on the order of 30 seconds, and max_output_tokens is included in every request parameter.
Confirm all three degradation levels have response markers, and monitoring can aggregate separately by degraded level.
In developer docs check error codes and usage field naming to avoid mixing fields from different platforms.
Run the 4 load-test cases and archive results before gradual rollout; start with 10% traffic for 1 day, then expand gradually.
Do not reverse the checklist order: first get constraints and accounting right, then discuss degradation and gradual rollout. Degradation strategies without accurate usage data only trade experience for a cost number you cannot see clearly.
Common pitfalls and troubleshooting order
Symptom | Common cause | Troubleshooting order |
Bill is higher than expected but success rate is normal | Failed attempts not accounted for or retry count not capped | Check average attempts → check failure logs → check backoff configuration |
Calls still occur after budget reaches zero | Over-limit only alerts without blocking, or multiple instances count separately | Check degradation branch → check whether counters are shared |
Costs rise during 429 periods | Lack of jitter causes synchronized retry storms | Check retry time distribution → add jitter |
Truncation rate rises along with call volume | max_output_tokens set too small, causing user retries | Compare truncation-rate and request-count curves |
Monitoring still shows all success after degradation | Response lacks degraded marker | Add markers and aggregate by level |
When troubleshooting, first look at the 'average attempts' and 'failed attempt ratio' metrics; they reflect issues earlier than the bill and are easier to map to specific configuration items.
Implement and validate on AGTCloud
When implementing, first check in developer docs check authentication, error codes, and usage field naming, then read from AGTCloud model library read the target model's context length and output limit, replacing assumed values in the example configuration with numbers that match the business. Then in console send a sample request and confirm that the usage field matches the log structure in this article.
When evaluating lightweight models for degradation, rely on the real-time display in the model library as well; do not hard-code lists in code or articles. According to the Step-5 launch announcement published by AGTCloud on December 1, 2026, total output tokens decreased by about 38%, and the equivalent API cost decreased by 36%—such changes in inference efficiency themselves affect the benefits of degradation strategies and are worth reviewing regularly.
Finally, reiterate the division of responsibilities: this article provides constraint methods that do not become invalid with model iterations, while specific parameters, unit prices, and available models are maintained in the model library. Keeping the two separate prevents configurations from becoming outdated after the next model update.
Frequently asked questions
Because most teams check the budget only once at request entry, while retries create multiple independently billed calls. More subtle is the timeout scenario: the server may have generated partial output; after client timeout, retry, the previous attempt's usage is still billed. Therefore, before each attempt, re-read remaining budget and put retry count, backoff interval, and single-call output limit into explicit configuration.
Source
Chen Yizhou
API Engineering
AGTCloud technical column author for API development, focusing on large-model API access, interface compatibility, SDK integration, and application development. Content covers Python API calls, OpenAI-compatible interfaces, streaming output, error handling, concurrency optimization, and development practices, helping developers reduce model access and migration costs.