Skip to content

Idempotency of LLM API Requests: Keys, Deduplication, and Retries

Cover: Idempotency of LLM API Requests: Keys, Deduplication, and Retries Idempotency of LLM API requests prevents redundant generation and double token charges during retries, timeouts, and parallel requests from a single user.

Problem: Retry Generates a Second Call

LLM API is non-idempotent: every call generates a new response and charges tokens. During a network timeout, the client does not know whether the request was processed by the provider. A standard retry leads to two scenarios:

Scenario What happened on the provider side Consequence for the client
Timeout before processing Request did not reach Retry is safe
Timeout after processing Response was generated but not delivered Retry = double charge
Parallel retries Both requests were processed Duplicates in the DB, state desynchronization

The problem is exacerbated with streaming: the connection may break during generation, and the client does not have a complete response, although tokens have already been charged.

Idempotency Key

An idempotency key is a unique identifier for a logical operation that is passed in the request header. The provider or an intermediary layer stores the mapping «key → result» and upon a retry returns the saved response without a new model call.

import uuid
import hashlib
import json

def make_idempotency_key(user_id: str, prompt: str, params: dict) -> str:
    payload = json.dumps({
        "user": user_id,
        "prompt": prompt,
        "params": params,
    }, sort_keys=True, ensure_ascii=False)
    return hashlib.sha256(payload.encode("utf-8")).hexdigest()

key = make_idempotency_key(
    user_id="u_1024",
    prompt="Generate a brief summary of the document",
    params={"model": "default", "temperature": 0.2},
)

Requirements for the key:

  • Determinism: the same input data produces the same key;
  • Uniqueness within the storage window (usually 24 hours);
  • No personal data in plain text — the key is hashed.

See Idempotent and Hash.

Processing Scheme

flowchart TD
    A[Client forms the request] --> B[Calculation of the idempotency key]
    B --> C{Key in storage?}
    C -- Yes, status completed --> D[Return saved response]
    C -- Yes, status in_progress --> E[Wait or 409 Conflict]
    C -- No --> F[Record key with status in_progress]
    F --> G[Call LLM API]
    G --> H{Success?}
    H -- Yes --> I[Save response, status completed]
    H -- No --> J[Status failed, retry allowed]
    I --> K[Response to client]
    J --> K

Key storage is a table in the DB or Redis with TTL. Minimum fields: key, status, response_body, created_at, expires_at.

Deduplication of Parallel Requests

If two requests with the same key arrive simultaneously, the second should not initiate a new model call. Two approaches are applied:

  1. Locking (lock). The first request acquires a lock on the key, the second waits for completion or receives 409 Conflict with a suggestion to retry later.
  2. Single-flight promise. Inside the process, requests with the same key are combined into one call, the result is distributed to all waiting requests.
import asyncio

_inflight: dict[str, asyncio.Future] = {}

async def call_with_singleflight(key: str, coro_factory):
    if key in _inflight:
        return await _inflight[key]
    fut = asyncio.ensure_future(coro_factory())
    _inflight[key] = fut
    try:
        return await fut
    finally:
        _inflight.pop(key, None)

Single-flight is efficient during bursts of identical requests (e.g., mass regeneration of one document). For a distributed system, an external lock is required — see Concurrency.

Interaction with Retries and Timeouts

Rules for idempotency coordination with retry mechanisms:

Situation Action
HTTP 429 or 5xx before generation Retry with the same key
Timeout after sending Retry with the same key, not with a new one
Stream break Retry with the same key if the provider supports resumption
Response validation error New key (logical operation has changed)

Key rule: the key does not change for any retry of the same logical operation. Changing the key means a new operation and new token charge. See also llm-api-timeout-retry and llm-api-error-handling.

Provider Limitations

Not all LLM APIs support the idempotency header natively. Implementation options:

  • Native header. The provider accepts the key and guarantees deduplication. Verified in the documentation of the specific API.
  • Proxy layer. A custom service before the LLM API stores keys and responses. Full control, but adds delay and a point of failure.
  • Client-side deduplication. The key is stored in the application DB, retries are blocked until the first operation completes. Does not protect against retries at the network level between client and provider.

For multi-tenant systems, the key must include the tenant identifier, otherwise response leakage between users is possible — see llm-api-multitenant-isolation.

Storage and Cleanup

The storage window for keys is defined by the maximum lifetime of retries and the period during which the client can repeat the operation. Typical values range from 1 to 24 hours.

CREATE TABLE idempotency_keys (
    key            TEXT PRIMARY KEY,
    tenant_id      TEXT NOT NULL,
    status         TEXT NOT NULL,
    response_body  JSONB,
    created_at     TIMESTAMPTZ NOT NULL DEFAULT now(),
    expires_at     TIMESTAMPTZ NOT NULL
);

CREATE INDEX idx_idem_expires ON idempotency_keys (expires_at);

Cleanup is performed on schedule via cron or TTL in Redis. Storing the full response body increases storage volume; for large responses, a reference to object storage is saved.

Metrics

Metric Purpose
Fraction of retries with existing key Efficiency of deduplication
Number of 409 conflicts Locking load
Saved tokens Difference between calls and unique operations
Wait delay with single-flight Impact on user experience

Metrics are included in the overall observability framework — see llm-observability-stack.

Implementation Checklist

  • The key is deterministically calculated from the input data and tenant identifier.
  • Key storage has TTL and regular cleanup.
  • Parallel requests with the same key do not generate a second model call.
  • Retries use the original key, not a new one.
  • Response validation errors are treated as a new operation.
  • Deduplication and conflict metrics are displayed on the dashboard.