Skip to content

Guide · Developer

PDF API error handling: retries, timeouts and idempotency

Handle PDF API errors in production: which statuses to retry, backoff with jitter, Retry-After, Idempotency-Key reuse, timeouts and tool results for agents.

Updated 20 min readSublimePDF Team

A PDF API call that works in development will eventually fail in production: a rate limit during a month-end invoice run, a dropped connection, a template that someone renamed, a payload an agent filled in wrongly. None of these should lose a document or produce two of them. This guide shows how to tell the failures apart, which ones to retry and how, and how to report the rest to your code, your logs and, if you use one, your AI agent.

It ends with a retry wrapper in TypeScript and Python that we ran through 13 failure scenarios against local mocks of the documented API. Download retry.ts or retry.py to use them directly.

Three kinds of failure

Every failed call falls into one of three groups, and each needs a different response:

  1. The request is wrong. Bad JSON, an unknown option, a missing field, a template ID that does not exist, a revoked key, a used-up monthly allowance. Sending the same request again gives the same answer. Fix it, or report it.
  2. The service is busy or briefly unavailable. Rate limits and server errors. The same request may well succeed shortly. Wait, then retry.
  3. There is no answer at all. A timeout or a dropped connection. You do not know whether the PDF was rendered. Retry, but in a way that cannot create a duplicate.

Status codes and what to do with them

All rows except the last two are statuses the API reference lists. The last two are not HTTP statuses at all: they are what your client sees when no response arrives.

StatusMeaningRetry?What to do
400Malformed request, unknown field or invalid option valueNoFix the request body; log it as a bug
401Missing, malformed or revoked API keyNoCheck the key; alert a person (see the authentication guide)
402Monthly document allowance used up (quota_exceeded)NoStop sending; wait for the 1st of the month (UTC) or change plan
403The key lacks the endpoint's scope (permission_error)NoUse a key with the right scope
404Template or job not found in this workspaceNoList templates and use an existing ID
409Same Idempotency-Key still running (code: idempotency_in_flight)YesWait for Retry-After, retry with the same key
409Other conflicts: job not finished, template version changedNoRe-read the job or template, then decide
410Stored result deleted or past retention (code: result_gone)NoRender again with a new Idempotency-Key
413Request body, HTML, data or upload too largeNoSend fewer rows, smaller inline images, or hosted image URLs
422Template data failed validation, render or PDF error, or a reused key with a different bodyNoCorrect the field or input named in the error
429Per-minute rate limit reachedYesWait for Retry-After, then retry with backoff
500Unexpected server errorYesRetry with backoff and the same Idempotency-Key
501Mode not available (for example lossy compression)NoUse a supported mode
503Rendering capacity or a dependency temporarily unavailableYesRetry with backoff and the same Idempotency-Key
TimeoutNo response in timeYesRetry with the same Idempotency-Key; the render may have happened
Connection errorReset, refused or DNS failureYesRetry with backoff; check your own network if it persists

Every error from the API has a JSON body in this shape:

{
  "error": {
    "type": "validation_error",
    "message": "data.customer.name is required.",
    "field": "data.customer.name",
    "request_id": "req_3d5Q9n2mJ8rT1vXy6bK0aZ"
  }
}

type is a stable category with one HTTP status each (validation_error, render_error, pdf_error and idempotency_error all use 422). code, when present, is a finer reason such as idempotency_in_flight, monthly_quota or result_gone. field is the dot path of the input to fix. request_id is also sent in the X-Request-Id header; log it, and quote it if you contact support. The message is for people: do not parse it.

Read type, code, message and field when they are present, but never depend on them. Your own proxy, a corporate gateway or a load balancer between you and any API can answer with a status that is not in the documented contract, such as 502 or 504, often with an HTML page. Treat those like 503, and make sure your code copes with a body that is not JSON. The wrappers below fall back to the status code and status text when the body is not JSON. One test sends exactly that HTML 502.

Retry with exponential backoff and jitter

Retrying immediately and repeatedly makes an overloaded service worse, especially when many of your workers hit the same error at the same moment and all retry in step. The usual remedy, described in the AWS Builders' Library article on retries, is exponential backoff with jitter: each wait is a random time between zero and a ceiling that doubles after every attempt.

With the wrapper defaults (500 ms base, 8 s cap, 4 attempts in total):

After attemptRandom wait between
10 and 0.5 s
20 and 1 s
30 and 2 s
4none, give up and report

Four attempts with these waits suit an interactive request, where a person or an agent is waiting. A background job that renders a nightly batch can afford more attempts and a higher cap, ideally by putting the job back on your queue rather than sleeping in a worker.

