Api2Pdf in Production: Timeouts, Retries, Idempotency and Background PDF Jobs

Summary. The first Api2Pdf call takes five minutes to write. The version that survives month-end invoicing, a flaky network and a deploy in the middle of a batch takes a little more thought. A PDF render is a slow, paid, synchronous HTTP call, and that combination breaks the defaults most HTTP code is written with: a 10 second timeout cuts off a large report, a naive retry loop renders the same invoice three times, and a render inside a web request ties up a worker while the user stares at a spinner. This post covers the patterns that fix that, language-agnostic in design and shown in Python: a timeout budget that matches the platform limits, retries that only fire when they can help, idempotency keys you own (because a conversion API cannot know that two requests mean the same invoice), a background job table on Postgres with FOR UPDATE SKIP LOCKED, delivery straight into S3 with useCustomStorage, an automatic fallback to the XL tier for documents that outgrow 90 seconds, and a signed webhook so the rest of your system knows when a PDF is ready.

The code is about 300 lines in total. It was run against a mocked Api2Pdf transport and a local Postgres 17 (15 tests, included below), not against a live API key, so treat the numbers in the comments as the documented limits rather than benchmarks. For framework-specific versions of the client, see the FastAPI, Node.js, Go and ASP.NET Core guides.

The facts you design around

Every pattern below follows from a handful of properties of the API. They are worth stating up front, because most production incidents with any document API come from guessing one of them wrong:

  • Requests are synchronous. POST https://v2.api2pdf.com/chrome/pdf/html returns when the PDF exists. There is no job id to poll and no webhook callback from Api2Pdf. If you want asynchronous behaviour, and for anything user-facing beyond a one-page invoice you do, you build it on your side. That is most of this post.
  • Each request gets 90 seconds and 2 GB of memory on the standard v2.api2pdf.com host. v2-xl.api2pdf.com gives a request 4 CPUs, 8 GB and 5 minutes, at 10x the price. Same paths, same JSON, different host.
  • No rate limits. Api2Pdf does not throttle you, so your concurrency limit is whatever you choose. Choose one anyway: it is what keeps your own memory, connection pool and bill predictable.
  • Errors are JSON, even for binary requests. Every response, success or failure, has Success, Error, FileUrl, ResponseId, MbOut, Seconds and Cost. A bad key is 401 with "Error": "Invalid API key"; a malformed body is 400. A 200 with "Success": false is still a failure.
  • A missing Authorization header is a 402, not a 401. Requests without a key get an x402 payment challenge (a JSON body with x402Version and an accepts list) so that AI agents can pay per call. In your backend it almost always means an unset environment variable. Never retry it; fail at startup instead.
  • Hosted files live for 24 hours. FileUrl is a temporary download link, not storage. Copy the file somewhere you own (or let Api2Pdf PUT it there with useCustomStorage), and call DELETE /file/{responseId} when you want it gone sooner.
  • Billing is per compute second and per MB out. A retried render is a second render. Cheap, usually a fraction of a cent, but it is why retries and idempotency belong together.

Pattern 1: a timeout budget, not a timeout

A single number like timeout=30 is the most common bug in PDF integrations. HTTP clients usually apply it to each phase or to the whole call, and either way 30 seconds is shorter than the 90 seconds Api2Pdf allows a render. Split it by phase instead:

  • Connect: 10 seconds. If you cannot open a TLS connection in 10 seconds, waiting longer will not help, and a fast failure lets the retry loop try a fresh connection.
  • Read: 120 seconds on v2, 330 on XL. That is the platform limit plus headroom for uploading the HTML and downloading the result. Shorter than the limit and you abandon renders that would have succeeded, and still pay for them.
  • An overall deadline per job. Retries multiply the read timeout. The job runner below passes a monotonic deadline into the client, and the client will not start a backoff sleep that would cross it. The deadline is set 60 seconds inside the job lease, so a job is never picked up by a second worker while the first is still waiting on Api2Pdf.

