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.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

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.

Versions used

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.

Beginner Measure before changing

First questions

  1. What changed and when: release, prompt, model, tool, data, configuration, traffic or provider?
  2. Who is affected: everyone, one task type, one region or one customer?
  3. How bad is it, measured against a normal period?
  4. Is it still happening, and is there harm that needs containment now?
  5. 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 traceLikely fixes
Many sequential model callsRemove steps; combine decisions; use code for fixed logic
Long generationShorter outputs; stream; a faster model where tests allow
Large input on each callTrim context; use prompt caching where supported
Independent tools run in turnRun them in parallel
One slow dependencyTimeout, cache, precompute or a better query
Waiting before work startsMore workers, concurrency limits, warm instances
Hidden retriesFix the underlying error; retry in one layer

A worked latency breakdown

Illustrative trace of a 21-second answer

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

PatternCheckResponse
Steps per task roseLoops and failing toolsFix the cause and cap steps
Input tokens per call roseHistory, retrieval size, tool outputSummarize, filter and limit results
Cache hit rate fellChanging text near the start of promptsKeep stable content first, where caching works that way
Costlier model usedRouting rules and fallbacksCorrect routing and alert on model mix
Traffic roseLegitimate growth, retries or abuseQuotas per user and rate limits
Spend without usage in logsOther users of the key; background jobsSeparate 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).

Intermediate Reliability and releases

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.
Retry storms

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

SymptomCheck
Build failsPinned dependencies, base image, architecture
Starts then exitsStartup logs, missing settings, memory limit
Health check failsPort, path, startup time and what the check calls
Authentication errorsWhich identity runs the service; expired or missing secrets
Permission deniedRole grants in this environment; never widen blindly
Cannot reach a serviceDNS, egress rules, private endpoints, proxy and certificates
Model not foundIdentifier, region, account access and retirement notices
Works for one request, fails under loadConcurrency, connection pools, quota, shared state
Old tasks fail after releaseState 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 restoreQuestion before you act
Code and imageIs the previous build still available?
Prompts and configurationAre they versioned together with the code?
ModelIs the earlier version still offered?
Tool schemasCan the old agent call the current tools?
Stored stateCan the old version read records written by the new one?
Index and dataIs a compatible snapshot retained?
Effects already madeWhat 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).

Expert Regressions

Evaluation score regression

Before hunting a cause, confirm that the drop is real.

  1. Noise: compare counts and intervals; rerun both versions together.
  2. Grader: regrade stored old and new outputs with one grader version.
  3. Dataset: check the version hash and any changed cases.
  4. Environment: look for timeouts, leftover state and rate limits.
  5. 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

SourceProtection
Model alias moves to a new versionPin versions where offered; test before adopting
Model or feature retiredWatch deprecation notices and keep a tested replacement
Dependency updateLock files and reviewed upgrades
Tool or API response changesContract tests and schema alerts
Data refreshIndex versions and retrieval tests
Different user behaviorFixed 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

ProblemEarly signal
Slowdown95th percentile time by task type; queue age
Spend spikeSpend rate against forecast; tokens and steps per task
Retry stormAttempts per request across layers
Bad releaseError and success rates compared by version
Quality lossScheduled canary set and sampled grades
Expiring credentialsDays until expiry

A worked diagnosis

Illustrative case: slow and costly after a harmless edit

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

MistakeBetter approach
Changing several things at onceOne change, one measurement
Tuning the average onlyWatch percentiles and slices
Raising every timeoutFind the slow part and set a task deadline
Granting broad access to fix a permission errorAdd the specific permission after review
Calling two failed cases a regressionCheck variation and counts
Editing the evaluation until the score returnsFix 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

Next steps