Errors, rate limits and safe retries
Read every error shape the API returns, understand the rate limits and tiers, and retry without ever paying twice.

How errors look
Errors use ordinary HTTP status codes and a JSON body. Most carry a single human-readable detail string. A few, the ones you are expected to branch on in code, carry an object with a stable machine-readable code instead. Every response, successful or not, includes an X-Request-Id header: quote it when you contact support and it identifies your call exactly.
| Shape | Where you meet it | How to read it |
|---|---|---|
{ "detail": "text" } | Most 400, 401, 404, 424 and 500 answers | The text is the message. Branch on the status. |
{ "detail": { "error": ..., "message": ... } } | 402 wallet, 403 scope or tier, 429 key and tier limits, IDA Q jobs | A stable code in error (or code) and a sentence in message. |
{ "detail": [ { "loc": ..., "msg": ... } ] } | Validation of typed request bodies (422) | One entry per bad field; loc is the path to it. |
{ "error": { "code": ..., "message": ... } } | The video timeline and analysis routes (/v1/video/projects, /ops, /jobs, scene, silence and beat detection, transcribe) | The envelope: a kebab-case code such as rate-limited, a message and optional details. |
| Status | Meaning | Charged? | What to do |
|---|---|---|---|
400 | Missing or invalid field, for example no prompt, a bad model parameter, an over-long text. A provider can also refuse with a 400 | No | Fix the request; do not retry unchanged |
401 | Key missing, malformed or revoked: Missing Authorization header, Invalid API key. Document routes answer Invalid or expired token | No | Check the Authorization: Bearer header and the key's status |
402 | insufficient_funds: the wallet cannot cover the request. spend_limit_reached: your own monthly spend limit would be exceeded | No | Top up the wallet or raise the limit; the body gives the numbers |
403 | insufficient_scope (key lacks a scope), read-only key on a write action, api_access_required (no paid plan or balance), or a tier refusing a feature or model | No | Change the key's scopes or type, fund the wallet, or use another key |
404 | Unknown path or a job/resource that is not yours | No | Check the path against the docs |
409 | An X-Idempotency-Key request is still running | Once | Retry after the Retry-After seconds to receive its result |
422 | Validation failed, or the idempotency key was reused with a different body | No | Fix the field named in the error, or use a fresh key |
424 | The provider or engine failed after your request was accepted. The message says the wallet was not charged | No | Retry later; try another model if it persists |
429 | Rate limit exceeded for the key, the account tier or the route; also a busy engine | No | Wait Retry-After seconds, then retry |
5xx | Server or engine error. A 503 from IDA Q says Retry-After: 5 and gives the job_id to retry with | Refunded if it was taken | Retry with backoff |
Real bodies
These are untouched answers from the production API, captured while writing this guide.
// 401, no Authorization header
{ "detail": "Missing Authorization header" }
// 401, wrong key
{ "detail": "Invalid API key" }
// 400, missing field
{ "detail": "prompt is required" }
// 404, unknown path
{ "detail": "Not Found" }
// 424, an engine failed after acceptance (nothing was charged)
{ "detail": "{\"error\":\"Video generation service error. Please try again.\"} Your wallet was not charged for this request." }The 424 shows the pattern for provider trouble: a sentence that quotes the upstream service and ends with the fixed line Your wallet was not charged for this request. The same line closes provider refusals that arrive as a 400, for example a capability the provider does not offer to the account behind it. Read the status and the closing sentence together: a 424 is worth retrying later, a provider 400 is not worth retrying unchanged.
The 402 carries everything a client needs to explain itself to the user. Its detail is an object:
{
"detail": {
"error": "insufficient_funds",
"code": "insufficient_funds",
"message": "Insufficient funds: this request costs $0.0315 but your balance is $0.0100. Top up your wallet with at least $0.0215 to continue.",
"required_usd": 0.0315,
"balance_usd": 0.01,
"shortfall_usd": 0.0215,
"currency": "USD",
"charged": false,
"charged_usd": 0,
"topup_url": "https://fotohub.app/console/wallet"
}
}A 402 (the message continues with a note that the API is prepaid and credits cannot pay for it). The check happens before any model runs, so a thin wallet costs you only the round trip.
spend_limit_reached has the same layout with spent_usd and limit_usd in place of the balance fields. Both set charged: false.
One parser for every shape
Put the parsing in one place so the rest of your code sees one error type: status, code, message, Retry-After and request id. The rule that covers every shape: when detail is an object, the code is its code or error field and the text is message; when the body has an error object, take its code and message; when detail is a list, join the loc and msg pairs; otherwise detail is the text.
import requests
class ApiError(Exception):
"""One error type for every body shape the API can return."""
def __init__(self, res: requests.Response):
try:
body = res.json()
except ValueError:
body = {}
detail = body.get("detail")
envelope = body.get("error")
if isinstance(detail, list):
# Typed-body validation: [{"loc": [...], "msg": "...", "type": "..."}]
self.code = "validation"
self.message = "; ".join(
".".join(map(str, e.get("loc", []))) + ": " + str(e.get("msg")) for e in detail
)
elif isinstance(detail, dict):
# 402, 403, 429 and IDA Q errors: the code is "code" or "error"
self.code = detail.get("code") or detail.get("error")
self.message = detail.get("message") or detail.get("error") or ""
elif isinstance(envelope, dict):
# Video timeline routes: {"error": {"code", "message", "details"}}
self.code = envelope.get("code")
self.message = envelope.get("message", "")
else:
# {"detail": "text"}, or {"error": "...", "message": "..."} from engines
self.code = envelope if isinstance(envelope, str) else None
self.message = detail if isinstance(detail, str) else body.get("message", "")
self.status = res.status_code
self.request_id = res.headers.get("X-Request-Id")
retry_after = res.headers.get("Retry-After")
self.retry_after = float(retry_after) if retry_after else None
super().__init__(f"{self.status} {self.code or '-'}: {self.message}")
def call(path: str, body: dict, headers: dict) -> dict:
res = requests.post("https://apis.fotohub.app" + path, json=body, headers=headers, timeout=120)
if res.ok:
return res.json()
raise ApiError(res)
# Branch on status first, then on code:
# 402 insufficient_funds / spend_limit_reached -> top up or raise the limit, do not retry
# 403 insufficient_scope / api_access_required -> fix the key or the account, do not retry
# 429 -> wait err.retry_after, then retry
# 409 / 424 / 5xx -> retry with the same X-Idempotency-Key
# anything else -> log err.request_id and stopPython with requests: one exception class for all shapes
export type ApiError = {
status: number;
code?: string;
message: string;
retryAfter?: number;
requestId?: string;
};
export async function parseError(res: Response): Promise<ApiError> {
const body: any = await res.json().catch(() => ({}));
const d = body.detail;
let code: string | undefined;
let message = "";
if (Array.isArray(d)) {
code = "validation"; // [{ loc, msg, type }]
message = d.map((e: any) => (e.loc ?? []).join(".") + ": " + e.msg).join("; ");
} else if (d && typeof d === "object") {
code = d.code ?? d.error; // 402, 403, 429 and IDA Q errors
message = d.message ?? d.error ?? "";
} else if (body.error && typeof body.error === "object") {
code = body.error.code; // video timeline routes
message = body.error.message ?? "";
} else {
code = typeof body.error === "string" ? body.error : undefined;
message = typeof d === "string" ? d : body.message ?? "";
}
const retryAfter = res.headers.get("retry-after");
return {
status: res.status,
code,
message,
retryAfter: retryAfter ? Number(retryAfter) : undefined,
requestId: res.headers.get("x-request-id") ?? undefined,
};
}TypeScript with fetch: the same parser
If you use an official SDK, you get this for free. The status maps to a typed error and the useful fields are properties on it.
from fotohub import (
AuthError,
FotoHub,
FotoHubError,
InsufficientFundsError,
RateLimitError,
ServerError,
ValidationError,
)
client = FotoHub()
try:
result = client.generate_image("a lighthouse at dusk", aspect_ratio="16:9")
print(result["images"][0]["url"])
except InsufficientFundsError as e:
# 402: nothing was charged. The wallet needs a top-up.
print(f"Wallet too low: needs ${e.required_usd}, has ${e.balance_usd}. Top up: {e.topup_url}")
except RateLimitError as e:
print(f"Slow down, retry after {e.retry_after} seconds")
except ValidationError as e:
print("Fix the request:", e.message)
except AuthError:
print("Check FOTOHUB_API_KEY: missing, malformed or revoked")
except ServerError as e:
print("Engine problem, safe to retry later:", e.message)
except FotoHubError as e:
print(f"HTTP {e.status_code}: {e.message}")The Python SDK: typed errors for 402, 429, 400/422, 401 and 5xx
import {
AuthenticationError,
FotoHub,
FotoHubError,
InsufficientCreditsError, // the 402 class; the name predates the USD wallet
RateLimitError,
ServerError,
} from "fotohub";
const client = new FotoHub({ apiKey: process.env.FOTOHUB_API_KEY! });
try {
const result = await client.generateImage({ prompt: "a lighthouse at dusk", aspect_ratio: "16:9" });
console.log((result.images[0] as unknown as { url: string }).url);
} catch (error) {
if (error instanceof InsufficientCreditsError) {
console.error("Wallet too low. Nothing was charged. Top up in the console.");
} else if (error instanceof RateLimitError) {
console.error(`Slow down, retry after ${error.retryAfter} seconds`);
} else if (error instanceof AuthenticationError) {
console.error("Check apiKey: missing, malformed or revoked");
} else if (error instanceof ServerError) {
console.error("Engine problem, safe to retry later:", error.message);
} else if (error instanceof FotoHubError) {
console.error(`${error.name} (${error.statusCode ?? "no status"}): ${error.message}`);
} else {
throw error;
}
}The TypeScript SDK: the same ladder (the 402 class keeps an older name)
Both SDKs also retry inside one call: rate limits and transient server errors are repeated with exponential backoff (the Python SDK also waits for Retry-After), and charged calls keep one automatic idempotency key across the attempts.
From symptom to action
When something fails at two in the morning, a lookup beats reasoning. Find the symptom, check the cause, take the action.
| Symptom | Likely cause | Action |
|---|---|---|
403 insufficient_scope | The key was created without the scope this route needs; the body names required_scope and granted_scopes | Add the scope to the key or use another key; see the API keys article |
402 insufficient_funds | Balance below the price of this call | Top up by at least shortfall_usd; ask POST /v1/billing/estimate first next time |
402 spend_limit_reached | Your own monthly spend limit is used up, even though the wallet is funded | Raise or remove the limit in the console, as the message says |
429 with scope: api_key | This one key passed its own requests-per-minute setting | Wait until X-RateLimit-Reset, pace the client, or raise the key's limit (up to 600) |
429 with tier | The whole account passed its tier's requests per minute, across all keys | Spread the load across the minute; see Limits & Tiers for the next tier |
A job ends failed | The engine could not deliver, for example an empty image | Read billing.refunded on the poll; submit again if you still need the result |
Rate limits and tiers
Three limits can apply to a call, and each answers 429 when it trips. A call has to get past all of them, so the tightest one decides.
| Limit | Who sets it | 429 body |
|---|---|---|
| Per key | You, on the key (1 to 600 requests per minute, 60 by default) | { "detail": { "error": "rate_limit_exceeded", "scope": "api_key", "limit_rpm": 60, ... } } |
| Per account tier | Your tier (requests per minute for the whole account) | { "detail": { "error": "rate_limit_exceeded", "tier": "...", "limit_rpm": ..., "upgrade_url": ... } } |
| Per route | The platform protects expensive routes with their own windows | { "error": "Rate limit exceeded. Please try again later." } |
The per-key limit is the one you control: set it on the key when you create it, and give a batch job its own key with a number that fits the job. The window is a fixed minute, so the counter starts again at the next minute boundary.
Headers to read on every response
| Header | Meaning |
|---|---|
X-RateLimit-Limit | Requests allowed in the window that decided this call |
X-RateLimit-Remaining | Requests left in that window |
X-RateLimit-Reset | When the window ends, in Unix seconds |
Retry-After | On a 429: seconds to wait. The key and tier limits say 60, a route window says its own length, a busy engine its own estimate |
X-Tier | The tier that was applied, on tier-checked routes |
X-Request-Id | A unique id for this call, on every response |
Two details help. On a key 429, Retry-After always says 60, but X-RateLimit-Reset is the real end of the current minute, which may be seconds away: waiting for the reset is faster. And the numbers describe the window that produced the answer, so read them as given.
let remaining = Infinity;
let resetAt = 0; // Unix seconds, from X-RateLimit-Reset
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
// Wraps fetch for a single worker: when the window is nearly used up,
// wait for its end instead of running into a 429.
export async function paced(url: string, init: RequestInit): Promise<Response> {
if (remaining <= 1 && resetAt * 1000 > Date.now()) {
await sleep(resetAt * 1000 - Date.now());
remaining = Infinity;
}
const res = await fetch(url, init);
const left = res.headers.get("x-ratelimit-remaining");
const reset = res.headers.get("x-ratelimit-reset");
if (left !== null) remaining = Number(left);
if (reset !== null) resetAt = Number(reset);
return res;
}A rate-limit-aware fetch wrapper for one worker: read the headers, wait for the reset before the first 429
Tiers