Web requests are the other half of the budget. If a user clicks Download, a 90-second render cannot sit inside a request that your load balancer kills at 30 or 60 seconds. Keep synchronous rendering for small documents you know finish in a couple of seconds (an invoice streamed with ?outputBinary=true), and put everything else on a queue (Pattern 4).

Pattern 2: retries that only fire when they can help

Retrying is correct for exactly two kinds of failure: the network (DNS, connection resets, timeouts) and server-side or capacity statuses (408, 429, 500, 502, 503, 504). Everything else fails the same way every time: a 400 for broken JSON, a 401 for a wrong key, a 402 for a missing one, or a 200 with Success: false because a source URL could not be fetched. Retrying those just delays the error and adds load.

The backoff is exponential with full jitter (a random delay between zero and the cap), which stops a fleet of workers that failed together from retrying together. If a response carries Retry-After, it wins. Here is the whole client, using httpx:

# pdfjobs/api2pdf_client.py
"""A small Api2Pdf client with timeouts, retries and one error type."""
import random
import time

import httpx

V2 = "https://v2.api2pdf.com"
V2_XL = "https://v2-xl.api2pdf.com"  # 4 CPU, 8 GB, 5 minute limit, 10x price

RETRYABLE_STATUS = {408, 429, 500, 502, 503, 504}


class Api2PdfError(Exception):
    def __init__(self, message, *, op, status=None, response_id=None, retryable=False,
                 timed_out=False, retry_after=None):
        super().__init__(f"{op}: {message}")
        self.op = op
        self.status = status
        self.response_id = response_id
        self.retryable = retryable
        self.timed_out = timed_out or status == 504
        self.retry_after = retry_after


class Api2Pdf:
    def __init__(self, api_key, *, base_url=V2, max_attempts=4, base_delay=0.5,
                 max_delay=20.0, transport=None, sleep=time.sleep):
        if not api_key:
            # Without an Authorization header Api2Pdf answers 402 with an x402
            # payment challenge. Fail at startup instead.
            raise ValueError("API2PDF_API_KEY is not set")
        read = 330.0 if base_url == V2_XL else 120.0
        self.http = httpx.Client(
            base_url=base_url,
            headers={"Authorization": api_key},  # the raw key, no "Bearer"
            timeout=httpx.Timeout(connect=10.0, read=read, write=30.0, pool=10.0),
            transport=transport,
        )
        self.max_attempts = max_attempts
        self.base_delay = base_delay
        self.max_delay = max_delay
        self.sleep = sleep

    # ---- endpoints -------------------------------------------------------

    def html_to_pdf(self, html, *, file_name=None, options=None, storage=None,
                    binary=False, deadline=None):
        body = {"html": html, "inline": False}
        if file_name:
            body["fileName"] = file_name
        if options:
            body["options"] = options
        if storage:
            body["useCustomStorage"] = True
            body["storage"] = storage  # {"method": "PUT", "url": ..., "extraHTTPHeaders": {...}}
        return self._call("POST", "/chrome/pdf/html", body, binary=binary, deadline=deadline)

    def delete_file(self, response_id):
        return self._call("DELETE", f"/file/{response_id}")

    def balance(self):
        return self._call("GET", "/balance")

    # ---- plumbing --------------------------------------------------------

    def _call(self, method, path, body=None, *, binary=False, deadline=None):
        op = f"{method} {path}"
        params = {"outputBinary": "true"} if binary else None
        for attempt in range(1, self.max_attempts + 1):
            try:
                resp = self.http.request(method, path, json=body, params=params)
                return self._parse(op, resp, binary)
            except httpx.TransportError as exc:  # DNS, connect, read timeout, reset
                err = Api2PdfError(repr(exc), op=op, retryable=True,
                                   timed_out=isinstance(exc, httpx.TimeoutException))
            except Api2PdfError as exc:
                err = exc
            if not err.retryable or attempt == self.max_attempts:
                raise err
            delay = err.retry_after if err.retry_after is not None else random.uniform(
                0, min(self.max_delay, self.base_delay * 2 ** (attempt - 1)))
            if deadline is not None and time.monotonic() + delay >= deadline:
                raise err
            self.sleep(delay)

    def _parse(self, op, resp, binary):
        ctype = resp.headers.get("content-type", "")
        if binary and resp.status_code == 200 and "json" not in ctype:
            if not resp.content.startswith(b"%PDF"):
                raise Api2PdfError(f"not a PDF: {resp.content[:80]!r}", op=op, status=200)
            return resp.content
        try:
            data = resp.json()
        except ValueError:
            data = {}
        ok = resp.status_code < 300 and data.get("Success", True) is not False
        if ok:
            return data
        message = data.get("Error") or data.get("error") or resp.reason_phrase
        ra = resp.headers.get("retry-after", "")
        raise Api2PdfError(
            f"HTTP {resp.status_code}: {message}", op=op, status=resp.status_code,
            response_id=data.get("ResponseId"),
            retryable=resp.status_code in RETRYABLE_STATUS,
            retry_after=min(float(ra), self.max_delay) if ra.isdigit() else None)

