Retries & Idempotency
A request can time out after SyncBooks has already done the work, for example on a slow mobile connection. Retry it blindly and you get a second invoice or a second payment. Send an Idempotency-Key and a retry returns the first answer instead.
How it works
Request
curl -X POST https://api.syncbooksapp.com/api/v1/invoices \
-H "Authorization: Bearer sk_live_your_key" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: 3f6c1d2e-8b7a-4c55-9a10-2d4e6f8a0b1c" \
-d '{ "customerId": "65f1a2b3c4d5e6f7a8b9c0d1", "lineItems": [{ "description": "Consulting", "quantity": 1, "rate": 1500 }] }'- Works on every
POSTandPATCHof the API.GET,PUTandDELETEare safe to repeat already. - The first request with a key does the work; its answer is kept for 24 hours.
- The same key again, with the same request, returns that answer (same status, same body) with the header
Idempotent-Replayed: true. Nothing is done twice. - Keys belong to one company: two companies can use the same key without meeting.
- Answers that mean "try again" (
429and5xx) aren't kept, so retrying with the same key really does retry.
Choosing keys
| Parameter | Type | Description |
|---|---|---|
Idempotency-Key | header | 1–255 printable characters. A new UUID per operation, or a reference from your own system (order-7781). |
Make the key mean this operation: create it when the user presses "Create invoice", keep it with the pending operation, and reuse it for every retry of that operation. A new operation gets a new key.
When a key is refused
| Parameter | Type | Description |
|---|---|---|
422 idempotency_key_reused | error | The key was used for a different request (another path or body). Use a new key. |
409 idempotency_in_progress | error | The first request with this key is still running. Retry in a second with the same key. |
400 invalid_idempotency_key | error | The key is empty, too long or has spaces or other characters outside printable ASCII. |
A retry loop
JavaScript
async function createInvoice(invoice) {
const key = crypto.randomUUID(); // one key for this invoice, reused on every retry
for (let attempt = 1; ; attempt++) {
const res = await fetch("https://api.syncbooksapp.com/api/v1/invoices", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.SYNCBOOKS_API_KEY}`,
"Content-Type": "application/json",
"Idempotency-Key": key,
},
body: JSON.stringify(invoice),
}).catch(() => null); // network error: retry
if (res && res.status < 500 && res.status !== 429 && res.status !== 409) return res.json();
if (attempt === 5) throw new Error(`Gave up (request ${res?.headers.get("X-Request-Id") ?? "not sent"})`);
const wait = Number(res?.headers.get("Retry-After")) || 2 ** attempt;
await new Promise((r) => setTimeout(r, wait * 1000));
}
}Request IDs
Every response, success or error, carries an X-Request-Id header (errors also have it as request_id). Log it with each call: quoting it lets us find exactly that request when you contact support.