The API is pay-as-you-go: every account pays the same USD price per model, straight from the prepaid wallet. Tiers set throughput only (requests per minute, concurrent jobs, storage) and they activate on their own from your wallet balance or lifetime spend; there is no plan to pick. At the time of writing the console lists these tiers:
| Tier | Requests per minute | Concurrent jobs |
|---|---|---|
| Pay-As-You-Go Basic | 30 | 3 |
| Pay-As-You-Go Standard | 120 | 10 |
| Pay-As-You-Go Premium | 500 | 30 |
| Business (no longer sold, kept on accounts that hold it) | 1,000 | 50 |
| Enterprise (by contract) | 5,000 | 200 |
The numbers can change, so treat Console → Limits & Tiers as the source of truth. API Usage shows the same limits as a utilisation gauge, including today's requests against the daily quota, which resets at midnight UTC.
Idempotency: retry without paying twice
The dangerous failure is a timeout or a 504 that arrives after the work has already started: the generation runs and is billed, but your client sees an error and tries again. Send an X-Idempotency-Key header on charged POST calls and the API recognises the retry.
| Situation | What the API does |
|---|---|
| Same key, same body, original finished | Returns the stored response with the header Idempotent-Replay: true. No second charge. |
| Same key, original still running | 409 with Retry-After: 5. The text says the operation is charged once. |
| Same key, different body | 422: the key was already used for a different request body |
| Key longer than 255 characters | 400: the key must be at most 255 characters |
On most routes these four answers use the plain { "detail": "text" } shape, so branch on the status (and on Retry-After for the 409). On the video timeline routes the same answers come in the envelope with the codes idempotency-in-progress, idempotency-key-reuse and idempotency-key-invalid.
- Applies to
POSTroutes under/v1/ai/,/v1/images/,/v1/video/,/v1/shorts/,/v1/story/,/v1/3d/,/v1/generate/and/v1/voice/. Elsewhere the header is harmless and ignored. - Streaming and binary-audio routes are excluded, because a stream cannot be replayed: chat completions, the agent stream, the story stream and the provider TTS synthesise routes.
- Keys are remembered for 24 hours, per credential and per endpoint. Use a fresh key (a UUID is fine) for each new logical request and reuse the same one for every retry of that request.
- Only successful (2xx) answers are stored. A failed attempt releases the key, so a
402,429or500never gets stuck: after you top up or wait, the same key works again.
Proving the replay
Goal. Check that a repeated call with the same key charges once.
Input you can copy.
Read `GET /v1/billing/balance`. Call `POST /v1/ai/analyze/image` twice with the same body and the same `X-Idempotency-Key`. Read the balance again.Why it works. Both calls answered 200, and the balance dropped by the price of one analysis only. The second answer is the stored result of the first.
Deduplicate a work queue by job id
A queue delivers messages at least once, so the same item will occasionally reach two workers, or reach one worker twice after a crash. Derive the idempotency key from your own job id and the duplicate is harmless: the second submit is a replay, or a 409 that resolves to the first result. The worker below combines the parser and the rate-limit wrapper from earlier.
const API = "https://apis.fotohub.app";
const RETRYABLE = new Set([408, 409, 424, 429, 500, 502, 503, 504]);
export async function submit(job: { id: string; prompt: string }) {
const init: RequestInit = {
method: "POST",
headers: {
Authorization: "Bearer " + process.env.FOTOHUB_API_KEY,
"Content-Type": "application/json",
// Derived from your own job id: identical on every attempt and
// after a restart of the worker, so a duplicate is replayed, not charged.
"X-Idempotency-Key": "job-" + job.id,
},
body: JSON.stringify({ model: "seedream-5-0-260128", prompt: job.prompt }),
};
for (let attempt = 1; attempt <= 4; attempt++) {
let res: Response;
try {
res = await paced(API + "/v1/ai/generate/image", init);
} catch {
if (attempt === 4) throw new Error("network error after 4 attempts");
await sleep(2 ** attempt * 1000);
continue;
}
if (res.ok) return res.json();
const err = await parseError(res);
if (!RETRYABLE.has(err.status) || attempt === 4) throw err;
await sleep(Math.min((err.retryAfter ?? 2 ** attempt) * 1000, 60000));
}
}A queue worker: stable key from your job id, pacing, parsed errors and bounded retries
IDA Q image jobs add a second guard that works without a header. Put your own UUID in the body as job_id: submitting it again answers with the same job and "duplicate": true instead of charging again. A malformed id gets a 400 saying job_id must be a UUID. If the queue is unreachable, the answer is a 503 with Retry-After: 5, retryable: true and the job_id to resend; a queued job is never charged twice.
A submit that times out
Goal. Resubmit a paid image job after a network timeout without paying twice.
Input you can copy.
The worker sends `POST /v1/ai/generate/image` with `X-Idempotency-Key: job-4711` and the connection drops after 120 seconds. It waits two seconds and sends the identical request with the identical key.Why it works. If the first request had finished, the retry gets 200 with Idempotent-Replay: true and the stored image. If it was still running, the retry gets 409, waits, then receives the same stored result. If it never arrived, the retry simply runs. In all three cases the wallet is charged once.
A retry strategy that holds up
| Status | Retry? |
|---|---|
400, 401, 402, 403, 404, 422 | No. Fix the request, key or wallet first. |
408, 424, 500, 502, 503, 504 | Yes, with exponential backoff and the same idempotency key. Exception: a 500 that says Pricing is not configured is a mistyped model id. |
429 | Yes, after the Retry-After seconds, or at X-RateLimit-Reset if that is sooner. |
409 idempotency-in-progress | Yes, after Retry-After. You will get the first call's result. |
- Cap the attempts (four is plenty) and cap the wait (a minute). An outage should surface as an error, not as a silent hour-long loop.
- Never retry a charged call without an idempotency key. If you cannot send one, treat a timeout as unknown and check the Request Log before you resubmit.
import os
import time
import uuid
import requests
API = "https://apis.fotohub.app"
HEADERS = {"Authorization": f"Bearer {os.environ['FOTOHUB_API_KEY']}"}
RETRYABLE = {408, 424, 429, 500, 502, 503, 504}
def post_with_retry(path: str, body: dict, attempts: int = 4) -> dict:
# One idempotency key for every attempt of this one logical request:
# a retry after a timeout is replayed, not charged twice.
headers = {**HEADERS, "X-Idempotency-Key": str(uuid.uuid4())}
for attempt in range(1, attempts + 1):
try:
res = requests.post(API + path, json=body, headers=headers, timeout=120)
except (requests.ConnectionError, requests.Timeout):
if attempt == attempts:
raise
time.sleep(2 ** attempt)
continue
if res.ok:
return res.json()
if res.status_code not in RETRYABLE or attempt == attempts:
res.raise_for_status()
# 429 tells you how long to wait; the rest back off exponentially.
wait = int(res.headers.get("Retry-After", 2 ** attempt))
time.sleep(min(wait, 60))
raise RuntimeError("unreachable")A small retry helper that reuses one idempotency key
Check the wallet before a batch
Goal. Know whether two images will go through before sending them.
Input you can copy.
`POST /v1/billing/estimate` with `{"operations": [{"type": "image", "model": "seedream-5-0-260128", "count": 2}]}`.Why it works. A real call answered total_usd: 0.063 (two pieces at 0.0315 each), the wallet balance and sufficient: true. Prices change, so read the live numbers from this endpoint, GET /v1/models or GET /v1/pricing rather than from this page. If sufficient is false, top up first and the batch never meets a 402.
Failed jobs and refunds
For asynchronous jobs the failure often arrives later, on the poll: the job reports failed with an error message and a billing block that says refunded: true and the amount returned. A charge is taken at submit time and given back automatically when the engine cannot deliver, so polling a failed job is also how you learn the money is back. Polling itself costs nothing.
{
"job_id": "1492a4fd-459e-4fe9-87de-573e235500af",
"status": "failed",
"error": "The model returned an empty image. You were not charged for it. (OUTPUT_INVALID)",
"billing": { "method": "wallet", "currency": "USD", "cost_usd": 0.13, "refunded_usd": 0.13, "refunded": true, "refund_pending": false },
"refunded": true
}A real failed IDA Q job: the charge came back automatically
| Field on the poll | What it tells you |
|---|---|
error | Present on a failed job: a sentence, with a closing code such as OUTPUT_INVALID |
billing.refunded_usd, refunded | What came back and whether the refund is complete |
billing.refund_pending | true while a refund is still being paid out |
If you would rather not poll, subscribe to webhooks: generation.failed reports a failed job, generation.refunded and billing.refunded report the money back, and billing.insufficient_funds fires when a call is refused for lack of funds. Events and signatures are in the webhooks article.
A failed job that paid itself back
Goal. Decide what to do with a job that ended failed.
Input you can copy.
The submit answered `202` with `cost_usd: 0.13`. Polls showed `processing` with rising `progress`, then the poll above: `failed` at 97 percent.Why it works. Read billing.refunded: it is true and refunded_usd equals cost_usd, so the wallet is whole again. There is nothing to claim. Show the user the error sentence, and submit a new job if the result is still needed. Use a new idempotency key for it, because the old one belongs to the failed job.
Find a failed call in the console
The Request Log lists every call with method, endpoint, model, status and timings. Filter by status to isolate the errors, and use Export CSV to analyse a period (the export covers the rows loaded on screen, not the whole range). Jobs shows every asynchronous job with its status, how long it took, what was charged and whether it was refunded. API Usage adds the big picture.