A few details worth copying even if you write your own:

  • The Authorization header is the raw key. There is no Bearer prefix.
  • One exception type carries the operation, HTTP status, Api2Pdf's Error text and the ResponseId. That id is what you log and what support uses to find the request in the portal logs.
  • timed_out is set for client-side read timeouts and 504s. The worker uses it to move a job to the XL tier.
  • With outputBinary=true, the client checks for the %PDF magic bytes before returning, so a proxy's HTML error page is never saved as invoice.pdf.
  • sleep and transport are injectable, which is what makes the tests below run in milliseconds with no network.

Pattern 3: idempotency keys you own

Api2Pdf has no idempotency key header, and it would not help much if it did: the API cannot know that two different HTML strings are the same invoice with a different timestamp in the footer. Idempotency is a property of your domain, so it lives in your database. The rule is: the same logical document always maps to the same job and the same storage key.

The job key is a SHA-256 of the document kind, the template version and the canonical JSON of the data the template needs. Bump the template version when the layout changes, and every document is rendered again on its next request; leave it alone, and a double-click, a client retry or a replayed queue message all land on the existing job. The output object key is derived from the job key, so even if a render does happen twice, the second upload overwrites the same object instead of creating a duplicate.

-- pdfjobs/schema.sql
CREATE TABLE IF NOT EXISTS pdf_jobs (
    id            bigserial PRIMARY KEY,
    job_key       text NOT NULL UNIQUE,          -- the idempotency key
    kind          text NOT NULL,                 -- 'invoice', 'statement', ...
    payload       jsonb NOT NULL,                -- what the template needs
    object_key    text NOT NULL,                 -- where the PDF lands in your bucket
    status        text NOT NULL DEFAULT 'queued'
                  CHECK (status IN ('queued', 'running', 'done', 'failed')),
    attempts      int NOT NULL DEFAULT 0,
    use_xl        boolean NOT NULL DEFAULT false, -- set after a timeout on v2
    run_after     timestamptz NOT NULL DEFAULT now(),
    lease_until   timestamptz,
    response_id   text,
    cost          numeric(12, 6),
    seconds       numeric(10, 3),
    last_error    text,
    created_at    timestamptz NOT NULL DEFAULT now(),
    finished_at   timestamptz
);
CREATE INDEX IF NOT EXISTS pdf_jobs_ready ON pdf_jobs (run_after) WHERE status IN ('queued', 'running');
# pdfjobs/jobs.py
"""Idempotent PDF jobs on Postgres (psycopg 3)."""
import hashlib
import json

TEMPLATE_VERSION = "invoice-v7"  # bump when the template changes


