DEV Community

Muthu kumaran
Muthu kumaran

Posted on

Why your PDF step runs twice: idempotency keys, batch retries and template versions

A webhook fires. Your workflow calls a PDF API, the call times out, and the workflow retries. Now there are two invoices with the same number, and one of them is already in the customer's inbox.

Most webhook senders deliver at least once. Many HTTP clients retry on timeouts, and tools such as n8n can retry a failed step. The PDF step is where those retries turn into something a customer can see, so the API behind it has to make a retry safe.

Disclosure: I built Docspout, a PDF API. The first half of this post is the pattern, and it applies to any document API. The second half shows how Docspout does it, with curl and Node you can paste.

The pattern: four rules

1. The client sends an idempotency key, and the key means "this one document"

The client picks a key that names the business event, not the HTTP attempt. order-1182 is a good key. A random UUID made fresh on each attempt is useless, because every retry looks new.

The server stores the key with a pointer to the document it created. When the same key arrives again, it returns that document and says so in a response header, so your logs show replays.

Two details matter more than they look:

  • Concurrent retries. If the retry lands while the first request is still running, the second must wait and return the first one's result. Check-then-insert has a race window. Insert the key in the same transaction that creates the job, and let a unique index make the second request wait.
  • Billing follows the document. Three attempts with one key count as one document.

2. Same key with a different body is an error, not a replay

If the key matches but the body does not, the server must refuse with 409 Conflict. Returning the old document would hide a real bug: the client thinks it sent new data and got a PDF of the old data.

To compare bodies, the server stores a hash of the request next to the key. The hash is usually taken over serialized JSON, so the same fields in a different key order can produce a different hash and a 409. Build the body the same way on every attempt.

3. A failed batch row is retried by row, not by resubmitting the batch

Batches break rule 1. One key covers the whole batch, and individual rows have no key of their own. If row 412 of 2,000 fails because a customer name is missing, resubmitting the batch either replays the old result (same key) or renders 1,999 documents a second time (new key).

The fix is a separate retry operation that re-queues only failed rows, optionally with corrected data. Run it twice and the second call re-queues nothing, because no rows are failed any more. The retry is idempotent without a key.

4. Every job is pinned to an immutable template version

Someone may publish a new template between the first attempt and the third. If the retry renders against it, the "same" document comes out different, or fails because the new template expects a field the old data lacks.

So each publish should create a new numbered version that never changes. Each job records its version, and the worker renders exactly that. Callers can pin a version. Callers who do not pin get the version published when the request arrived, for the life of that job.

How Docspout implements this

Docspout templates are built from blocks in an editor, not HTML. You publish a template once, then send JSON to POST /v1/renders and get a PDF back. Here is a render with an idempotency key. An sk_test_ key stamps the PDF with TEST and never counts against your plan, so this is safe to run while you experiment.

curl https://docspout.com/v1/renders \
  -H "Authorization: Bearer sk_test_…" \
  -H "Idempotency-Key: order-1182" \
  -H "Content-Type: application/json" \
  -d '{
  "template": "tpl_your_template",
  "data": {
    "number": "INV-1182",
    "customer": { "name": "Acme GmbH", "email": "ap@acme.de" },
    "items": [{ "description": "Brand identity design", "qty": 1, "price": 1200 }]
  }
}'
Enter fullscreen mode Exit fullscreen mode

The response JSON includes the render id and its status. url is set once status is succeeded, and is null while the render is running or if it failed. By default the server waits up to 25 seconds. If it is still queued or rendering after that, you get 202 and can poll GET /v1/renders/:id or pass a webhook_url.

Send the same command again and you get the same render back, with the header Idempotent-Replayed: true. The status follows the original: 200 if it finished, 202 if still queued or rendering, 422 if it failed. If two copies arrive at once, the second waits for the first and returns its render. One PDF is made, and on a live key only one counts.

Here is the same flow in Node, using only the built-in fetch (Node 18 or later):

const KEY = process.env.DOCSPOUT_KEY; // an sk_test_ key while you try this

