# Safe retries

> Send an Idempotency-Key with every POST, reuse it only for retries of the same call, and log the request id.

Source: https://docs.b7r.app/safe-retries

## An Idempotency-Key on every POST

Every POST needs an `Idempotency-Key` header: up to 255 letters, digits, `.`, `_`, `:` or `-`. A UUID is a good choice. Without it the answer is `400 idempotency_key_required`.

## One key per operation

1. Make a new key when you decide to make a call, and store it with your own record of that call.
2. Send the same key and the same body on every retry of that call.
3. Make a new key for the next, different operation, even when its body looks the same.

Keep the key with the job:

```javascript
import { randomUUID } from "node:crypto";

// Make the key when you decide to make the call, and keep it with your record.
job.idempotencyKey ??= randomUUID();
await saveJob(job);

const res = await fetch("https://api.b7r.app/v1/quote", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.B7R_API_KEY}`,
    "Idempotency-Key": job.idempotencyKey, // the same value on every retry
    "Content-Type": "application/json",
  },
  body: JSON.stringify(job.body), // the same body on every retry
});
```

## What the key does

Today the only POST is `POST /v1/quote`, which saves nothing, so a repeated quote is harmless. The endpoints that create things, arriving next, use the key: the same key with the same body answers the first result again instead of doing the work twice, and the same key with a different body is refused. Code that sends the key correctly now needs no change then.

## Request ids

Every answer carries an `X-Request-Id` header, and every error body repeats it as `request_id`. Log it with your record of the call, and include it when you ask B7R for help.
