> For the complete documentation index, see [llms.txt](https://docs.flora.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.flora.ai/api/platform/idempotency.md).

# Idempotency

Retry FLORA API requests safely with the Idempotency-Key header and the Technique-run idempotency\_key, without starting or paying for duplicate runs.

When a `POST` fails mid-flight, you can't tell whether FLORA received it, and a blind retry can start the same run twice and bill it twice. Idempotency keys make retries safe. FLORA has two kinds, and they behave differently:

|                                     | `Idempotency-Key` header                                  | `idempotency_key` body field                    |
| ----------------------------------- | --------------------------------------------------------- | ----------------------------------------------- |
| Works on                            | Every mutating request (`POST`, `PUT`, `PATCH`, `DELETE`) | `POST /techniques/{slug}/runs` only             |
| Remembered for                      | 2 hours                                                   | As long as the run exists                       |
| Scope                               | Workspace + endpoint + path parameters                    | Workspace                                       |
| A repeat gets                       | `409 idempotency_duplicate`                               | The original run, with its current status       |
| Released if the first request fails | Yes                                                       | Not applicable: a failed request creates no run |

## The `Idempotency-Key` header

Send any string you choose in the `Idempotency-Key` header:

```bash
curl -X POST https://app.flora.ai/api/v1/generate \
  -H "Authorization: Bearer $FLORA_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: spring-launch-hero-01" \
  -d '{
    "type": "image",
    "prompt": "A ceramic mug on a sunlit table",
    "workspace_id": "ws_abc123",
    "project_id": "prj_abc123"
  }'
```

How it works:

1. FLORA records the key for **two hours**, scoped to your workspace, the endpoint and its path parameters. The same key on a different endpoint, or aimed at a different project or folder, is a different request.
2. A second request with the same key in that window is rejected with `409 idempotency_duplicate`. FLORA doesn't replay the first response, and it doesn't compare bodies: a different body with the same key is still a duplicate.
3. If the first request fails (any non-2xx response), FLORA releases the key, so a retry with the same key runs normally.
4. Concurrent requests with the same key don't both run: one proceeds and the other gets `409 idempotency_duplicate`.

So a `409 idempotency_duplicate` means "the first one got through". Don't retry with a new key; look up what it created instead. For a generation, list the project's newest generations:

```bash
curl "https://app.flora.ai/api/v1/generations?project_id=prj_abc123&limit=5" \
  -H "Authorization: Bearer $FLORA_API_KEY"
```

`POST /generate` with `quote: true` ignores the header, so you can refresh an estimate whenever you like.

### Batch uploads

`POST /assets/reserve` and `POST /assets/complete` follow the same rules, with one addition. If every entry in the batch was rejected (`input_validation_error`, `not_found` or `forbidden`), nothing was written, so FLORA releases the key and you can resend the same request with it. Any other batch keeps its key, even if an entry failed with `unknown_error`, because that write may have landed. Retry the failed entries in a new request with a new key.

## The `idempotency_key` body field on Technique runs

`POST /techniques/{slug}/runs` also accepts `idempotency_key` in the body. FLORA stores it with the run. Any later request in the same workspace with the same key returns that run, whatever its status, instead of starting a new one. If it has completed, the response includes its outputs.

```bash
curl -X POST https://app.flora.ai/api/v1/techniques/your-technique-slug/runs \
  -H "Authorization: Bearer $FLORA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "inputs": [{ "id": "headline", "type": "text", "value": "Smart living, simple" }],
    "mode": "async",
    "idempotency_key": "q3-thumb-DE"
  }'
```

The body isn't compared, and the key doesn't expire. Change the key whenever you want a new run.

For Technique runs, prefer the body field: a retry gives you the run back instead of a `409`. If you send both, the header is checked first.

LoRA training has its own `client_token`, which works like the body field. See [Train and use LoRA Styles](https://docs.flora.ai/api/guides/loras.md).

## In code

{% tabs %}
{% tab title="TypeScript" %}

```ts
import { FloraClient } from "@flora-ai/flora"

const client = new FloraClient()

// Technique runs: body field
const run = await client.techniques.runs.create({
  techniqueId: "your-technique-slug",
  inputs: [{ id: "headline", type: "text", value: "Smart living, simple" }],
  mode: "async",
  idempotency_key: "q3-thumb-DE",
})

// Everything else: header, passed in the request options
const generation = await client.generations.create(
  {
    type: "image",
    prompt: "A ceramic mug on a sunlit table",
    workspace_id: "ws_abc123",
    project_id: "prj_abc123",
  },
  { headers: { "Idempotency-Key": "spring-launch-hero-01" } },
)
```

{% endtab %}

{% tab title="CLI" %}

```bash
# --idempotency-key sets the body field on Technique runs
flora techniques:runs create \
  --technique-id your-technique-slug \
  --input '{id: headline, type: text, value: "Smart living, simple"}' \
  --mode async \
  --idempotency-key "q3-thumb-DE"
```

{% endtab %}
{% endtabs %}

## Choosing good keys

Good keys are deterministic: the same logical operation always produces the same key.

* `q3-thumb-{market_code}`: derived from the market you're processing.
* `import-csv-row-{row_hash}`: derived from a hash of the input row.
* `user-{user_id}-onboarding-thumbnail`: derived from the user.

Bad keys change on every attempt, which defeats the point:

* `crypto.randomUUID()` generated inside the retry loop.
* `Date.now()`, for the same reason.
* `"my-run"`, which collides across unrelated operations.

If you want a UUID, generate it once at the start of the logical operation and reuse it on every retry:

```ts
const idempotencyKey = crypto.randomUUID() // once per logical operation

for (let attempt = 0; attempt < 3; attempt++) {
  try {
    return await client.techniques.runs.create({
      techniqueId: "your-technique-slug",
      inputs,
      mode: "async",
      idempotency_key: idempotencyKey, // same on every retry
    })
  } catch (err) {
    if (!shouldRetry(err)) throw err
  }
}
```

## What idempotency keys aren't

* **Not deduplication of content.** Two different keys with the same inputs start two runs, each billed. Keys protect against accidental retries, not intentional repeats.
* **Not authentication.** Anyone with your API key can use any idempotency key.

## Recipe: idempotent batch import

```ts
import { FloraClient } from "@flora-ai/flora"
import crypto from "node:crypto"

const client = new FloraClient()

function keyFor(row: { market: string; headline: string }) {
  const hash = crypto
    .createHash("sha256")
    .update(`${row.market}|${row.headline}`)
    .digest("hex")
    .slice(0, 16)
  return `q3-thumb-${row.market}-${hash}`
}

async function importRow(row: { market: string; headline: string }) {
  return client.techniques.runs.create({
    techniqueId: "your-technique-slug",
    inputs: [{ id: "headline", type: "text", value: row.headline }],
    mode: "async",
    idempotency_key: keyFor(row),
  })
}
```

Re-running this script on the same CSV returns the existing run for every row it already started. Edit a row's headline and its key changes, so that row runs again.

## Related

* [Errors](https://docs.flora.ai/api/platform/errors.md): `409 idempotency_duplicate` and what to retry.
* [Batch from a CSV](https://docs.flora.ai/api/recipes/batch-from-csv.md): a full batch pattern.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.flora.ai/api/platform/idempotency.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