def job_key(kind, payload, version=TEMPLATE_VERSION):
    canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"), default=str)
    return hashlib.sha256(f"{kind}|{version}|{canonical}".encode()).hexdigest()


def enqueue(conn, kind, payload, object_prefix):
    """Create the job once. Calling it again with the same input returns the same job."""
    key = job_key(kind, payload)
    object_key = f"{object_prefix}/{key[:16]}.pdf"
    row = conn.execute(
        """
        INSERT INTO pdf_jobs (job_key, kind, payload, object_key)
        VALUES (%s, %s, %s, %s)
        ON CONFLICT (job_key) DO UPDATE SET job_key = EXCLUDED.job_key
        RETURNING id, status, object_key, (xmax = 0) AS created
        """,
        (key, kind, json.dumps(payload, default=str), object_key),
    ).fetchone()
    conn.commit()
    return row  # (id, status, object_key, created)


def claim(conn, lease_seconds=600):
    """Take one ready job. SKIP LOCKED lets many workers poll the same table."""
    row = conn.execute(
        """
        UPDATE pdf_jobs SET status = 'running', attempts = attempts + 1,
               lease_until = now() + make_interval(secs => %s)
        WHERE id = (
            SELECT id FROM pdf_jobs
            WHERE (status = 'queued' AND run_after <= now())
               OR (status = 'running' AND lease_until < now())   -- a worker died
            ORDER BY run_after
            FOR UPDATE SKIP LOCKED
            LIMIT 1)
        RETURNING id, kind, payload, object_key, attempts, use_xl
        """,
        (lease_seconds,),
    ).fetchone()
    conn.commit()
    return row


def complete(conn, job_id, result):
    conn.execute(
        """
        UPDATE pdf_jobs SET status = 'done', finished_at = now(), lease_until = NULL,
               response_id = %s, cost = %s, seconds = %s, last_error = NULL
        WHERE id = %s
        """,
        (result.get("ResponseId"), result.get("Cost"), result.get("Seconds"), job_id),
    )
    conn.commit()


def retry_later(conn, job_id, error, delay_seconds, use_xl=False):
    conn.execute(
        """
        UPDATE pdf_jobs SET status = 'queued', lease_until = NULL, last_error = %s,
               run_after = now() + make_interval(secs => %s), use_xl = use_xl OR %s
        WHERE id = %s
        """,
        (error, delay_seconds, use_xl, job_id),
    )
    conn.commit()


def fail(conn, job_id, error):
    conn.execute(
        "UPDATE pdf_jobs SET status = 'failed', finished_at = now(), lease_until = NULL,"
        " last_error = %s WHERE id = %s",
        (error, job_id),
    )
    conn.commit()

Three Postgres details do the heavy lifting. ON CONFLICT (job_key) DO UPDATE ... RETURNING returns the existing row on a duplicate, which DO NOTHING would not; xmax = 0 tells you whether this call created it. FOR UPDATE SKIP LOCKED lets any number of workers poll one table without handing the same job to two of them. And the lease (lease_until) means a worker that is killed mid-render does not strand its job: once the lease expires, another worker reclaims it, with attempts incremented.

Keep the payload deterministic. If the template prints "generated at 09:41:07", that timestamp must not be part of the key, or every request becomes a new document. Hash the inputs that define the document (invoice id, line items, totals, locale), not the render time.

Pattern 4: render in a worker, deliver to your bucket

The worker claims a job, renders it, and has Api2Pdf upload the PDF straight into S3 with a presigned PUT URL. Your server never downloads or re-uploads the bytes, and you never hand Api2Pdf any cloud credentials. The useCustomStorage and storage fields work on every conversion endpoint (Chrome, wkhtmltopdf, LibreOffice, PdfSharp and /zip); storage is ignored unless useCustomStorage is true.

# pdfjobs/worker.py
"""Render queued PDF jobs straight into your bucket, then tell whoever is waiting."""
import logging
import time

from . import jobs
from .api2pdf_client import Api2PdfError