Also set an overall deadline. Retries multiply the worst case: four attempts with a 60-second timeout each is four minutes. The wrappers stop retrying once the next wait would pass the deadline (120 s by default).

Honour Retry-After

A 429 tells you to slow down, and the Retry-After header says for how long. RFC 9110 allows two forms: a number of seconds (Retry-After: 7) or an HTTP date (Retry-After: Sun, 22 Nov 2026 12:00:05 GMT). Parse both, wait at least that long, and keep the jitter so your workers do not all return in the same instant.

Then put a limit on it. If the server asks you to wait two minutes while a user watches a spinner, waiting is the wrong answer. The wrappers give up immediately when Retry-After exceeds 30 seconds and return a retryable error, so the caller can queue the job or tell the user to try again shortly. In the tests, Retry-After: 120 ended the call after one attempt in 2 ms instead of blocking for two minutes.

SublimePDF's per-minute limit currently answers with Retry-After: 60, so with the default 30-second ceiling the wrappers return a retryable error at once instead of waiting. That is deliberate for interactive calls. A background worker that would rather wait can raise maxRetryAfterMs (max_retry_after in Python) above 60 seconds.

A 402 is different: the monthly allowance is used up, and no amount of waiting within the month changes that. Do not retry it; stop the batch and alert someone.

Retrying is a fallback, not a capacity plan. If you see sustained 429 responses, spread the work out: a queue with a fixed number of workers, sized below your plan's per-minute limit, is better than many processes retrying. Per-minute limits by plan are on the pricing page.

Use one Idempotency-Key per document

The dangerous case is the third group: a timeout or a dropped connection after the request was sent. The server may have rendered the PDF and counted it, and the response was lost on the way back. A plain retry would render it again.

The API accepts an optional Idempotency-Key header for this. The rules that make it work:

  • Generate one key per logical document, for example a UUID when you decide to create invoice 1042, not one per HTTP request.
  • Send the same key on every retry of that document.
  • Use a new key when the request changes. If an agent corrects a field after a 422, that is a different document request.
  • Store the key with your job record if the work can outlive the process. A worker that crashes and restarts should retry with the key it saved, not a new one.

The IETF is standardising this header pattern in an Internet-Draft, but what a given API does with a repeated key is up to that API. SublimePDF applies these rules, per workspace, on render and PDF-operation requests:

You send the key again andYou get
The first request succeededThe stored PDF again, byte for byte, with Idempotent-Replayed: true. It is not counted again, even if the monthly allowance has since run out
The first request is still running409, code: idempotency_in_flight, Retry-After: 2. Wait and retry with the same key
The first request failed with a 5xxThe request runs again on the same job
The first request failed with a 4xxThe same error again, without running. Fix the request and use a new key
The body is different422, type: idempotency_error. A key belongs to one request body
The stored result was deleted or expired410, code: result_gone. Use a new key

Results are stored for a retention period, 24 hours by default, so a replay works within that window. Keep your own record of which documents were generated as well; the key protects against duplicates, it is not your system of record.

The in-flight case matters after a client-side timeout: your retry can arrive while the first render is still running. The wrappers below were written before the API returned 409 for this and treat every 409 as final. To wait and retry instead, add this check in the TypeScript wrapper right after lastError = await toApiError(res);:

if (res.status === 409 && res.headers.get("retry-after")) {
    // idempotency_in_flight: the first request with this key is still running
    lastError.retryable = true;
    waitMs = parseRetryAfter(res.headers.get("retry-after"));
}

Only the in-flight conflict carries Retry-After; other 409 responses stay non-retryable. In the Python wrapper, add the same check in the except urllib.error.HTTPError as e: branch, after the 429 check:

            if e.code == 409 and e.headers.get("Retry-After"):
                error["retryable"] = True  # idempotency_in_flight
                wait = parse_retry_after(e.headers.get("Retry-After"))

We applied both changes to copies of the downloadable files and ran them against a stub server: a 409 with Retry-After was retried with the same key, and a 409 without it ended the call as a non-retryable error. The TypeScript version still type-checks under tsc --strict. The 13 scenarios in the table further down were run before these changes.

We tested the pattern with a mock that renders slowly the first time it sees a key and replays the result for a key it has already rendered. With a 1-second timeout:

Client behaviourRequestsRenders on the mock
Wrapper: timeout, then retry with the same key21
Naive client: a fresh key on its second try22

The mock replays immediately rather than answering 409 while the first render runs. It shows that the client sends what it should; the API's own test suite covers the replay, in-flight and mismatch cases against a local test database, but not yet against the deployed service.

