Idempotency and retries

Send the Idempotency-Key header so a repeated write gets the first answer back instead of running twice.

On this page

Networks drop answers. When a call times out you cannot tell whether it ran, and sending it again could create a second site, queue the same prompt twice or send an email twice. The Idempotency-Key header makes a repeat safe.

How it works

Add a key of your own to a call that changes something. Any value of 1 to 255 visible ASCII characters works, and a fresh UUID for each new piece of work is the usual choice.

curl -X POST https://api.modulify.ai/v1/send_message \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Idempotency-Key: 3f8b6c2e-2a51-4f0e-9a7d-6a4d1c9b2e10" \
  -d '{"projectId":"SITE_ID","prompt":"Add a newsletter sign-up form to the footer."}'

Then send the same request again, with the same key, whenever you are not sure the first one arrived:

What happened to the first call What the repeat gets
It succeeded The first call's answer, without running again, with the headers Idempotency-Replayed: true and Idempotency-Status: replayed
It is still running A 409 with Idempotency-Status: running and the message "A request with this Idempotency-Key is still running. Wait for it to finish before retrying!" Wait, then repeat it again
It was refused before it ran, or the method refused it with a status below 500 Nothing is kept, so the repeat runs as a new attempt
It failed with a status of 500 or above The same failure again, with Idempotency-Replayed: true, because the method may have done part of its work before it failed
It never arrived The repeat runs, as the first attempt

A key belongs to the token that sent it, so two tokens can never collide. A kept answer is held for 24 hours. After that the key is forgotten and a call with it runs again.

Rules

  • Only methods that change something use a key. A read-only method ignores the header completely: it runs every time, keeps nothing and never answers with a replay. Reads are always safe to repeat.
  • The token must hold the method's scope. Without it the key is ignored and the call is refused with the usual 403 naming the scope, so a token whose scopes were narrowed can never replay an answer it got before.
  • Same key, same request. A key reused with a different method, or with different arguments, is refused with a 422, the header Idempotency-Status: mismatch and the message "This Idempotency-Key was already used for a different tool or body!". Arguments are compared after they are read, so the order of the keys in your JSON and its spacing do not matter, but every value must be the same. Use a new key for new work.
  • A running call holds its key for 30 minutes. Until 30 minutes after the first call started, a repeat gets the 409, even when that call will never finish because the server restarted in the middle of it. After that, a repeat with the same method and arguments takes the key over and runs as a new attempt. For work that can take longer, read its state before repeating it.
  • Server failures keep their key. A call that failed with a 500 or above may have changed something before it failed, so its key is not released and a repeat gets the same failure back. Read the current state, then use a new key if the work still needs doing.
  • Large answers are not replayed. An answer bigger than 64 KB is not kept. A repeat of that call gets the original status code with data set to null and the message "This request already ran with this Idempotency-Key, and its result was too large to keep, so read the current state instead.", and it does not run again.
  • Credentials are never kept. A method that hands over a live credential, which needs the credentials:reveal scope, never has its answer stored. A repeat gets the original status code with data set to null and the message "This request already ran with this Idempotency-Key. Its result held a credential, so it was not kept. Read it again with the matching get method.", and it does not run again.
  • A bad key is refused. On a method that changes something, an empty key, or one longer than 255 characters or with spaces or other characters outside visible ASCII, gets a 400 with "The Idempotency-Key header must be 1 to 255 visible characters!".
  • Replays are free. A replayed answer does not run the method, is not logged, does not count against the token's per-minute budget and carries no X-Request-Id or rate-limit headers.

Telling the answers apart

The Idempotency-Status header says when the key, not the method, decided the answer:

Header value Status Meaning
replayed the original status The stored answer of the first call
running 409 The first call with this key has not finished
mismatch 422 The key was used before for a different method or arguments

A 409 or 422 without the header comes from the method itself, and its message says why. See Errors.

Which calls need a key

Every method's page says whether it only reads, makes changes, or is destructive. The same three facts are in GET /v1/tools and in the OpenAPI description, which lists the Idempotency-Key header only on methods that change something.

  • Reads are safe to repeat as they are, and ignore a key.
  • Changes that set a value end in the same state however many times they run, such as renaming a site or turning a scheduled job off. A repeat is harmless, though a key still saves the second call.
  • Changes that add something are the ones to protect: create_site, duplicate_site, clone_site, send_message, send_site_email, send_site_email_bulk, uploads with a unique file name, and anything else that creates a new item each time. Always send these with a key.

When the connection drops before an answer arrives, repeat the call with the same key. If the first attempt succeeded, you get its answer back. If it is still running, you get a 409 and wait. If it never arrived, it runs now. If it failed on the server, you get that failure back, and you read the current state before trying again with a new key.

A retry loop

import { randomUUID } from 'node:crypto'

const Wait = seconds => new Promise(resolve => setTimeout(resolve, seconds * 1000))

const Call = async (method, body, key = randomUUID()) => {
    for (let attempt = 1; attempt <= 5; attempt++) {
        let response

        try {
            response = await fetch(`https://api.modulify.ai/v1/${method}`, {
                method: 'POST',
                headers: {
                    Authorization: `Bearer ${process.env.MODULIFY_TOKEN}`,
                    'Idempotency-Key': key
                },
                body: JSON.stringify(body)
            })
        }

        catch {
            await Wait(attempt * 2)

            continue
        }

        if (response.status === 429) {
            await Wait(Number(response.headers.get('Retry-After') || 2))

            continue
        }

        if (response.status === 409 && response.headers.get('Idempotency-Status') === 'running') {
            await Wait(attempt * 2)

            continue
        }

        return await response.json()
    }

    throw new Error(`${method} did not complete after five attempts`)
}

The key is created once and reused on every attempt, which is what makes the loop safe. The loop repeats only when no answer arrived, when the token is over its call limit, or when the first call with the key is still running. Any other answer, including a 500, is returned to you, so you can read the current state before deciding what to do next.

Next