Idempotency Key API: Retry AI Jobs Without Paying Twice
How an idempotency key API header works for image and video jobs: a retried request returns the first job instead of a second charge. Code, edge cases.
Updated 6 min read
An idempotency key is a string of your choosing, sent in a header, that lets an API recognize a retry of a request it has already received. In an idempotency key API such as Frameport's, the Idempotency-Key header on POST /v1/images/generations, /v1/videos/generations and /v1/videos/edits means that the same request sent twice returns the first generation instead of starting, and charging, a second one, for 24 hours.
This guide covers why retries double-charge without a key, what the API does with one in each case, the edge cases that surprise people (a changed body, a failed job, a shared key), how to generate keys, and how agents and automations should use them.
The double-charge problem
A video request can take a few seconds to answer while the API checks it and holds its price. If your connection drops in that window, your code sees a timeout and cannot tell which of two things happened: the request never arrived, or it arrived, the clip started, and only the answer was lost.
Retrying without a key is a gamble. If the first request had arrived, the retry starts a second clip, holds its price, and charges it when it succeeds: two Seedance 2.5 clips at $1.35 each instead of one. Not retrying is no better, because the request may never have arrived. The only safe retry is one the server can match to the original.
How an idempotency key API call works
Send the header with a unique value per logical job. The first request with that key runs normally; later ones are matched against it:
| When | What the API answers |
|---|---|
| The first request with this key | 202 Accepted: the generation, its price held |
| The same key and the same body again | 200 OK with Idempotent-Replayed: true: the same generation, as it stands now, and nothing more held |
| The same key with a different body, or on another endpoint | 409 idempotency_conflict |
| The same key while the first request is still being answered | 409 request_in_progress, with a Retry-After of a couple of seconds |
The first request was refused (400, 402, 429…) | The key is free again: nothing was held, so fix the request and resend it with the same key |
Here is the effect from each language: the same body sent twice with one key produces one generation.
KEY=$(uuidgen)
for attempt in 1 2; do
curl -s -o /dev/null -w "%{http_code}\n" https://frameport.ai/v1/videos/generations \
-H "Authorization: Bearer $FRAMEPORT_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: $KEY" \
-d '{"model": "seedance-2-5", "prompt": "Paper lanterns rise over a dark lake", "duration": 5, "resolution": "480p"}'
done
# 202, then 200: the second send returned the first clipThe replay is not a stale copy: it reads the generation as it is now, so a retry that comes a minute later can already show it running or succeeded. The idempotency reference has the same table in short.
Same key, same body; same key, new body
The key is bound to the endpoint and to the body you sent with it. Most surprises come from that second part.
- The body is compared as sent. Whitespace does not matter, but the fields, their values and their order do. A retry that rebuilds the body with a new timestamp, an extra field, or the fields in another order is a different request, and gets
409 idempotency_conflict. Serialize the body once and send the same bytes on every attempt. - A failed job keeps its key. If the request was accepted and the clip failed later, the key stays bound to that failed generation for 24 hours, and resending it returns the failure. Nothing was charged; to try again, send the job with a new key, for example the old one with
-2on the end. - A refused request frees its key. A
400,402or429held nothing, so the key can be used again at once. - Keys belong to the workspace. Every API key of the workspace shares one key space. Two apps that both use
order-1842will collide, so prefix keys with the app or the job type. - 24 hours, then new. After that, the same string starts a fresh request.
- A replay still counts as a request. It is counted toward the workspace's 60 requests a minute, even though it starts nothing, so retry after a wait rather than in a tight loop.
A key is 1 to 200 printable ASCII characters with no spaces. Anything else is refused with 400 invalid_request before the request runs.
How to generate an idempotency key
There are two good recipes, and one rule behind both: the key must be created once per job, stored, and reused on every attempt. A new random key per attempt defeats the whole point.
- A random key stored with the job. Generate a UUID when you create the job record in your database, save it, then send it on every try. A crash and a restart still find the same key.
- A key derived from your own ids.
order-1842-videoorrow-77-thumbnailneeds no storage, since the same input always gives the same key. Make sure the id is unique within the workspace for 24 hours.
This pattern does both: the job, its exact body and its key are written before anything is sent, so a retry, a cron re-run or a restarted worker sends the identical request.
import json
import os
import sqlite3
import uuid
import requests
API = "https://frameport.ai/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['FRAMEPORT_API_KEY']}", "Content-Type": "application/json"}
db = sqlite3.connect("jobs.db")
db.execute("CREATE TABLE IF NOT EXISTS jobs (id TEXT PRIMARY KEY, body TEXT, idem TEXT, generation TEXT)")
def start(job_id: str, body: dict) -> str:
row = db.execute("SELECT body, idem, generation FROM jobs WHERE id = ?", (job_id,)).fetchone()
if row is None:
row = (json.dumps(body), f"video-{job_id}-{uuid.uuid4().hex[:8]}", None)
db.execute("INSERT INTO jobs VALUES (?, ?, ?, ?)", (job_id, *row))
db.commit()
raw, idem, generation = row
if generation:
return generation # started on an earlier run
res = requests.post(f"{API}/videos/generations", headers={**HEADERS, "Idempotency-Key": idem}, data=raw.encode(), timeout=60)
gen = res.json()
if gen.get("error"):
raise RuntimeError(f"{gen['error']['code']}: {gen['error']['message']}")
db.execute("UPDATE jobs SET generation = ? WHERE id = ?", (gen["id"], job_id))
db.commit()
return gen["id"]
print(start("1842", {"model": "seedance-2-5", "prompt": "Paper lanterns rise over a dark lake", "duration": 5}))Run it twice, or kill it between the send and the update: the second run sends the same bytes with the same key and gets the same generation back. When a request is refused, the error body has the same error field, so one test covers both cases.
Keys for agents and automations
Agents and no-code tools retry more than people do, so they need keys the most.
- MCP agents. The tools
generate_image,generate_videoandedit_videoof the MCP server take anidempotency_keyargument with the same rules. Tell the agent to use one new key per image or clip, and the same key when it retries a call. - n8n, Make and Zapier. Build the header from the row or record id (
clip-plus the row id). The tool's own "retry on failure" setting then becomes safe, and running a workflow twice over the same rows starts nothing twice. The n8n video workflow shows it in a real node. - Queues and cron jobs. Use the job's id from your queue. A message delivered twice then maps to one generation.
Keys pair with the rule that failed jobs cost nothing: one makes retries safe, the other makes failures free. Together they mean a retry policy never changes your bill (what a failed generation costs). For which errors deserve a retry at all, see the error codes guide.
FAQ
What is an idempotency key?
A unique string your client sends with a request, usually in an Idempotency-Key header, so the server can tell a retry from a new request. If the same key arrives again with the same request, the server returns the result of the first one instead of doing the work twice.
What is an idempotent API?
An API call is idempotent when making it twice has the same effect as making it once. Reading a resource is idempotent by nature. Creating a job is not, unless the API takes an idempotency key that turns a repeat into a replay of the first call.
Is the Idempotency-Key header required?
No. A request without one runs every time it is sent. Send one whenever a retry could happen, which in practice means every submit made by code.
What happens if an idempotency key is not unique?
If you reuse a key with a different body or on another endpoint within 24 hours, the API refuses the request with 409 idempotency_conflict and starts nothing. Use a new key for each new job, and keep the old key only for retries of the same job.
How long does an idempotency key last?
24 hours from the first request. After that, the same string is treated as a new key and starts a new request.