Skip to content

Token burn, tool latency, failed attempts and accepted-workflow economics

14 min reading

Account for token burn, tool latency, retries and cost per accepted workflow.

Page details

GenAI · Lesson 43 of 45 · 6 / 6.2

Sources · 14 min reading · 30 min with practice

Published · Last edited:

More
20px

Progress is saved in this browser when storage is available.

View guided paths and progress

Know first: Trace recursive workflows with OpenTelemetry; LangSmith as a concrete comparison. Optional help: GenAI foundations.

Optional background references

Hypothetical scenario. Northwind’s traces explain where attempts spend time. Maya sees a lower token bill, but more workflows finish without an accepted result. Dev proposes reporting cost per request; Priya asks whether that denominator hides the retries and failures needed to obtain useful outcomes.

Maya: “Are we spending less to complete the task, or just less on each attempt?”

Dev: “We can connect model and tool charges to the same logical workflow.”

Priya: “Keep failed work in the ledger and state exactly which outcomes the denominator counts.”

You will follow the supplied illustrative rates through token, tool and retry accounting, then distinguish cost per attempted workflow from cost per accepted workflow. Preserve deadlines and uncertain-action outcomes while comparing economics with latency and correctness.

What did the workload spend to obtain an accepted result?

Hypothetical scenario. Choose a rate of $0.01 per 1,000 input tokens and $0.02 per 1,000 output tokens solely for this exercise. These are invented rates, not vendor prices. Across all attempts, a workload consumes 20,000 input and 5,000 output tokens: 20 × $0.01 + 5 × $0.02 = $0.30. Add ten tool attempts at a chosen $0.01 each: total cost is $0.30 + $0.10 = $0.40.

If eight of ten workflows meet the complete acceptance rule, cost per accepted workflow is $0.40/8 = $0.05. Dividing by all ten would give $0.04 per attempted workflow, a different measure. Failed attempts remain in the numerator. Token burn, tool invocation latency and retry counts belong to the same run ledger, but units must remain visible rather than added as if milliseconds were dollars.

Use the API deadline and uncertainty mechanisms below to explain how a run spends its budget. A cheap request that times out after an unobserved side effect can create reconciliation work beyond its token bill. Evaluate total accepted-task economics alongside latency and correctness, not as permission to weaken an action boundary.

Hypothetical scenario. A provider times out during the sale and Sam must decide whether another attempt fits the deadline.

In short. Carry one deadline through every attempt. Separate unknown outcomes from confirmed failures.

A lost response leaves an uncertain outcome

Hypothetical scenario. A document assistant sends a summarization request to a remote model service. The user waits, the connection closes, and the application has no complete result. The application knows what it received; it does not necessarily know whether the service accepted the request, finished generating, or recorded usage before the connection failed.

Calling an API moves part of the work across a service boundary. The application still owns the user's deadline, permissions, output acceptance, and explanation of failure. “Retry on error” is not a complete design because an error can describe several different states.

This chapter teaches how to define that boundary without depending on a particular vendor's current model names, limits, or prices. You will separate a logical user request from transport attempts, derive retry and token budgets, and decide what a streamed response actually proves.

Settle costs against useful completed tasks

Hypothetical scenario. Choose ten task intentions consuming 200 toy cost units across all attempts, with eight accepted completions. Cost per accepted completion is 200/8 = 25 units, while cost per intention is 200/10 = 20. Neither quantity is a provider price or production measurement.

Settle costs against useful completed tasks
ArtifactConcrete evidenceDecision boundary
Task intentionstable identity and acceptance ruleDenominator
Attempt usagemodel/tool, known or uncertain unitsFull work
Settlementreserved, consumed, unresolvedBound exposure
Include failed and retried work: Task intentions → All attempt usage.Include failed and retried work: Task intentions → All attempt usage. Task intentions to All attempt usage: include failed and retried work; All attempt usage to Accepted completions: divide by useful accepted outcomes.Task intentionsAll attempt usageAccepted completionsinclude failed and retried workdivide by useful accepted outcomes
Include failed and retried work: Task intentions → All attempt usage. Enlarge the diagram to inspect its labels; the surrounding records and explanation give the text alternative.

Keep input/output usage, tool work, failed attempts, fallback and unresolved usage in the ledger. A timeout does not imply zero provider consumption. Reserve bounded exposure before dispatch and settle from evidence or the declared conservative accounting rule. A cheaper model call can increase whole-task cost if it creates more corrections or lower acceptance. Compare equivalent task populations and consequences.

