Fix Latency, Cost, Deployment and Score Regressions
When an agent becomes slow, expensive, undeployable or suddenly worse, measure first and change one thing at a time.
Compare with a known good state. For latency and cost, break one trace into model calls, tools, queues and retries, then attack the largest part. For deployment failures, check configuration, identity, network and limits in order. For a score drop, rule out noise and grader changes, then revert components one at a time.
What you will learn: how to find the cause of slow runs, spend spikes, timeouts and retries, failed deployments and evaluation regressions.
Prerequisites: Agent Tracing and OpenTelemetry and Continuous Evaluation, Statistics and Scorecards.
The example runs in November 2026 with Python 3.13 and only the standard library. Its scores are invented and produced by a lookup, not by a model.
First questions
- What changed and when: release, prompt, model, tool, data, configuration, traffic or provider?
- Who is affected: everyone, one task type, one region or one customer?
- How bad is it, measured against a normal period?
- Is it still happening, and is there harm that needs containment now?
- Can you roll back safely while investigating?
If users are being harmed or spend is climbing fast, contain first: roll back, lower limits or switch to a manual path (Incident Runbook and Failure Mode Catalog).
High latency
Total time is the sum of waiting in queues, model calls, tool calls, retries and your own processing, minus whatever overlaps. A trace shows which one dominates. Look at percentiles, because an average can look fine while one user in twenty waits far too long.
| Finding in the trace | Likely fixes |
|---|---|
| Many sequential model calls | Remove steps; combine decisions; use code for fixed logic |
| Long generation | Shorter outputs; stream; a faster model where tests allow |
| Large input on each call | Trim context; use prompt caching where supported |
| Independent tools run in turn | Run them in parallel |
| One slow dependency | Timeout, cache, precompute or a better query |
| Waiting before work starts | More workers, concurrency limits, warm instances |
| Hidden retries | Fix the underlying error; retry in one layer |
A worked latency breakdown
Queue wait 1 s; first model call 3 s; three lookups run one after another, 4 s each; final model call 5 s; own processing under 1 s.
The lookups account for about 12 seconds. If they are independent, running them together would bring that part close to 4 seconds and the total to around 13, without touching the model. Check the independence first: if the second lookup needs the first one's result, parallel calls are not possible, and a combined query or a precomputed view may help instead. Measure again after the change, since a faster step often exposes the next limit.
Waiting time that users feel
Time to the first useful output matters as well as total time. Streaming, progress messages and the option to continue in the background can improve the experience without changing total duration. They are not a substitute for fixing a slow dependency, and progress messages must reflect real state (Progress, Approval, Undo and Handoff UX).
Unexpected cost
| Pattern | Check | Response |
|---|---|---|
| Steps per task rose | Loops and failing tools | Fix the cause and cap steps |
| Input tokens per call rose | History, retrieval size, tool output | Summarize, filter and limit results |
| Cache hit rate fell | Changing text near the start of prompts | Keep stable content first, where caching works that way |
| Costlier model used | Routing rules and fallbacks | Correct routing and alert on model mix |
| Traffic rose | Legitimate growth, retries or abuse | Quotas per user and rate limits |
| Spend without usage in logs | Other users of the key; background jobs | Separate keys, revoke suspicious ones, investigate |
Track cost per verified success. A cheaper step that doubles failures or retries is not a saving (Agent Cost Model and Token Economics).
Find where the money goes
Multiply it out for one typical task: for each model call, input tokens times the input price plus output tokens times the output price, including any cache pricing; add tool fees; multiply by tasks per day; then divide by verified successes. Use current prices from your provider. Because agents resend context on every step, input often grows faster than the number of steps: ten steps that each add to the history can cost far more than twice as much as five. That makes history size and tool output size good first suspects.
Set a spend limit per task as well as per day. A daily limit stops a disaster eventually; a per-task limit stops one bad run quickly and tells you which task caused it (Reducing Tokens, Tool Calls and Spend).
Timeouts and retries
- Give the whole task a deadline and pass the remaining time to each call.
- Retry only transient errors, with exponential backoff, jitter and a small maximum.
- Respect retry-after guidance from rate-limited services.
- Treat a timed-out write as unknown, not failed: query the result or reuse an idempotency key.
- Use streaming or background tasks for work longer than gateway limits allow.
- Check timeouts at every hop: client, gateway, load balancer, function, tool and database.
Three layers that each try three times can turn one request into 27 attempts at the deepest dependency. Choose one layer to retry and count total attempts.
Rate limits and quota
Identify which limit was hit: requests, tokens, concurrent tasks or daily spend, and whose it is: yours, a gateway's or a provider's. Smooth bursts with queues, reserve capacity for important work, reduce tokens and ask for higher limits with measured evidence. Switching to a fallback model helps only if it has been tested and has its own capacity.
Agent deployment failures
| Symptom | Check |
|---|---|
| Build fails | Pinned dependencies, base image, architecture |
| Starts then exits | Startup logs, missing settings, memory limit |
| Health check fails | Port, path, startup time and what the check calls |
| Authentication errors | Which identity runs the service; expired or missing secrets |
| Permission denied | Role grants in this environment; never widen blindly |
| Cannot reach a service | DNS, egress rules, private endpoints, proxy and certificates |
| Model not found | Identifier, region, account access and retirement notices |
| Works for one request, fails under load | Concurrency, connection pools, quota, shared state |
| Old tasks fail after release | State and tool schema compatibility |
Compare configuration between the working and failing environments, and read the first error rather than the last, since later messages are often consequences. Keep a smoke test that exercises model, tool and state access immediately after deployment, without causing real effects (CI/CD, Infrastructure as Code and Safe Releases).
Rollback that actually works
| Item to restore | Question before you act |
|---|---|
| Code and image | Is the previous build still available? |
| Prompts and configuration | Are they versioned together with the code? |
| Model | Is the earlier version still offered? |
| Tool schemas | Can the old agent call the current tools? |
| Stored state | Can the old version read records written by the new one? |
| Index and data | Is a compatible snapshot retained? |
| Effects already made | What must be corrected separately? |
Rollback restores behavior going forward. It does not undo messages sent or records changed, so list those and handle them as part of the repair (Promotion, Feature Flags, Rollback and Drift).
Evaluation score regression
Before hunting a cause, confirm that the drop is real.
- Noise: compare counts and intervals; rerun both versions together.
- Grader: regrade stored old and new outputs with one grader version.
- Dataset: check the version hash and any changed cases.
- Environment: look for timeouts, leftover state and rate limits.
- Outside change: model service, index, tool API or source data.
Then list every difference between the good and current versions and test them.
"""Find which change caused a score drop by reverting one change at a time (simulation)."""
GOOD = {"model": "model-a", "prompt": "p7", "tools": "t3", "index": "i12"}
BAD = {"model": "model-a", "prompt": "p8", "tools": "t4", "index": "i13"}
def evaluate(config):
"""Stands in for running the evaluation suite. Returns passes out of 200."""
score = 182
if config["prompt"] == "p8":
score += 2
if config["index"] == "i13":
score -= 3
if config["tools"] == "t4":
score -= 31
return score
def main():
good, bad = evaluate(GOOD), evaluate(BAD)
print(f"last good release: {good}/200 current: {bad}/200")
changed = [k for k in GOOD if GOOD[k] != BAD[k]]
print("changed:", ", ".join(changed))
print()
effects = {}
for part in changed:
trial = {**BAD, part: GOOD[part]}
effects[part] = evaluate(trial) - bad
print(f"revert {part:<7} {BAD[part]} -> {GOOD[part]}: "
f"{evaluate(trial)}/200 ({effects[part]:+d})")
culprit = max(effects, key=effects.get)
print()
print(f"largest recovery: revert {culprit}")
fixed = {**BAD, culprit: GOOD[culprit]}
print(f"confirm: {evaluate(fixed)}/200 with only {culprit} reverted")
if __name__ == "__main__":
main()
Output:
last good release: 182/200 current: 150/200
changed: prompt, tools, index
revert prompt p8 -> p7: 148/200 (-2)
revert tools t4 -> t3: 181/200 (+31)
revert index i13 -> i12: 153/200 (+3)
largest recovery: revert tools
confirm: 181/200 with only tools reverted
Reverting only the tool change recovers almost all the lost cases; the other two reversions move a few cases either way, which may be noise. The confirmation run supports the conclusion. One-at-a-time reversion can miss causes that act only in combination, so if no single change explains the drop, try pairs or step through releases in order. With real models, repeat trials before reading small differences.
Read the failures, not only the total
Group newly failing cases by task type, tool and error. A drop concentrated in one slice points to a specific part. Compare a failing trace with a passing trace of the same case and find the first step where they differ. A small overall change can hide a serious loss in a rare category (Task, Tool and Planning Metrics).
Change that you did not make
| Source | Protection |
|---|---|
| Model alias moves to a new version | Pin versions where offered; test before adopting |
| Model or feature retired | Watch deprecation notices and keep a tested replacement |
| Dependency update | Lock files and reviewed upgrades |
| Tool or API response changes | Contract tests and schema alerts |
| Data refresh | Index versions and retrieval tests |
| Different user behavior | Fixed canary set alongside production sampling |
Report the problem so others can help
Whether you escalate to a colleague or a provider, include the first and latest failure times with time zone, request and run identifiers, versions, the exact error, how often it happens, what changed, what you already tried and a minimal example with sensitive data removed. A precise report shortens the exchange and avoids repeating checks. Never paste keys, tokens or customer records into a ticket or a public forum.
Close the problem properly
Record the symptom, evidence, cause, fix and the check that will catch it next time. Remove temporary limits and debug logging that you added, since verbose logs can hold sensitive data. If the cause was a missing gate or alert, add it and give it an owner.
Alerts that would have caught it
| Problem | Early signal |
|---|---|
| Slowdown | 95th percentile time by task type; queue age |
| Spend spike | Spend rate against forecast; tokens and steps per task |
| Retry storm | Attempts per request across layers |
| Bad release | Error and success rates compared by version |
| Quality loss | Scheduled canary set and sampled grades |
| Expiring credentials | Days until expiry |
A worked diagnosis
Report: the monthly forecast doubles and users complain of delays after a release described as a wording change.
Compare: steps per task are unchanged, but input tokens per call are far higher and the cache hit rate has collapsed.
Cause: the edit placed the current time at the very top of the system prompt, so the start of each request was now different every time.
Fix: move changing values after the stable content, then confirm cache use, latency and cost on live-like traffic.
Prevention: include tokens, cache behavior, latency and cost per success in the release gate, even for small text changes.
The lesson is that a change is small only if the measurements say so. Prompt text affects behavior, length and caching, so treat it as code with the same review and tests (Prompt Testing, Versioning and Optimization).
Common mistakes
| Mistake | Better approach |
|---|---|
| Changing several things at once | One change, one measurement |
| Tuning the average only | Watch percentiles and slices |
| Raising every timeout | Find the slow part and set a task deadline |
| Granting broad access to fix a permission error | Add the specific permission after review |
| Calling two failed cases a regression | Check variation and counts |
| Editing the evaluation until the score returns | Fix the cause; change graders only for proven defects |
Diagnosis checklist
- A known good version and period are identified.
- Harm and spend are contained before deep analysis.
- One slow or costly trace is broken into its parts.
- Retries are counted across all layers.
- Deployment settings, identity, network and limits are compared.
- Noise, grader and dataset changes are ruled out.
- Suspected causes are reverted one at a time and confirmed.
- A test or alert now covers the failure.
Frequently asked questions
What is the quickest way to cut latency?
Measure one slow trace first; removing an unnecessary model call or running independent tools together is often more effective than changing models.
Why did cost rise with the same traffic?
Look at tokens and steps per task, cache behavior, retries and the mix of models used.
Should I roll back before finding the cause?
Yes when users are affected and rollback is safe for running tasks and stored state.
What if the score drop cannot be reproduced?
Repeat enough trials, check the environment and outside services, and keep the traces and versions for the next occurrence.
References and further reading
- Google SRE Book: effective troubleshooting: a method for diagnosis.
- Google SRE Book: addressing cascading failures: overload and retries.
- Amazon Builders' Library: timeouts, retries and backoff with jitter: retry design.
- OpenAI deprecations and Claude model deprecations: retirement notices.
Next steps
Incident Runbook and Failure Mode Catalog
Respond when diagnosis cannot wait.
Latency, Load Testing and Capacity Planning
Plan speed and capacity.
Model Routing, Fallbacks and Gateways
Control cost with tested routing.