Skip to content
Browse the docs

Guides · curl · Python · 4 min

Retry without paying twice

Use an idempotency key so a repeated request returns the first result instead of a second charge.

Networks fail in the worst place: after the server did the work and before you received the answer. An idempotency key lets you repeat a request and get the original result instead of a second charge.

How it works

Add an Idempotency-Key header to POST /v1/images/generations. The value is any unique string up to 200 characters; a UUID is a good choice.

bash
curl https://api.useunbound.ai/v1/images/generations \
  -H "Authorization: Bearer $UNBOUND_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: 3f6c2f0a-8d1e-4c57-9a30-0b9a5d1c7e42" \
  -d '{ "model": "<image-model-id>", "prompt": "A lighthouse at dusk" }'

The first request with a given key creates a job, holds the price and generates the images. Any later request with the same key, from the same account, returns the same images. It does not start a second generation and it is not charged again.

Keys are scoped to your account. Another customer using the same string does not collide with yours.

A retry loop

Generate the key once per logical operation, outside the loop, and reuse it on every attempt.

python
import time, uuid
from openai import OpenAI, APIConnectionError, APIStatusError

client = OpenAI(base_url="https://api.useunbound.ai/v1", api_key="<your Unbound key>")
key = str(uuid.uuid4())

for attempt in range(4):
    try:
        result = client.images.generate(
            model="<image-model-id>",
            prompt="A lighthouse at dusk",
            extra_headers={"Idempotency-Key": key},
        )
        break
    except APIConnectionError:
        time.sleep(2 ** attempt)
    except APIStatusError as e:
        if e.status_code in (429, 502):
            time.sleep(2 ** attempt)
        else:
            raise

What to retry

ResponseRetry?
Connection dropped or timed outYes, with the same key.
429Yes, after the retry-after interval.
502Yes, with backoff. The hold was already released.
400, 401, 403, 404No. Fix the request or the key.
402No. Add credit or raise the key's spending limit.
400 with code content_policyNo. The provider refused the prompt; repeating it will not help.

Chat completions

Chat completions accept the same Idempotency-Key header. The first request with a given key runs; a later request with the same key from the same account is answered with 409 and is not generated or charged again, so a retry after a timeout cannot bill you twice. The answer of the first request is not replayed: if you did not receive it, send the request again with a new key.