Set timeouts deliberately

Without a timeout, a request can hang until the operating system gives up, which may be minutes. Set two:

  • Per attempt. Long enough for your largest real document to render. A one-page invoice and a 60-page report take very different times, so measure your own templates against your account and set the timeout well above the slowest result you see. The API stops a render after 45 seconds, so the wrappers' 60-second default leaves room for the upload and the response.
  • Overall. The total time you are willing to spend, retries included.

A timeout is not proof of failure. Always retry it with the same Idempotency-Key. For documents that take long to render, or batches you do not need to wait for, the webhooks guide covers asynchronous delivery with webhook_url.

The retry wrapper

renderWithRetry sends one render request with the rules above and always returns a result object instead of throwing on API errors. It works for POST /html-to-pdf and POST /templates/{id}/generate. This is the complete file, also available as retry.ts. It type-checks under tsc --strict and runs directly as a .ts file on Node.js 22.18 or later:

/**
 * Retry wrapper for SublimePDF render calls, as published in /guides/pdf-api-error-handling.
 * Node.js 22.18+ (runs as .ts via type stripping), no dependencies.
 */
import { randomUUID } from "node:crypto";
 
export interface ApiError {
    status: number | null; // null = no HTTP response (timeout, connection error)
    type: string;
    message: string;
    field?: string;
    retryable: boolean;
}
export type RenderResult =
    | { ok: true; pdf: Buffer; attempts: number; idempotencyKey: string }
    | { ok: false; error: ApiError; attempts: number; idempotencyKey: string };
 
export interface RetryOptions {
    apiKey?: string;
    baseUrl?: string;
    maxAttempts?: number; // total tries, including the first
    baseDelayMs?: number; // first backoff step
    maxDelayMs?: number; // cap for one backoff step
    maxRetryAfterMs?: number; // give up instead of waiting longer than this
    attemptTimeoutMs?: number; // per request
    deadlineMs?: number; // whole operation, all retries included
    idempotencyKey?: string; // pass your own to make retries span process restarts
    log?: (event: Record<string, unknown>) => void;
}
 
const RETRYABLE = new Set([429, 500, 502, 503, 504]);
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
 
/** Retry-After is either delay-seconds or an HTTP-date (RFC 9110, section 10.2.3). */
export function parseRetryAfter(value: string | null, now = Date.now()): number | null {
    if (!value) return null;
    if (/^\d+$/.test(value.trim())) return Number(value) * 1000;
    const date = Date.parse(value);
    return Number.isNaN(date) ? null : Math.max(0, date - now);
}
 
/** "Full jitter": a random delay between 0 and the exponential step. */
const backoff = (attempt: number, base: number, cap: number) => Math.random() * Math.min(cap, base * 2 ** (attempt - 1));
 
async function toApiError(res: Response): Promise<ApiError> {
    let body: any = null;
    try {
        body = await res.json();
    } catch {
        // not JSON, e.g. an HTML page from a proxy
    }
    const e = body?.error ?? {};
    return {
        status: res.status,
        type: typeof e.type === "string" ? e.type : `http_${res.status}`,
        message: typeof e.message === "string" ? e.message : res.statusText || `HTTP ${res.status}`,
        ...(typeof e.field === "string" ? { field: e.field } : {}),
        retryable: RETRYABLE.has(res.status),
    };
}
 