A client library cannot choose the product contract

A client library can serialize requests, manage connections, and expose response events. It cannot decide whether a partial summary is useful, whether a second attempt is affordable, or whether sending a document to another provider is permitted. Those are application decisions.

The same JSON shape also does not make two endpoints interchangeable. They may differ in input interpretation, supported output constraints, completion signals, refusal handling, or cancellation semantics. An adapter can translate representations; it cannot establish equivalent behavior without evaluation.

Start with the task: what is a complete acceptable result, what must remain private, and what happens when the service cannot supply it? Then inspect the chosen endpoint's documented request and response contract. Keep actual service limits and data-handling terms in a separately verified configuration rather than borrowing them from an unrelated example.

Trace one logical request across attempts

Give the application a stable identity for the user's task and separate identities for each network attempt. Preserve the model/configuration revision, the permitted data scope, the remaining deadline, and the final accepted result. Request identifiers support correlation; by themselves they do not prevent duplicate remote execution.

A logical request can contain several bounded attempts The application task carries identity, permissions, and a deadline. It sends an attempt to a service and classifies complete, rejected, or uncertain outcomes. Only a policy that checks retry safety, remaining time, and quota can create another attempt. Application acceptance is separate from transport receipt. Task identityscope + deadlineAttempt identitysend requestRemote serviceexecutionClassify outcomeaccept or stopRetry policytime + safety + quota

Classify observations precisely: an explicit rejection, a complete response awaiting application checks, an interrupted stream, or a connection failure with uncertain remote outcome. Define which conditions can be retried and when the caller should instead receive a clear failure or a recoverable task status.

HTTP Semantics, section 9.2.2, distinguishes idempotent methods and cautions against automatically retrying non-idempotent requests without knowledge that repetition is safe. HTTP method semantics do not establish a model endpoint's deduplication, charging, or recovery contract. Verify those separately; do not assume that including a request identifier creates idempotency.

Keep credentials and routing decisions behind the appropriate application boundary. Authenticate the caller, authorize the data and operation, and avoid exposing a shared privileged service credential to an untrusted client. Transport protection does not decide which document a user may submit.

Derive the cost of another attempt

Hypothetical scenario. An application's chosen admission policy allows 120 attempts per minute and 60,000 input tokens per minute. Each admitted attempt contains exactly 1,000 input tokens. These are illustrative policy values, not a vendor quota.

The attempt-count bound allows 120 attempts per minute. The input-token bound allows 60,000/1,000 = 60 attempts per minute. Ignoring other restrictions, the tighter bound is 60. An output-token limit, concurrency limit, or different input sizes would add constraints; this arithmetic does not establish that the service can sustain that rate.

In a separate hypothetical batch, 100 logical requests each make an initial attempt and 20 make exactly one retry. Total attempts are 100 + 20 = 120, or 120/100 = 1.2 attempts per logical request. If every attempt resends all 1,000 input tokens, submitted input volume is 120 × 1,000 = 120,000 tokens rather than 100,000. That is 20,000 extra submitted tokens, a 20% increase. This is not a billing calculation; charging and caching rules require the actual service contract.

Now consider one request with a 3,000 ms deadline. Its first attempt consumes 1,700 ms, planned backoff is 300 ms, and the application reserves 200 ms for response checks and delivery. Remaining allowance for a second attempt is 3,000 − 1,700 − 300 − 200 = 800 ms. A proposed 900 ms retry plan exceeds that allowance by 100 ms.

Do not restart the full deadline for each attempt. The original user is still waiting. A retry that cannot finish usefully within the remaining budget may add load without improving the outcome. These numbers are planning assumptions, not measured latency or sums of latency percentiles.

In the wild: Calling Model APIs: Timeouts, Retries, and Budgets

HTTP Semantics, section 9.2.2: HTTP distinguishes idempotent methods and constrains automatic repetition of non-idempotent requests.

Streaming separates progress from completion

Receiving a first chunk can improve perceived responsiveness, but it is not the same as receiving a complete usable answer. The application needs distinct states for waiting, displaying provisional content, completed output, interrupted output, and rejected output. Match those states to the endpoint's actual protocol.

Receiving successful status headers does not prove that the full response body and the application's required completion condition arrived. A connection can fail later. The HTTP framing discussion in RFC 9110, section 6.1, distinguishes complete and incomplete messages; the model service's terminal-event meaning is an additional contract.