log = logging.getLogger("pdf-worker")
MAX_JOB_ATTEMPTS = 6
LEASE_SECONDS = 600


class Worker:
    def __init__(self, conn, api2pdf, storage, render_html, notify, api2pdf_xl=None):
        self.conn = conn
        self.api2pdf = api2pdf          # Api2Pdf(key)
        self.api2pdf_xl = api2pdf_xl    # Api2Pdf(key, base_url=V2_XL), optional
        self.storage = storage          # .exists(key), .presigned_put(key, content_type)
        self.render_html = render_html  # (kind, payload) -> HTML string
        self.notify = notify            # (event, data) -> None: your own webhook

    def run_once(self):
        job = jobs.claim(self.conn, LEASE_SECONDS)
        if job is None:
            return False
        job_id, kind, payload, object_key, attempts, use_xl = job
        try:
            # An earlier attempt may have uploaded the PDF and died before it
            # committed. The object key is deterministic, so look before rendering.
            if self.storage.exists(object_key):
                jobs.complete(self.conn, job_id, {})
            else:
                result = self.render(kind, payload, object_key, use_xl)
                jobs.complete(self.conn, job_id, result)
                log.info("pdf done job=%s response_id=%s seconds=%s cost=%s", job_id,
                         result.get("ResponseId"), result.get("Seconds"), result.get("Cost"))
            self._notify("pdf.ready", {"job_id": job_id, "object_key": object_key})
        except Api2PdfError as exc:
            log.warning("pdf error job=%s status=%s response_id=%s: %s",
                        job_id, exc.status, exc.response_id, exc)
            if exc.retryable and attempts < MAX_JOB_ATTEMPTS:
                jobs.retry_later(self.conn, job_id, str(exc),
                                 delay_seconds=min(30 * 2 ** attempts, 3600),
                                 use_xl=exc.timed_out and self.api2pdf_xl is not None)
            else:
                jobs.fail(self.conn, job_id, str(exc))
                self._notify("pdf.failed", {"job_id": job_id, "error": str(exc)})
        return True

    def _notify(self, event, data):
        # The job is already committed. A failed webhook must not undo it;
        # the receiver can still poll, and you can replay from the table.
        try:
            self.notify(event, data)
        except Exception:
            log.exception("webhook %s failed for job %s", event, data.get("job_id"))

    def render(self, kind, payload, object_key, use_xl):
        client = self.api2pdf_xl if (use_xl and self.api2pdf_xl) else self.api2pdf
        return client.html_to_pdf(
            self.render_html(kind, payload),
            file_name=object_key.rsplit("/", 1)[-1],
            options={"printBackground": True, "preferCSSPageSize": True},
            storage={
                "method": "PUT",
                "url": self.storage.presigned_put(object_key, "application/pdf"),
                "extraHTTPHeaders": {"Content-Type": "application/pdf"},
            },
            # Give up on in-call retries well before the lease expires, so a
            # second worker never picks up a job this one is still rendering.
            deadline=time.monotonic() + LEASE_SECONDS - 60,
        )

    def run_forever(self, idle_seconds=1.0):
        while True:
            if not self.run_once():
                time.sleep(idle_seconds)

The order of operations is what makes this safe to crash at any point:

  1. Check the bucket first. If a previous attempt uploaded the file and then died before committing done, the object is already there under its deterministic key. Mark the job done and skip the render.
  2. Render with a fresh presigned URL. URLs are generated per attempt with a 15 minute expiry, so a job that waits an hour in backoff never tries to upload with a stale signature.
  3. Commit, then notify. The job row is the source of truth. A webhook that fails is logged and does not undo a finished job; consumers can still poll, and you can replay notifications from the table.
  4. Classify the failure. Retryable errors go back to queued with a job-level backoff (60 seconds, then 2, 4, 8 minutes, capped at an hour), separate from the short in-call retries. Permanent errors go straight to failed with the API's message in last_error.

