API Retry Duplicate Billing: Idempotency for LLM Request Timeouts

Blog / Developer tools

API Retry Duplicate Billing: Idempotency for LLM Request Timeouts

A retry can bill you twice, and that is often not a bug. LLM generation requests are not idempotent by nature: your client may time out while the server keeps going, finishes the whole answer, and records the charge. If you retry at that point, you pay a second time for the same question. So "API retry duplicate billing" breaks down into two questions: which failures leave usage on the server, and how does the client deduplicate on its own when the API has no official idempotency key?

This article makes no claims about any single vendor's billing rules. How timeouts, dropped streams, and client-side cancellations are billed is defined by each vendor's official documentation and your invoice line items. What follows is vendor-neutral and can be done in your own code.

Why am I charged even though the request timed out?

A generation request goes roughly through these stages: open a connection, send the request body, wait in the server queue, start inference, emit tokens one by one, finish and settle billing. A client "timeout" only means the client stopped waiting. The server may not know that.

Common cases:

  • A read timeout fires mid-generation. For example, the client sets a 60-second read timeout, but the response takes 90 seconds to write. By the time the client disconnects, the server may have processed all input tokens and generated most of the output.
  • An intermediate layer cuts the connection first. If the request passes through Nginx, a CDN, or a load balancer, the idle timeout of any one of them can sever the connection. The classic example is Cloudflare's 524, where the origin is still computing. See AI API returns 524 Gateway Timeout.
  • A streamed response breaks partway. For example, an SSE stream drops at token 800, and the server has already produced everything before it. See Troubleshooting dropped streaming responses.
  • The response was sent but never arrived. The server finished and billed, and the response packet was lost in transit. The client sees a timeout or a connection reset.

In all of these the client sees roughly the same thing, "no result," but the server-side state is completely different. A timeout exception does not tell you how far the other side got.

Which failures are safe to retry, and which risk duplicate billing?

Sort failures by whether the request could already have entered inference:

FailurePossible server stateDuplicate billing riskRecommendation
DNS failure, connection refusedRequest never arrivedBasically noneSafe to retry immediately
TLS handshake failure or timeoutRequest never arrivedBasically noneSafe to retry immediately
400, 401, 403, 404Request rejected, never entered inferenceLow, but retrying will not helpFix the request, do not retry
429 rate limitUsually blocked at the entry pointLowWait per retry-after, then retry
500, 502, 503, 529Uncertain; may have failed before or during inferenceDepends on the vendor's policyRetry with backoff, log the request_id for reconciliation
Read timeout, 504, 524May have completed or may still be generatingHighCheck for a result first, then decide whether to retry
Stream cut off midwayPartial output already producedHighSave what you received, then decide between continuing and starting over

For what each status code means, see the LLM API error code cheatsheet. For the differences between connection-level errors, see Connection refused vs. timed out vs. reset.

Also note that official SDKs usually retry automatically. If you add another retry layer in your application code, the two layers multiply, and one read timeout can balloon into several full generations. To find and change the SDK's default timeout and retry count, see Timeout and retry settings in the OpenAI and Anthropic SDKs.

Why can't you just copy payment-API idempotency keys?

Search for "idempotency key" and most results come from payments. The pattern: the client generates a unique key per operation and sends it in a header. The server executes the first time it sees the key and stores the result. Any later request with the same key gets the stored result back, with no second charge.

Applied to LLM APIs, there are three differences:

  1. Not every vendor supports it. Whether an endpoint accepts an idempotency key, how long the key stays valid, and whether it covers streaming requests must be checked in each vendor's official docs. Do not assume it works just because you sent the header.
  2. The result itself is non-deterministic. A payment ends in success or failure. A generation ends in a block of text, and the same input usually produces different output on two calls. Server-side dedup here means "bill once and return the same result," not "recomputing would give the same result."
  3. Billing is not the only side effect. In agent scenarios, model output triggers tool calls: writing files, sending messages, calling downstream APIs, submitting orders. Those side effects happen in your own systems, out of reach of the server's idempotency key.

So even when an endpoint supports idempotency keys, you still need client-side deduplication.

What can the client do without an official idempotency key?

The four layers below can be used alone or stacked. The further down you go, the closer to business logic and the more specific the problem it prevents.

Layer 1: Give every logical request a stable ID, and persist it first

Generate the ID before sending the request, persist it, and reuse the same ID on every retry instead of creating a new one each time.

import hashlib, json, uuid

def logical_request_id(task_id: str, step: int, payload: dict) -> str:
    # Same task, same step, same input -> same ID
    body = json.dumps(payload, sort_keys=True, ensure_ascii=False)
    digest = hashlib.sha256(body.encode()).hexdigest()[:16]
    return f"{task_id}:{step}:{digest}"

# Write to the database before sending, with status pending
rid = logical_request_id(task.id, step, payload)
db.upsert("llm_requests", id=rid, status="pending", attempts=0)

The ID has three uses: put it in a request header or metadata (if the endpoint supports that), use it as the local cache key, and reconcile it later against the server's request_id and your invoice line items. For how to check an invoice, see AI API bill doesn't match: token counting and how to verify.

Layer 2: Cache results and check before retrying

Once you have a complete result, store it in a cache or database under the logical request ID. The first step of your retry logic should not be sending a request. It should be checking whether this ID already has a finished result.