Do not append a second attempt to the first attempt's partial text as though they were one response. The continuation may repeat, contradict, or reinterpret what the reader saw. A deliberate resume protocol can be useful when supported, but requires explicit state and semantics. Otherwise, clearly replace or mark the interrupted output.

Cancellation also crosses a boundary. The application can stop presenting a task or close its side of a connection without proving that remote execution stopped immediately. Document what cancellation actually does, what result status can be recovered, and how usage is reported. Do not promise free cancellation or immediate resource release without that evidence.

Several retry layers can amplify one failure

Hypothetical scenario. A frontend, application gateway, and service client each allow an original attempt plus one retry. If every parent attempt triggers the next layer's full retry allowance, one user action can produce 2 × 2 × 2 = 8 attempts at the deepest service boundary.

This is a worst-case count under the stated nesting policy, not an observed incident or a claim about any library's defaults. It shows why retry ownership and budgets must be visible across layers. A timeout configured in one client does not describe the whole user request.

AWS documents timeouts, retries and backoff with jitter. Choose a bounded retry owner, propagate the original deadline and measure attempts separately from logical requests. Backoff spreads attempts; it does not create capacity or make a repeated operation safe.

Four shortcuts that hide a changed contract

“A timeout proves the server did nothing.” It proves the caller did not receive the required result in time. Remote execution may be uncertain.

“A request ID makes retries exactly once.” Correlation and deduplication are different functions. The service must implement a documented repetition policy.

“Fallback is just another URL.” Check allowed data destinations, task quality, output constraints, and the remaining deadline. An endpoint switch changes more than routing.

“The first token means the task succeeded.” Completion and application acceptance remain unproven while the response is provisional.

Choose a boundary you can operate

A remote model service can be useful when it meets the task's behavior, data-handling, capacity, and operating requirements. It can move some runtime operations to a provider while leaving application integration and evaluation with the caller.

A local deployment may suit a different constraint, but it inherits its own memory, scheduling, updates, and recovery work. Compare both using the same task cases and complete request path. A price per token alone does not establish cost per useful accepted result.

Begin with one explicit request contract and a small failure matrix: rejection, delayed response, interrupted stream, invalid output, and uncertain completion. Add retries or fallback only when their behavior is defined and tested. A clear failure can be preferable to returning an unreviewed alternate result as though nothing changed.

Limits of Calling Model APIs: Timeouts, Retries, and Budgets

A deadline bounds caller waiting rather than proving the provider stopped. Retry and cancellation semantics must be checked for the actual interface. Preserve logical operation identity and distinguish a confirmed rejection from an unresolved remote outcome.

Test the task intention boundary

A provider timeout has no usage record yet. May the gateway refund its full reservation?

Reveal the design reasoning

Only under a declared policy that still bounds total exposure. Otherwise retain pending or conservative usage and reconcile the original attempt. Missing evidence is not zero consumption.

Decision: Compare accepted-workflow economics while retaining uncertainty and all attempt work.

Check yourself: reason about the uncertain attempt

A connection fails after the service may have accepted a request. Does retrying with the same correlation ID prove that only one execution will occur?

No. The ID helps identify related events, but deduplication requires a documented service behavior and appropriate request semantics. Treat the remote outcome as uncertain and follow the defined retry or recovery policy.

An application permits 80 attempts per minute and 24,000 input tokens per minute. Each attempt sends 600 input tokens. What bound applies before other limits?

The input bound allows 24,000/600 = 40 attempts per minute, less than the attempt bound of 80. Retries consume the same chosen attempt/token policy unless the actual contract says otherwise. This does not predict measured service throughput.

A streamed answer displayed two paragraphs before interruption. Can a fallback response be appended without marking the boundary?

Not safely as a general rule. They are distinct attempts with potentially different content and contracts. Preserve the interruption state and clearly replace or distinguish the new result, unless a verified resume protocol defines how continuity works.

Northwind decision log

Carry one deadline through every attempt.
Separate unknown outcomes from confirmed failures.
Cap retries and record the final state.

Go deeper into remote outcomes

Check the mechanism in this lesson

Why do failed workflows remain in the cost-per-accepted-workflow numerator?

Compare the explanation

Their attempts consumed resources. Dividing the full $0.40 by eight accepted outcomes yields $0.05. Excluding failed-attempt cost would understate what the workload actually spent to obtain those accepted outcomes.

Carry the decision forward

Northwind can compare accepted-task economics without hiding failed work. Page 44 asks which versions, source records, controls and review decisions must remain connected so that a release decision can be reconstructed.