The S3 side is a small adapter. The one trap is the signed Content-Type: with SigV4, the header you sign is the header you must send, which is why the worker passes extraHTTPHeaders alongside the URL. A mismatch comes back from S3 as 403 SignatureDoesNotMatch.

# pdfjobs/storage.py
"""S3 adapter for the worker: a deterministic key, a presigned PUT, and an existence check."""
import boto3
from botocore.config import Config
from botocore.exceptions import ClientError


class S3Storage:
    def __init__(self, bucket, region="us-east-1"):
        self.bucket = bucket
        self.s3 = boto3.client("s3", region_name=region, config=Config(signature_version="s3v4"))

    def presigned_put(self, key, content_type, expires=900):
        # ContentType becomes a signed header, so the upload must send the same
        # value: that is what storage.extraHTTPHeaders does in the worker.
        return self.s3.generate_presigned_url(
            "put_object",
            Params={"Bucket": self.bucket, "Key": key, "ContentType": content_type},
            ExpiresIn=expires,
        )

    def exists(self, key):
        try:
            self.s3.head_object(Bucket=self.bucket, Key=key)
            return True
        except ClientError as exc:
            if exc.response["Error"]["Code"] in ("404", "NoSuchKey", "NotFound"):
                return False
            raise

    def presigned_get(self, key, expires=300):
        return self.s3.generate_presigned_url(
            "get_object", Params={"Bucket": self.bucket, "Key": key}, ExpiresIn=expires)

Azure Blob SAS URLs and Google Cloud Storage signed URLs work the same way; the batch and zip guide has both variants and the headers each one needs.

Escalating to XL automatically

Most documents never get near 90 seconds. The ones that do are predictable: a 400-page statement, a report with dozens of charts, a page that loads slow third-party scripts. You can route those to v2-xl.api2pdf.com up front when you know the size, but the worker also handles the case you did not predict. When a job fails with timed_out, it is re-queued with use_xl = true, and the next attempt goes to the XL host with a 330 second read timeout. XL costs 10x per request, so only documents that have proved they need it pay for it. If XL also times out, the job fails after its attempts run out, and that is a signal to split the document (render sections and /pdfsharp/merge them) rather than to wait longer.

Pattern 5: answer 202, then tell the caller when it is ready

With the worker in place, the web endpoint does almost nothing: it enqueues and returns 202 Accepted with a job id. Because enqueue is idempotent, a user who clicks the button five times gets the same job five times. Here it is in FastAPI; the shape is the same in any framework:

# app.py
"""The web side: accept the request, enqueue, answer 202. Never render in the request."""
import os

import psycopg
from fastapi import FastAPI, HTTPException
from fastapi.responses import RedirectResponse

from pdfjobs import jobs
from pdfjobs.storage import S3Storage

app = FastAPI()
storage = S3Storage(os.environ["PDF_BUCKET"])


def db():
    return psycopg.connect(os.environ["DATABASE_URL"])


@app.post("/invoices/{invoice_id}/pdf", status_code=202)
def request_pdf(invoice_id: int):
    payload = load_invoice(invoice_id)  # your data access; must be deterministic
    with db() as conn:
        job_id, status, _, _ = jobs.enqueue(conn, "invoice", payload, f"invoices/{invoice_id}")
    return {"job_id": job_id, "status": status, "poll": f"/pdf-jobs/{job_id}"}


@app.get("/pdf-jobs/{job_id}")
def job_status(job_id: int):
    with db() as conn:
        row = conn.execute("SELECT status, object_key, last_error FROM pdf_jobs WHERE id = %s",
                           (job_id,)).fetchone()
    if row is None:
        raise HTTPException(404)
    status, object_key, error = row
    if status == "done":
        return RedirectResponse(storage.presigned_get(object_key), status_code=303)
    return {"status": status, "error": error if status == "failed" else None}