A good order: start in API Usage to see whether 4xx (your requests) or 5xx (the service) dominate; open the Request Log filtered to errors to find the time and endpoint; for an asynchronous job, open Jobs and copy its id and poll route.
Writing a support request that gets answered fast
- Capture the request id Log the
X-Request-Idresponse header for every failed call, together with the status and the body. A crash (a500from an unhandled error) also puts the id in the JSON body asrequest_id. - Add the job id and the time For an asynchronous job include the
job_idand the last poll body. State the time in UTC and the endpoint. Never paste your API key; the request id is enough to find the call.
Production checklist
- One key per application or environment, with only the scopes it needs and a per-key rate limit that fits its traffic. A leaked key then costs little and is easy to revoke.
- A single error parser that understands every body shape, as above, and a log line with status, code, message and
X-Request-Idfor each failure. X-Idempotency-Keyon every chargedPOST, derived from your own job id so it survives restarts.- A balance check before big batches (
POST /v1/billing/estimate) and a handler for402that tells the user to top up and linkstopup_url. - Polling that stops on
completedorfailed, or a webhook endpoint forgeneration.failedandgeneration.refunded. Show users theerrortext of a failed job.
Troubleshooting FAQ
- Was I charged for a call that failed?
- Synchronous failures (400, 401, 402, 403, 404, 422, 424 and the pricing 500) do not charge, and the message often says so. An asynchronous job is charged at submit time and refunded automatically if it fails: check
billing.refundedon the poll, or the refunded marker in Jobs. - I get 429 although I send only a few requests. Why?
- Look at the 429 body.
scope: api_keymeans this key's own limit; atierfield means the whole account's limit, which every key and every script shares. Several scripts on one account add up. Also check whether a polling loop is sleeping too briefly: polls are free but they still count as requests. - A provider error came back as 400 or 424. Which should I retry?
- A 424 is worth retrying later, then with another model if it persists. A provider 400 means the provider declined the request itself, for example because a capability is not available to the account behind it; the same request will get the same answer. Either way the closing sentence says the wallet was not charged.
What to read next
Continue in the webhooks article for signed events that replace polling, the API keys article for scopes and per-key limits, and the Python SDK and TypeScript SDK articles for automatic retries and typed errors.