def call_with_dedup(rid, payload):
    row = db.get("llm_requests", rid)
    if row and row.status == "done":
        return row.result               # Result exists, use it directly
    if row and row.attempts >= 2:
        raise NeedsHumanReview(rid)     # Retry budget exceeded, hand off to a human
    db.incr("llm_requests", rid, "attempts")
    resp = client.create(**payload, timeout=REQUEST_TIMEOUT)
    db.update("llm_requests", rid, status="done",
              result=resp.text, upstream_id=resp.id,
              usage=resp.usage)
    return resp.text

This stops the most common duplicate: the process crashes after receiving the result but before handling it, and on restart the whole task runs again from the beginning. It cannot stop the case where the previous attempt timed out but the server actually finished. That money is already spent, and the cache has no result. You can only reduce that case with two measures:

  • Set timeouts wider than the model's real latency, and use streaming for long generations so data keeps flowing on the connection.
  • Give retries a budget, for example at most 2 extra attempts per logical request, after which you stop and alert instead of retrying forever. For backoff and budget implementation, see How to write LLM API retries: exponential backoff, jitter, and retry budgets.

Layer 3: Save the partial output of streaming requests

When a stream breaks, the tokens you already received are content you have paid for. Store them under the logical request ID first, then decide what to do next:

  • If what you received is enough (for example, a classification or short summary already contains the answer), use it and do not retry.
  • If the content is clearly incomplete and the task can be continued, put the partial output into the context and ask the model to continue. This usually costs fewer output tokens than regenerating from scratch.
  • If you must start over completely, retry within the budget from Layer 2.

Layer 4: Isolate the side effects of tool calls

This is the most dangerous part in agent scenarios. A typical path to duplicate execution:

  1. The model returns a tool call, for example "send an email to the user."
  2. The agent executes the tool, and the email goes out.
  3. The request that sends the tool result back to the model times out.
  4. The retry logic redoes the whole step, the model asks to send the email again, and two emails go out.

The extra tokens are minor. Duplicate side effects are usually much harder to clean up. The fix is a separate ledger for tool calls:

def run_tool(rid, call):
    key = f"{rid}:{call.name}:{stable_hash(call.arguments)}"
    done = db.get("tool_ledger", key)
    if done:
        return done.output              # Already executed, return the earlier result
    output = TOOLS[call.name](**call.arguments)
    db.insert("tool_ledger", key=key, output=output)
    return output

Supporting rules:

  • Split tools into read-only and side-effecting. Reading files and queries are safe to rerun. Writes, sends, payments, and deletes must go through the ledger.
  • For side-effecting tools, pass an idempotency key downstream. If the downstream API supports one (a payment API, for example), use the ledger key as its idempotency key. Then even if the ledger write fails, the downstream service can still block one duplicate.
  • Record "about to execute," then execute, then record "completed." If the process crashes mid-execution, on restart it sees an "about to execute but not completed" record and hands off to a human to confirm, rather than automatically executing again.
  • Retry at the granularity of one model call, not a whole step. For a step whose tools have already run, retry only the request that hands the tool results back to the model.

Pre-launch checklist

  • The application and the SDK keep only one layer of automatic retry, or you know the maximum count after the two layers multiply
  • Every logical request gets a stable ID before it is sent and is persisted; retries reuse the same ID
  • Before retrying, check locally whether a complete result already exists
  • Automatic retry only for connection-level errors, 429, and 5xx; for read timeouts and 524, check status first
  • Every logical request has a retry budget, and exceeding it raises an alert instead of retrying further
  • Read timeouts are set with real generation latency in mind, and long outputs use streaming
  • Partial output is saved when a stream breaks
  • All side-effecting tool calls go through the ledger and pass an idempotency key downstream
  • Logs record both the logical request ID and the server's request_id, to make invoice reconciliation easier
  • You have read the official docs for your endpoint: whether it supports idempotency keys, and how timed-out and cancelled requests are billed

Did I retry too much, or is the service really having problems?

If the call count on your invoice is clearly higher than your business request count, first check how many times the same logical request ID appears in your logs. If the duplicates cluster in a particular time window, compare that window against service status. cdnping's API status page probes each vendor's official API endpoint from the Cloudflare edge every 5 minutes and keeps 30 days of history. Is it down? combines official status pages, API probes, and user reports. If the service had a recorded incident in that window, the heavy retrying was probably caused by the outage, and you should check whether your circuit breaker and retry budget actually kicked in (for circuit breaker design, see Multi-provider failover for LLM APIs: circuit breakers and fallback chains). If the service was healthy, the problem most likely lies in your own timeout settings or network path. The probing method and its limits are described in Methodology.

cdnping only started collecting data on October 17, 2026, so the history is still short. It is suited to checking a specific incident, not to long-term statistics.

If you use an aggregation gateway, check whether it publishes success and failure counts based on real requests. For example, AGI Plan (a commercial partner of cdnping) publishes hourly success and failure counts per capability group at https://agiplan.dev/api/status/requests?month=YYYY-MM, with no login required. Only 5xx responses count as platform failures. cdnping's AGI Plan status page also mirrors this data. Data like this helps you tell whether a failure came from the platform or from your own requests, but it still cannot replace your own deduplication logic.

Related articles

Keep reading