The status endpoint redirects to a short-lived presigned GET once the job is done, so the browser downloads from S3 directly and the URL it sees expires in five minutes. load_invoice is your own data access.

Polling is fine for a browser tab. For other services (a billing system that emails the PDF, a CRM that attaches it) send a webhook. This one is yours, not Api2Pdf's, and it follows the conventions receivers expect: an event id to dedupe on, a timestamp, and an HMAC-SHA256 signature over timestamp.body so a replayed or forged request is rejected:

# pdfjobs/notify.py
"""Your own outbound webhook: signed, with an event id receivers can dedupe on."""
import hashlib
import hmac
import json
import time
import uuid

import httpx


def send_webhook(url, secret, event, data, client=None):
    body = json.dumps({"id": str(uuid.uuid4()), "type": event, "created": int(time.time()),
                       "data": data}, separators=(",", ":"))
    ts = str(int(time.time()))
    sig = hmac.new(secret.encode(), f"{ts}.{body}".encode(), hashlib.sha256).hexdigest()
    (client or httpx).post(url, content=body, timeout=10.0, headers={
        "Content-Type": "application/json",
        "X-Signature": f"t={ts},v1={sig}",
    }).raise_for_status()


def verify_webhook(secret, header, body, tolerance=300):
    parts = dict(p.split("=", 1) for p in header.split(","))
    if abs(time.time() - int(parts["t"])) > tolerance:
        return False
    expected = hmac.new(secret.encode(), f"{parts['t']}.{body}".encode(), hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, parts["v1"])

Wiring it together is a short process you run next to your web app, one or more copies depending on how many PDFs you need per minute:

# run_worker.py
import logging
import os

import psycopg

from pdfjobs.api2pdf_client import V2_XL, Api2Pdf
from pdfjobs.notify import send_webhook
from pdfjobs.storage import S3Storage
from pdfjobs.worker import Worker
from templates import render_html  # (kind, payload) -> HTML, e.g. Jinja2

logging.basicConfig(level=logging.INFO)
key = os.environ["API2PDF_API_KEY"]
worker = Worker(
    conn=psycopg.connect(os.environ["DATABASE_URL"]),
    api2pdf=Api2Pdf(key),
    api2pdf_xl=Api2Pdf(key, base_url=V2_XL),
    storage=S3Storage(os.environ["PDF_BUCKET"]),
    render_html=render_html,
    notify=lambda event, data: send_webhook(
        os.environ["PDF_WEBHOOK_URL"], os.environ["PDF_WEBHOOK_SECRET"], event, data),
)
worker.run_forever()

Throughput is roughly workers × 60 / average render seconds per minute. Four workers rendering two-second invoices produce around 120 PDFs a minute; for a month-end run of 50,000, run more workers for an hour rather than changing the code. Because there are no rate limits on the Api2Pdf side, the knobs are entirely yours: worker count, database connections and how fast your bucket accepts writes.

Pattern 6: observability and cost

  • Log ResponseId, Seconds and Cost on every call, not the HTML. The worker writes all three to the job row, so cost per document kind is one GROUP BY away, and the id matches the request logs in the portal.
  • Watch your balance. GET /balance returns the remaining credit on the account. Call it from a daily cron and alert well before it runs out, rather than finding out from a wave of failed jobs.
  • Alert on the job table, not on individual errors. Useful queries: jobs queued for longer than five minutes (workers are down or saturated), the failed count per hour (a template or data bug), and the share of jobs with use_xl set (documents are growing).
  • Do not put GET /status in your readiness probe. It is a health check for the API, and it is useful on a dashboard. But if your pods go unready whenever a dependency blips, a brief upstream issue becomes a full outage of your app. The queue already absorbs it: jobs wait and retry.
  • Clean up what you do not keep. If you use hosted FileUrls for intermediate steps, for example rendering parts and merging them, delete each one with DELETE /file/{responseId} after the merge. For regulated documents, see HIPAA compliance for PDF generation.

Testing it without a network or an API key

