Retrying safely

Retrying safely

An Idempotency-Key header makes a retry do nothing twice.

Example request

A write you can retrybash
curl -X POST "https://console.brevily.com/api/NORTHWIND/links" \  -H "x-api-key: brv_ak_7Fq2Lw9xK3" \  -H "x-api-secret: $BREVILY_SECRET" \  -H "Idempotency-Key: 6f1c2d4e-launch-1" \  -H "content-type: application/json" \  -d '{"url": "https://example.com/launch"}'

Example answer

The same call againhttp
HTTP/1.1 201 CreatedIdempotency-Replayed: true{ …the link the first call made… }

Made-up values.

A read (GET) changes nothing, so it is always safe to send again. A write is not: if a POST times out, it may have made the link anyway, and sending it again would make two. Send an Idempotency-Key header with the write, and send the same one with every retry of it: the first call runs, and the rest answer what it did.

The headers
NameTypeDescriptionAllowed values
Idempotency-KeyheaderYour own value, up to 255 characters, new for each write you mean to make once: a UUID does. Sent empty, it is as if not sent.—
Idempotency-ReplayedheaderOn an answer: true when it is the first call’s answer, sent again.—

Every write here takes it. The MCP server takes idempotency_key among a tool’s arguments instead.

How a key is keptPermalink

  • A key is your API key’s own: the same value from another key, or another organisation, is another key.
  • A finished answer is kept 24 hours. Inside that time the same key and the same request answer it again (the same status and body), with Idempotency-Replayed: true, and do nothing. A replay does not count against the rate limit.
  • The same request means the same method, path, query and body, byte for byte. The same key on a different one answers 422 IDEMPOTENCY_MISMATCH.
  • While the first call is still running, the same key answers 409 IDEMPOTENCY_IN_FLIGHT: wait and send it again. If that call’s server stopped mid-way, the key frees itself after 2 minutes.
  • A refused call is not kept: a 400 or a 429 sent again with its key runs again, so a fix goes through.
  • A key longer than 255 characters answers 400 IDEMPOTENCY_KEY_INVALID.
  • A list of links sent in one call is one request: one key covers it all, and a retry answers the same results.

Which answers to retryPermalink

Retry when nothing came back (a timeout, a dropped connection), on 429 and 503 (after Retry-After when the answer sends one), on 409 IDEMPOTENCY_IN_FLIGHT, and on 500, 502 and 504 with a growing pause. Any other 4xx needs the request changed first. A signed request is signed again for each attempt, with a new nonce; the Idempotency-Key stays the same.

A write, retried with backoffjavascript
// One key for every attempt of the same write.async function createLink(body, key = crypto.randomUUID()) {  for (let attempt = 1; ; attempt++) {    let res;    try {      res = await fetch(`${API}/NORTHWIND/links`, {        method: 'POST',        headers: {          'x-api-key': KEY_ID,          'x-api-secret': SECRET,          'content-type': 'application/json',          'Idempotency-Key': key,        },        body: JSON.stringify(body),      });    } catch (failed) {      if (attempt === 5) throw failed; // no answer, five times      await pause(attempt);      continue;    }    if (res.ok) return await res.json();    const answer = await res.json().catch(() => ({}));    const again = [429, 500, 502, 503, 504].includes(res.status) ||      answer.code === 'IDEMPOTENCY_IN_FLIGHT';    if (!again || attempt === 5) throw new Error(answer.message ?? res.status);    await pause(attempt, res.headers.get('Retry-After'));  }}// Retry-After when the answer gives it, else 1, 2, 4, 8 s and a little more.const pause = (attempt, after) =>  new Promise((done) => setTimeout(done, after    ? Number(after) * 1000    : (2 ** (attempt - 1) + Math.random()) * 1000));

Common mistakesPermalink

  • A new key for each attempt: then every attempt is a first call, and a timeout can still make two.
  • One key for several different writes: the second answers 422 IDEMPOTENCY_MISMATCH. Keep the key with the thing it makes (the row in your database, say) and reuse it only for that.
  • Retrying a write with no key at all: if the first went through, the retry makes a second.
  • Retrying past 24 hours with the same key: by then the first answer is gone, and the write runs again.