Idempotency
Send a request again safely with the Idempotency-Key header.
3 min read Updated
A request can go through and still look as if it failed: the server was ordered, but the answer never reached you because the connection dropped. Send
it again and you could order a second one. An Idempotency-Key makes sending a request again safe: whatever happens, it's done only once.
The header
Idempotency-Key: 6f0c6c0e-5d0b-4b53-9a7e-2f1a3a6d7b11
Every POST, PUT, PATCH and DELETE accepts one. A key is your own: 1 to 255
letters, digits and _ - : . (anything else answers 400 invalid_idempotency_key). A new UUID for each thing you mean
to do is the simplest good key.
Requests that spend money need one, and so do those that would do something else if they ran twice: without it they answer
400 idempotency_key_required.
These are all of them (the reference marks those that spend money, and shows the header as required on each):
| Operation | Request |
|---|---|
| Create a server | POST / |
| Resize a server | POST / |
| Turn on a site's malware protection | POST / |
| Choose where and how often a site is backed up | PUT / |
| Push the staging copy to the live site | POST / |
| Undo a push to the live site | POST / |
| Clone a site | POST / |
| Try a failed clone again | POST / |
| Turn on Media Offload for a site | POST / |
| Start a Media Offload operation on a site | POST / |
| Add a notice or reply address to a site's SMTP | POST / |
| Send an address's confirmation email again | POST / |
The samples make the key once, before the request, so a second try sends the same one:
# Keep this key when you send the same request again (after a timeout, say), so it's only done once.
KEY=$(uuidgen)
curl -X POST "https://api.rabbitflare.com/v1/servers" \
-H "Authorization: Bearer $RABBITFLARE_TOKEN" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: $KEY" \
-d '{
"name": "Production",
"cloud": "digitalocean",
"region": "fra1",
"planId": "business",
"site": {
"name": "Shop",
"siteTitle": "Example Shop",
"adminUsername": "editor",
"adminEmail": "[email protected]"
}
}' import { randomUUID } from "node:crypto";
// Keep this key when you send the same request again (after a timeout, say), so it's only done once.
const idempotencyKey = randomUUID();
const res = await fetch("https://api.rabbitflare.com/v1/servers", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.RABBITFLARE_TOKEN}`,
"Content-Type": "application/json",
"Idempotency-Key": idempotencyKey,
},
body: JSON.stringify({
"name": "Production",
"cloud": "digitalocean",
"region": "fra1",
"planId": "business",
"site": {
"name": "Shop",
"siteTitle": "Example Shop",
"adminUsername": "editor",
"adminEmail": "[email protected]"
}
}),
});
if (!res.ok) throw new Error(`Rabbitflare API error ${res.status}: ${await res.text()}`);
const { data } = await res.json();
console.log(data); import { Rabbitflare } from "@rabbitflare/api";
const rf = new Rabbitflare({ token: process.env.RABBITFLARE_TOKEN });
// The SDK sends an Idempotency-Key and keeps it when it sends the request again, so it's only done once.
const data = await rf.servers.create({
name: "Production",
cloud: "digitalocean",
region: "fra1",
planId: "business",
site: {
name: "Shop",
siteTitle: "Example Shop",
adminUsername: "editor",
adminEmail: "[email protected]",
},
});
console.log(data); <?php
// Keep this key when you send the same request again (after a timeout, say), so it's only done once.
$idempotencyKey = bin2hex(random_bytes(16));
$ch = curl_init('https://api.rabbitflare.com/v1/servers');
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 120,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('RABBITFLARE_TOKEN'),
'Content-Type: application/json',
'Idempotency-Key: ' . $idempotencyKey,
],
CURLOPT_POSTFIELDS => json_encode([
'name' => 'Production',
'cloud' => 'digitalocean',
'region' => 'fra1',
'planId' => 'business',
'site' => [
'name' => 'Shop',
'siteTitle' => 'Example Shop',
'adminUsername' => 'editor',
'adminEmail' => '[email protected]',
],
]),
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($body === false || $status >= 400) {
throw new RuntimeException("Rabbitflare API error $status: $body");
}
print_r(json_decode($body, true)['data']); import os
import uuid
import requests
# Keep this key when you send the same request again (after a timeout, say), so it's only done once.
idempotency_key = str(uuid.uuid4())
response = requests.post(
"https://api.rabbitflare.com/v1/servers",
headers={
"Authorization": "Bearer " + os.environ["RABBITFLARE_TOKEN"],
"Idempotency-Key": idempotency_key,
},
json={
"name": "Production",
"cloud": "digitalocean",
"region": "fra1",
"planId": "business",
"site": {
"name": "Shop",
"siteTitle": "Example Shop",
"adminUsername": "editor",
"adminEmail": "[email protected]",
},
},
timeout=120,
)
response.raise_for_status()
print(response.json()["data"]) Sending a request again
- The same key, the same request
-
The first answer comes back again, with the header
Idempotent-Replayed: true. Nothing runs a second time. The same request means the same operation, the same query and the same body, sent with the same token. - The same key, another request
-
422idempotency_key_reused: a key belongs to one request. Make a new key for new work. Another token of the account that sends the key gets this too: only the token that sent the first request gets its answer again. - While the first is still running
-
409idempotency_in_progress, withRetry-After. Wait, then send it again: you'll get the first request's answer. - When nothing ran
-
A request refused before the work started (a field at fault, a missing scope,
429), or answered with an error worth retrying (502, 503, 504,busyand the like): the key isn't kept, so you can send the same request with the same key again. For an operation that spends money the key stays this request's: send the same request again with it (a payment the first try made is found, never made twice), and use a new key for any other request. That's why a payment error is answered502billing_erroronly by the operations whose payments are known never to be taken twice (they're listed in Paying through the API); every other operation that spends money answers it with a500, below. - After any other refusal
-
It's kept with the key like any answer, so the same key gets the same refusal for 24 hours: a plan out of stock
(
plan_unavailable), a limit reached (limit_reached), a declined card (card_declined). Once you've fixed the cause, send the request with a new key. - After a
500 - The answer is kept, because the work may have happened (or did: the message says when a change went through, or a payment may have). Don't send it again with a new key: read the resource first, to see what was done.
How long keys last
A key belongs to the account, and is kept for 24 hours: send a request again within that time, with the same token, and it's done
once. While a request is still running, its key is held for as long as it runs, even when it waits many minutes for a server: the same key gets
409 idempotency_in_progress until it's done, then its answer. If a request stopped half-way on our side (during a restart, say), its key
is held for 5 minutes and can then be sent again.
A good key
- A new UUID for each new thing you mean to do: each server you order, each site you create.
- Kept with your own record of that work (a job, an order, a queue message), so a retry, even from another machine, sends the same key.
- Not the time, a counter or the same key for different requests: two different requests would then clash.
Still have a question?
Our team answers support tickets about the API, and other developers answer in the community.