httpx's MockTransport stands in for Api2Pdf, so the retry rules are tested directly: a 503 is retried and then succeeds, a 401 is not retried and keeps its ResponseId, a 200 with Success: false raises, a read timeout is flagged as timed_out, and Retry-After sets the sleep. An excerpt:

import json

import httpx
import pytest

from pdfjobs.api2pdf_client import Api2Pdf, Api2PdfError

OK = {"Success": True, "FileUrl": "https://example/f.pdf", "ResponseId": "r1",
      "MbOut": 0.02, "Seconds": 1.1, "Cost": 0.0002, "Error": None}


def client(handler, **kw):
    return Api2Pdf("test-key", transport=httpx.MockTransport(handler), sleep=lambda s: None, **kw)


def test_sends_raw_key_and_json_body():
    seen = {}

    def handler(req):
        seen["auth"] = req.headers["authorization"]
        seen["body"] = json.loads(req.content)
        return httpx.Response(200, json=OK)

    assert client(handler).html_to_pdf("<h1>x</h1>", file_name="a.pdf")["ResponseId"] == "r1"
    assert seen["auth"] == "test-key"
    assert seen["body"] == {"html": "<h1>x</h1>", "inline": False, "fileName": "a.pdf"}


def test_retries_503_then_succeeds():
    calls = []

    def handler(req):
        calls.append(1)
        return httpx.Response(503) if len(calls) < 3 else httpx.Response(200, json=OK)

    assert client(handler).html_to_pdf("x")["Success"]
    assert len(calls) == 3


def test_does_not_retry_401():
    calls = []

    def handler(req):
        calls.append(1)
        return httpx.Response(401, json={"Success": False, "Error": "Invalid API key", "ResponseId": "r9"})

    with pytest.raises(Api2PdfError) as e:
        client(handler).html_to_pdf("x")
    assert len(calls) == 1 and e.value.status == 401 and e.value.response_id == "r9"
    assert not e.value.retryable


def test_success_false_on_200_is_an_error():
    def handler(req):
        return httpx.Response(200, json={"Success": False, "Error": "boom"})

    with pytest.raises(Api2PdfError, match="boom"):
        client(handler).html_to_pdf("x")

The worker tests run against a real Postgres (a throwaway cluster is enough) with a fake bucket: enqueueing twice returns the same job, an existing object skips the render, a 400 fails the job immediately, a timeout re-queues it on XL and the XL attempt completes it, and an expired lease is reclaimed by the next claim.

pip install httpx "psycopg[binary]" boto3 fastapi pytest
pytest -q
...............                                                          [100%]
15 passed in 0.19s

Production checklist

  • The API key comes from a secret store and the client refuses to start without it (no accidental 402s).
  • Connect timeout around 10 s, read timeout of 120 s on v2 and 330 s on XL, plus a deadline per job.
  • Retries only for network errors, 408, 429 and 5xx, with jittered backoff and Retry-After.
  • Every document has a deterministic job key and storage key; the template version is part of the key.
  • Anything slower than a couple of seconds renders in a worker, not in a web request.
  • PDFs land in your bucket through useCustomStorage; hosted FileUrls are treated as 24-hour temporary links.
  • Timeouts escalate to v2-xl.api2pdf.com, and documents that time out there are split and merged.
  • Completion is announced with a signed webhook that carries an event id, and the job table is the source of truth.
  • ResponseId, Seconds and Cost are stored per job; balance and queue age are alerted on.

Wrap-up

None of this is specific to PDFs, and that is the point: once rendering is a job with a key, a lease and a deterministic destination, it behaves like the rest of your background work. Deploys, retries, double-clicks and slow documents stop being incidents. The same worker can run any Api2Pdf conversion by swapping the endpoint: Markdown to PDF, Office files through /libreoffice/any-to-pdf, watermarks, or file to Markdown extraction. Create a free account to get an API key, and browse every request field in the interactive API docs.