export async function renderWithRetry(path: string, body: unknown, opts: RetryOptions = {}): Promise<RenderResult> {
    const {
        apiKey = process.env.SUBLIMEPDF_API_KEY,
        baseUrl = process.env.SUBLIMEPDF_API_BASE_URL ?? "https://api.sublimepdf.com/v1",
        maxAttempts = 4,
        baseDelayMs = 500,
        maxDelayMs = 8_000,
        maxRetryAfterMs = 30_000,
        attemptTimeoutMs = 60_000,
        deadlineMs = 120_000,
        idempotencyKey = randomUUID(), // one key per logical render, reused by every retry
        log = () => {},
    } = opts;
    if (!apiKey) throw new Error("SUBLIMEPDF_API_KEY is not set");
    const started = Date.now();
    let lastError: ApiError = { status: null, type: "not_attempted", message: "No attempt made", retryable: false };
    let attempt = 0;
 
    while (++attempt <= maxAttempts) {
        let waitMs: number | null = null;
        try {
            const res = await fetch(`${baseUrl}${path}`, {
                method: "POST",
                headers: {
                    Authorization: `Bearer ${apiKey}`,
                    "Content-Type": "application/json",
                    Accept: "application/pdf",
                    "Idempotency-Key": idempotencyKey,
                },
                body: JSON.stringify(body),
                signal: AbortSignal.timeout(Math.min(attemptTimeoutMs, deadlineMs - (Date.now() - started))),
            });
            if (res.ok) {
                const pdf = Buffer.from(await res.arrayBuffer());
                log({ attempt, status: res.status, outcome: "success", idempotencyKey });
                return { ok: true, pdf, attempts: attempt, idempotencyKey };
            }
            lastError = await toApiError(res);
            if (res.status === 429) waitMs = parseRetryAfter(res.headers.get("retry-after"));
        } catch (e: any) {
            const timedOut = e?.name === "TimeoutError";
            lastError = {
                status: null,
                type: timedOut ? "timeout" : "network_error",
                message: timedOut ? "No response before the timeout. The render may still have run." : String(e?.cause?.code ?? e?.message ?? e),
                retryable: true,
            };
        }
        log({ attempt, status: lastError.status, type: lastError.type, retryable: lastError.retryable, idempotencyKey });
        if (!lastError.retryable || attempt === maxAttempts) break;
 
        const delay = Math.max(waitMs ?? 0, backoff(attempt, baseDelayMs, maxDelayMs));
        if ((waitMs ?? 0) > maxRetryAfterMs || Date.now() - started + delay >= deadlineMs) {
            log({ attempt, outcome: "give_up", reason: "wait exceeds budget", waitMs: Math.round(delay) });
            break;
        }
        await sleep(delay);
    }
    return { ok: false, error: lastError, attempts: Math.min(attempt, maxAttempts), idempotencyKey };
}

Use it from a script in the same folder. This one renders the sample invoice: download template.html and data.json, set SUBLIMEPDF_API_KEY, and run node render-invoice.ts. It sends the HTML with the data, or, when SUBLIMEPDF_TEMPLATE_ID is set, the data alone to your saved copy of the template:

// render-invoice.ts
import { readFile, writeFile } from "node:fs/promises";
import { renderWithRetry } from "./retry.ts";
 
const data = JSON.parse(await readFile("data.json", "utf8")); // { seller, customer, invoice, items, ... }
const templateId = process.env.SUBLIMEPDF_TEMPLATE_ID;
const [path, body] = templateId
    ? [`/templates/${encodeURIComponent(templateId)}/generate`, { data }]
    : ["/html-to-pdf", { html: await readFile("template.html", "utf8"), data }];
 
// One key per logical document. Store it with your job record if a retry can happen after a restart.
const idempotencyKey = `invoice-${data.invoice.number}`;
 
const result = await renderWithRetry(path, body, {
    idempotencyKey,
    log: (event) => console.error(JSON.stringify({ ...event, document: data.invoice.number })),
});
 
if (result.ok) {
    await writeFile("invoice.pdf", result.pdf);
    console.log(`Saved invoice.pdf after ${result.attempts} attempt(s)`);
} else if (result.error.retryable) {
    console.error(`Temporary failure (${result.error.type}). Queue the job and retry later with key ${idempotencyKey}.`);
    process.exitCode = 75;
} else {
    console.error(`Request needs fixing: ${result.error.message}${result.error.field ? ` (field ${result.error.field})` : ""}`);
    process.exitCode = 1;
}

The Python version has the same behaviour and the same defaults using only the standard library (urllib, Python 3.8 or later). Save it as retry.py next to this script:

# render_invoice.py
import json
import os
import sys
 
from retry import render_with_retry
 
with open("data.json", encoding="utf-8") as f:
    data = json.load(f)  # { seller, customer, invoice, items, ... }
 
template_id = os.environ.get("SUBLIMEPDF_TEMPLATE_ID")
if template_id:
    path, body = f"/templates/{template_id}/generate", {"data": data}
else:
    with open("template.html", encoding="utf-8") as f:
        path, body = "/html-to-pdf", {"html": f.read(), "data": data}
 
key = f"invoice-{data['invoice']['number']}"  # one key per logical document
result = render_with_retry(path, body, idempotency_key=key,
                           log=lambda event: print(json.dumps(event), file=sys.stderr))
 
if result["ok"]:
    with open("invoice.pdf", "wb") as f:
        f.write(result["pdf"])
    print(f"Saved invoice.pdf after {result['attempts']} attempt(s)")
elif result["error"]["retryable"]:
    sys.exit(f"Temporary failure ({result['error']['type']}). Retry later with key {key}.")
else:
    sys.exit(f"Request needs fixing: {result['error']['message']}")

What we tested