async function render(idempotencyKey, data) {
  const res = await fetch("https://docspout.com/v1/renders", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${KEY}`,
      "Idempotency-Key": idempotencyKey,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ template: "tpl_your_template", data }),
  });
  const body = await res.json();
  console.log(res.status, res.headers.get("idempotent-replayed"), body.error?.code ?? body.id);
  return body;
}

const invoice = {
  number: "INV-1182",
  customer: { name: "Acme GmbH", email: "ap@acme.de" },
  items: [{ description: "Brand identity design", qty: 1, price: 1200 }],
};

await render("order-1182", invoice); // first attempt: a new render
await render("order-1182", invoice); // retry: same render id, replayed = "true"
await render("order-1182", { ...invoice, number: "INV-1183" }); // 409 idempotency_conflict
Enter fullscreen mode Exit fullscreen mode

Save it as retry.mjs and run DOCSPOUT_KEY=sk_test_… node retry.mjs. The JSON in data must match the fields your published template expects; the editor lists any that are missing. The third call shows rule 2. The key was used with a different body, so the API answers 409 with the code idempotency_conflict. Docspout hashes the parsed request as serialized JSON and does not sort keys inside data, so a retry that only reorders fields in data also gets 409.

Gotcha: after you fix bad data, send a new key

Docspout checks data against the template's field list before anything is queued. A missing field returns 422 missing_field with the paths that are missing, for example ["customer.name"]. A wrong type returns 422 wrong_type.

That failed render stays tied to your key. Fix the data, resend with the same key, and you get 409, because the body changed. When you change the body after a failure, change the key too, for example order-1182-fix1.

The failure costs nothing. Usage only goes up when a live render succeeds. Failed validation, failed renders and test-key renders never count, and nothing is reserved up front, so there is nothing to refund.

Limit: keys last 24 hours

Docspout keeps idempotency keys for 24 hours, then a cleanup job deletes them. After that, the same key is treated as new. A retry that arrives more than a day later makes and counts a second PDF.

Webhook and workflow retries usually happen within minutes or hours. If your system can replay events days later, from a dead-letter queue for example, keep your own record of which orders already have a PDF and check it first. No server-side key window replaces that.

Batch retries

POST /v1/batches takes up to 10,000 rows, depending on the plan, and returns 202 with a batch id. The whole batch accepts an Idempotency-Key, with the same replay and 409 rules as a single render.

For failed rows, call the retry endpoint. Rows are numbered from 0, so the 412th row is 411. You can send corrected data for the rows you fixed:

curl https://docspout.com/v1/batches/BATCH_ID/retry \
  -H "Authorization: Bearer sk_test_…" \
  -H "Content-Type: application/json" \
  -d '{ "rows": [{ "row": 411, "data": {
    "number": "INV-2411",
    "customer": { "name": "Acme GmbH", "email": "ap@acme.de" },
    "items": [{ "description": "Brand identity design", "qty": 1, "price": 1200 }]
  } }] }'
Enter fullscreen mode Exit fullscreen mode

The response reports how many rows were re-queued. A second call reports 0.

If a Docspout worker dies mid-batch, its rows go back to the queue and finish on another worker. I tested this by killing a worker partway through a 100-row batch, and nothing was lost or counted twice. The raw log is at docspout.com/proof/batch-recovery-run.txt.

Pinning a template version

Each publish in Docspout creates a new numbered version that never changes, with its own field list. Render and batch requests accept an optional version next to template:

{ "template": "tpl_your_template", "version": 3, "data": { …same invoice data as above… } }
Enter fullscreen mode Exit fullscreen mode

Without version, a request uses the version published when it arrived. The render stores that version and the worker loads exactly it, so a later publish cannot change a job in flight or being retried.

Editing the draft changes nothing until you publish. After you publish a version that adds a required field, unpinned requests that lack it fail with 422 before anything renders, and nothing counts. Requests pinned to the old version keep working. If several workflows share one template, pin each one and move it to the new version when its data is ready.

A checklist for any document API

Before you turn on retries, on Docspout or any other document API, check these four things:

  1. Does it accept an idempotency key, and does a replay return the original document?
  2. Does a changed body with the same key fail loudly, with a 409, instead of returning the old document?
  3. Can you retry only the failed rows of a batch, and is that retry safe to run twice?
  4. Is each job pinned to a template version that a later publish cannot change?

If the answer to any of them is no, add the missing piece on your side before the first retried webhook reaches a customer.

The API reference is at docspout.com/docs. I'm Muthu, building this alone from Chennai. If you have shipped a document pipeline and hit a retry case these four rules miss, I would like to hear it in the comments.

Top comments (0)