Both wrappers ran through the same 13 scenarios: five against the mock that ships with the agent quickstart (success, 422, 404, a single 503 and a constant 429) and eight against a small scenario mock written for this guide. Backoff steps were shortened to a 50 ms base for the test run. Retry-After waits were real. TypeScript and Python gave the same outcomes on Node.js 24.5 and Python 3.9.6:

ScenarioAttemptsResult
Valid invoice data1PDF
422, missing report fields1Error, not retried
404, unknown template1Error, not retried
422 with field: "customer.name"1Error with field, not retried
503 once, then success2PDF
503, 503, then success3PDF
500 every time4Error, retryable
429 every time with Retry-After: 14Error after about 3 s
429 with an HTTP-date Retry-After2PDF after waiting for the date
429 with Retry-After: 1201Error at once, retryable (wait exceeds 30 s)
Connection reset, then success2PDF
502 with an HTML body, then success2PDF; the error parsed as http_502
Timeout (1 s) on a slow render, then replay2PDF, one render on the mock

Every retry in every scenario carried the same Idempotency-Key as the first attempt. We also ran render-invoice.ts and render_invoice.py against the quickstart mock in HTML mode and with template IDs invoice (saved), flaky (one 503, then a PDF on the second attempt) and an unknown ID (404, reported as a request to fix, exit code 1). These are client-path tests against mocks of the documented contract. Before going live, check the non-retryable statuses against your own account with a deliberately wrong template ID and an incomplete payload.

Validate before you send

The cheapest error is the one you never send. Most 400, 404, 413 and 422 responses can be caught on your side:

  • Data: validate the payload against a JSON Schema for the template. The template variables guide shows one, with the error messages it produces.
  • Template IDs: keep an allow-list, or cache the result of GET /templates and check against it.
  • Size: cap the number of line items and the length of free text, and reference hosted images instead of inlining large base64 data.
  • Options: keep options in your code, not in user or model input.

Errors in AI agent tools

When a model calls a PDF tool, errors are part of the conversation. The agent quickstart shows the full executor; three rules carry over from this guide:

  • The executor retries transient errors, not the model. Run renderWithRetry inside the tool. If the model sees a 503 and calls the tool again, that is a new tool call with a new key, and possibly a second document.
  • Return failures as tool results with a clear next step. Pass retryable, the field and a plain instruction: correct this field and call once more; or ask the user; or stop and report. A 402 should always be "stop and report": the account is out of documents for the month. The model cannot act on an exception that ends the conversation.
  • Bound the loop. Cap tool calls per conversation, and stop after one corrected retry of a 422. A model that keeps adjusting a payload can spend renders as quickly as a retry loop.

For documents sent to customers, add a human confirmation step before anything leaves your system. It catches the errors no status code will report, such as a correct-looking invoice with the wrong customer.

Log enough to debug, nothing more

Log one structured line per attempt: time, endpoint, template ID, your job or document ID, attempt number, status, error type, code and field, the request_id (or X-Request-Id header), latency and the Idempotency-Key. With those you can answer "what happened to invoice 1042?" months later.

Do not log the API key or the Authorization header, PDF bytes, or full request data when it contains personal information. Log the field name from a 422, not the value.

Alert on patterns, not single errors: any 401 or 403 in production (a key problem), any 402 (the monthly allowance is used up), a sustained share of 429 responses (you need a queue or a larger plan), and a rising 5xx or timeout rate.

Checklist

  • 4xx responses other than 429 and an in-flight 409 are never retried unchanged; 402 stops the batch.
  • 429, 5xx, timeouts and connection errors are retried with capped exponential backoff and jitter.
  • Retry-After is honoured in both forms, and long waits are handed back to the caller or queue.
  • Each document has one Idempotency-Key, stored with the job and reused for every retry.
  • Each attempt has a timeout, and the whole operation has a deadline.
  • Error parsing falls back to the status code when the body is not JSON.
  • Payloads, template IDs and sizes are validated before sending.
  • Agents receive errors as tool results, and retries happen in the executor.
  • Logs contain IDs, statuses and fields, never keys or document contents.

Sources

  1. RFC 9110: HTTP Semantics (section 10.2.3 Retry-After) · accessed 23 November 2026
  2. RFC 6585: Additional HTTP Status Codes (429 Too Many Requests) · accessed 23 November 2026
  3. AWS Builder Center (Builders' Library): Timeouts, retries, and backoff with jitter · accessed 23 November 2026
  4. IETF draft-ietf-httpapi-idempotency-key-header-09: The Idempotency-Key HTTP Header Field (active Internet-Draft) · accessed 23 November 2026

Generate your first PDF with one API call.

Create an account, copy an API key and send HTML, or a template ID with JSON data, from your code or your agent.