May 9, 2026

Async PDF Generation Status: Polling vs Webhook

PDF APIwebhookasyncpollingAPI integration

The FUNBREW PDF generation endpoints (POST /api/pdf/generate-from-html and friends) are synchronous. They do not respond until the PDF is ready, and the response's data.download_url (fetched with your API key) gives you the PDF directly. There is no single-document endpoint that returns a job ID first and lets you ask for its status later.

The asynchronous path is batch (POST /api/pdf/batch, every plan including Free). You submit up to 100 HTML/URL items, get a batch_id back immediately, and each item is generated in a server-side queue. "Status tracking" in this article is mostly about batches.

There are three ways to track them: polling (call GET /api/pdf/batch/{batch_id} repeatedly), webhooks (a pdf.generated event reaches your endpoint each time a PDF is ready), and — added in the May 31, 2026 release — SSE (Server-Sent Events) (stream progress from GET /api/pdf/jobs/{id}/events). Each has different trade-offs.

For the SSE implementation in detail, see the PDF Real-Time Progress Streaming Guide. For full webhook setup including Slack integration, see the PDF API Webhook Integration Guide. For batch processing patterns, see the PDF API Batch Processing Guide.

When You Need Async (Batch)

Synchronous generation is fine when:

  • You are generating a single PDF per request
  • The client (browser or mobile app) can wait until generation finishes
  • You only need a handful of PDFs — calling the synchronous API in parallel is simpler than polling

Batch (async) is the better fit when:

  • You generate tens to 100 PDFs in one go
  • You want to decouple PDF generation from the HTTP request lifecycle
  • You want to see exactly which items failed and resubmit only those (batch status returns status and error_message per item)

For batch jobs, the PDF API batch processing guide covers concurrency control and queue patterns.

Strategy 1: Polling

How Polling Works

1. POST /api/pdf/batch          →  201 { "data": { "batch_id": "9b1c…", "status": "pending", "total_items": 2 } }
2. GET /api/pdf/batch/{batch_id}  →  { "data": { "status": "processing", "completed_items": 1, "failed_items": 0, … } }
3. GET /api/pdf/batch/{batch_id}  →  { "data": { "status": "completed", "completed_items": 2, "failed_items": 0, "items": [ … ] } }

status moves from pending to processing to completed or failed. When every item has finished, the batch is completed if at least one item succeeded and failed only if all of them failed. items[] holds each item's id, source_type, status, and error_message.

Note: the status endpoint returns neither file names nor download URLs. To get the PDFs a batch produced, receive their filename through the pdf.generated webhook described below. Polling alone tells you whether the batch has finished and how many items succeeded or failed.

Basic Polling (Node.js)

const API_BASE = 'https://pdf.funbrew.cloud';
const authHeaders = { Authorization: `Bearer ${process.env.FUNBREW_PDF_API_KEY}` };

async function pollBatchUntilDone(batchId, intervalMs = 2000, maxAttempts = 30) {
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    const response = await fetch(`${API_BASE}/api/pdf/batch/${batchId}`, {
      headers: authHeaders,
    });

    if (!response.ok) throw new Error(`Status check failed: ${response.status}`);

    const { data } = await response.json();

    if (data.status === 'completed') return data;
    if (data.status === 'failed') {
      const errors = data.items.map(item => item.error_message).join('; ');
      throw new Error(`All batch items failed: ${errors}`);
    }

    // Still processing — wait before next check
    if (attempt < maxAttempts) {
      await new Promise(r => setTimeout(r, intervalMs));
    }
  }

  throw new Error(`Batch ${batchId} did not complete after ${maxAttempts} attempts`);
}

// Usage
async function generateBatchAndWait(htmlList) {
  // Step 1: Submit the batch (up to 100 items)
  const submitResp = await fetch(`${API_BASE}/api/pdf/batch`, {
    method: 'POST',
    headers: { ...authHeaders, 'Content-Type': 'application/json' },
    body: JSON.stringify({
      items: htmlList.map(html => ({ type: 'html', html, options: { 'page-size': 'A4' } })),
    }),
  });
  if (!submitResp.ok) throw new Error(`Batch submit failed: ${submitResp.status}`);
  const { data } = await submitResp.json();

  // Step 2: Poll until done
  const result = await pollBatchUntilDone(data.batch_id);
  console.log(`${result.completed_items}/${result.total_items} succeeded`);
  return result;
}

Exponential Backoff Polling

A fixed interval wastes requests for long-running jobs and adds latency for quick ones. Exponential backoff adjusts the wait time dynamically. Polling requests live under /api/pdf/ too, so they count against the per-minute rate limit (per company, shared by all API keys). On a 429, wait for the number of seconds in the Retry-After header.

async function pollWithBackoff(batchId, {
  initialIntervalMs = 500,
  maxIntervalMs = 10000,
  maxAttempts = 20,
} = {}) {
  let intervalMs = initialIntervalMs;

  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    const response = await fetch(`${API_BASE}/api/pdf/batch/${batchId}`, {
      headers: authHeaders,
    });

    if (response.status === 429) {
      const retryAfter = Number(response.headers.get('Retry-After') ?? 1);
      await new Promise(r => setTimeout(r, retryAfter * 1000));
      continue;
    }
    if (!response.ok) throw new Error(`Status check failed: ${response.status}`);

    const { data } = await response.json();

    if (data.status === 'completed') return data;
    if (data.status === 'failed') throw new Error('All batch items failed');

    // Exponential backoff with jitter
    const jitter = Math.random() * 200;
    await new Promise(r => setTimeout(r, intervalMs + jitter));

    // Double the interval up to the cap
    intervalMs = Math.min(intervalMs * 2, maxIntervalMs);
  }

  throw new Error(`Polling timed out after ${maxAttempts} attempts`);
}

The jitter (random offset) prevents multiple clients from all checking at the same moment — important when polling from multiple workers.

Polling in Python

import os
import time
import requests

API_BASE = "https://pdf.funbrew.cloud"


def poll_batch_until_done(
    batch_id: str,
    initial_interval: float = 0.5,
    max_interval: float = 10.0,
    max_attempts: int = 20,
) -> dict:
    interval = initial_interval
    headers = {"Authorization": f"Bearer {os.environ['FUNBREW_PDF_API_KEY']}"}

    for attempt in range(1, max_attempts + 1):
        resp = requests.get(
            f"{API_BASE}/api/pdf/batch/{batch_id}",
            headers=headers,
            timeout=10,
        )
        resp.raise_for_status()
        data = resp.json()["data"]

        if data["status"] == "completed":
            return data
        if data["status"] == "failed":
            errors = "; ".join(item["error_message"] or "" for item in data["items"])
            raise RuntimeError(f"All batch items failed: {errors}")

        if attempt < max_attempts:
            time.sleep(interval)
            interval = min(interval * 2, max_interval)

    raise TimeoutError(f"Batch {batch_id} did not complete in {max_attempts} attempts")

Polling Trade-offs

Pros of polling:

  • Simple to implement — no public endpoint needed
  • Works in any environment (serverless, CLI scripts, cron jobs)
  • Easy to debug — you can see every status check in logs
  • completed_items / total_items gives item-level progress

Cons of polling:

  • Wasted requests when the job takes longer than expected
  • Added latency equal to one polling interval after job completion
  • Polling requests consume the per-minute rate limit
  • The status endpoint does not return file names, so you need another channel (webhooks) to receive the PDFs

Polling is the right choice for knowing whether a batch is done in low-to-medium concurrency use cases, CLI tools, scripts, and any environment where receiving incoming HTTP requests is not possible.

Strategy 2: Webhooks

How Webhooks Work

1. Register a URL and events (e.g. pdf.generated) with POST /api/webhooks (every plan including Free; save the secret from the response)
2. POST /api/pdf/batch  →  { "data": { "batch_id": "9b1c…" } }  (returns immediately)
3. [Items are generated in a server-side queue]
4. For each finished PDF: POST <your URL>  →  { "event": "pdf.generated", "timestamp": "…", "data": { "filename": "…", "download_url": "…", … } }

Your code receives a push notification each time a PDF is ready, rather than checking repeatedly. pdf.generated is also sent for PDFs created through the synchronous API, not only for batch items.

The events delivered are pdf.generated, pdf.downloaded, and pdf.expired (plus tus.upload.completed and tus.upload.aborted for resumable uploads). There is no generation-failed event and no batch-completed event. Check failures through batch status (failed_items, items[].error_message).

data contains filename, download_url, file_size, source_type, and expires_at (pdf.downloaded adds download_count and remaining_downloads). There is no job ID or batch ID. download_url is normally the public download page (/dl/...) meant for people. To fetch the PDF bytes from code, use the filename with GET /api/pdf/download/{filename} (with your API key).

Webhook Endpoint (Node.js / Express)

The signature arrives in the X-Webhook-Signature header as sha256= followed by the hex HMAC-SHA256. The HMAC is computed over the exact body that was sent, so verify it against the raw body before parsing (re-serializing with JSON.stringify(req.body) changes details such as escaped slashes and will not match).

const express = require('express');
const crypto  = require('crypto');
const app     = express();

app.post('/webhooks/pdf', express.raw({ type: 'application/json' }), (req, res) => {
  // Step 1: Verify the signature against the raw body
  const signature = req.get('x-webhook-signature') ?? '';
  const expected  = 'sha256=' + crypto
    .createHmac('sha256', process.env.WEBHOOK_SECRET)
    .update(req.body)
    .digest('hex');

  const a = Buffer.from(signature);
  const b = Buffer.from(expected);
  if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) {
    return res.status(401).json({ error: 'Invalid signature' });
  }

  // Step 2: Acknowledge receipt immediately (before processing; delivery times out after 10 seconds)
  res.status(200).json({ received: true });

  // Step 3: Handle the event asynchronously
  const { event, data } = JSON.parse(req.body.toString('utf8'));
  handlePdfEvent(event, data).catch(err => console.error('Webhook handler error:', err));
});

async function handlePdfEvent(event, data) {
  switch (event) {
    case 'pdf.generated':
      console.log(`PDF ready: ${data.filename} (${data.file_size} bytes)`);
      // Download, store, or notify the user (notifyUser is your own code)
      await notifyUser(data.filename, data.download_url);
      break;

    case 'pdf.downloaded':
      console.log(`Downloaded: ${data.filename} (${data.remaining_downloads} left, -1 means unlimited)`);
      break;

    case 'pdf.expired':
      console.log(`Expired and deleted: ${data.filename}`);
      break;
  }
}

app.listen(3000);

Webhook Endpoint (Python / FastAPI)

import hashlib
import hmac
import json
import os

from fastapi import BackgroundTasks, FastAPI, HTTPException, Request

app = FastAPI()


@app.post("/webhooks/pdf")
async def handle_webhook(request: Request, background_tasks: BackgroundTasks):
    body = await request.body()
    signature = request.headers.get("x-webhook-signature", "")

    # Verify the signature against the raw body
    expected = "sha256=" + hmac.new(
        os.environ["WEBHOOK_SECRET"].encode(),
        body,
        hashlib.sha256,
    ).hexdigest()

    if not hmac.compare_digest(signature, expected):
        raise HTTPException(status_code=401, detail="Invalid signature")

    # Processing runs in the background after the response is returned
    payload = json.loads(body)
    background_tasks.add_task(process_event, payload["event"], payload["data"])

    return {"received": True}


async def process_event(event: str, data: dict):
    if event == "pdf.generated":
        print(f"PDF ready: {data['filename']}")
        # notify_user is your own code
        await notify_user(data["filename"], data["download_url"])
    elif event == "pdf.expired":
        print(f"Expired and deleted: {data['filename']}")

Signature Verification

Always verify the webhook signature before processing the payload. Without verification, anyone who knows your endpoint URL can send fake events. The signing secret is returned only in the POST /api/webhooks registration response, so store it right away.

// Correct: check the length, then compare in constant time
// (timingSafeEqual throws if the lengths differ)
const a = Buffer.from(signature);
const b = Buffer.from(expected);
const isValid = a.length === b.length && crypto.timingSafeEqual(a, b);

// Wrong: use === (vulnerable to timing attacks)
// const isValid = signature === expected;

Using timingSafeEqual (Node.js) or hmac.compare_digest (Python) prevents timing attacks where an attacker could infer the expected signature by measuring response time.

Handling Webhook Retries

FUNBREW PDF delivers webhooks like this:

  • The timeout is 10 seconds
  • On a 5xx response, a connection failure, or a timeout, delivery is retried (up to 3 attempts including the first, waiting 60 seconds and then 5 minutes)
  • On a 4xx response, delivery is not retried
  • A retry sends the same payload (including the same timestamp)

Your endpoint must handle duplicate deliveries gracefully. The payload has no job ID, so for pdf.generated use the filename, which is unique per generated PDF, as the key.

// Idempotent handler: check whether this file was already processed
async function handlePdfEvent(event, data) {
  if (event !== 'pdf.generated') return;

  // Check if already processed
  const existing = await db.query(
    'SELECT filename FROM processed_pdfs WHERE filename = $1',
    [data.filename]
  );
  if (existing.rows.length > 0) {
    console.log(`${data.filename} already processed — skipping`);
    return;
  }

  // Process and mark as done (downloadAndStorePdf is your own code;
  // fetch the PDF bytes from /api/pdf/download/{filename})
  await downloadAndStorePdf(data.filename);
  await db.query(
    'INSERT INTO processed_pdfs (filename, processed_at) VALUES ($1, NOW())',
    [data.filename]
  );
}

Store processed file names and skip re-processing if you see the same value twice. This is the standard idempotency pattern for webhook consumers.

Webhook Trade-offs

Pros of webhooks:

  • Notification arrives as soon as a PDF is ready — no polling delay
  • No wasted requests on checking status
  • You receive the finished PDF's filename, so you can fetch it from /api/pdf/download/{filename}
  • Your server is free while the PDF generates

Cons of webhooks:

  • Requires a publicly accessible HTTP endpoint
  • Not suitable for CLI scripts or one-off jobs
  • More complex to set up (registration, signature verification, duplicate handling)
  • Local development requires a tunnel (ngrok, etc.)
  • No failure or batch-completed events, and no batch ID in the payload (you cannot tell from the payload which batch a PDF belongs to)

Webhooks are the right choice for production applications that process many PDFs and want to receive the finished files with minimal API load.

Choosing Between Polling and Webhooks

Situation Recommendation
Script or CLI tool making a few PDFs Call the synchronous API directly (no tracking needed)
Script waiting for a batch to finish Polling
Background worker processing many jobs Webhooks
Notify users as soon as a PDF is ready Webhooks
Local development or testing Polling (simpler)
Receive the PDFs a batch produced Webhooks (the status endpoint returns no file names)
Public endpoint not available Polling

For production web applications that use batches, webhooks are preferable. For scripting and tooling, polling is simpler. The two compose well: receive PDFs through webhooks and confirm completion and failures by polling.

Strategy 3: SSE (Server-Sent Events)

The May 31, 2026 release added an SSE endpoint (GET /api/pdf/jobs/{id}/events) as a third option alongside polling and webhooks.

How SSE Works

1. POST /api/pdf/batch  →  receive batch_id
   (for a single generation, POST generate-from-html etc. with your own UUID in the X-Job-Id header)
2. GET /api/pdf/jobs/{batch_id or X-Job-Id}/events  →  connect with an Authorization header
3. Server pushes progress for each phase as event: progress
4. Stream closes on done or failed (by default it is also cut after 600 seconds at most)

SSE Characteristics

  • One-way stream from server to client — no need for WebSocket-style bidirectional communication
  • Lower latency than polling — the server checks for progress every 500 ms by default and sends it. SSE connections are not subject to the per-minute rate limit
  • No receiving server required, unlike webhooks
  • Fine-grained phase progress — data has phase, progress (0 to 1), message, data, and occurred_at. Batches emit queued / rendering / postprocess / done / failed; single generations emit queued / rendering / postprocess / uploading / done / failed
  • No missed events when you connect late — connecting without Last-Event-ID replays from the first event; sending Last-Event-ID on reconnect resumes from there (410 if it is too old)
  • Header authentication only — send the API key as Authorization: Bearer or X-API-Key. The browser's native EventSource cannot set headers, so a browser cannot subscribe directly (and you should not put API keys in the browser anyway); receive the stream on your backend and relay it

For a single generation, subscribing before the generation request reaches the server returns 404. Send the POST first, then subscribe, and reconnect after a short wait on 404.

Server-Side Implementation (Node.js)

// Read the SSE stream and finish on done / failed (fetch in Node.js 18+)
async function streamProgress(jobId, onProgress) {
  const res = await fetch(`${API_BASE}/api/pdf/jobs/${jobId}/events`, {
    headers: { ...authHeaders, Accept: 'text/event-stream' },
  });
  if (!res.ok) throw new Error(`SSE connect failed: ${res.status}`);

  const decoder = new TextDecoder();
  let buffer = '';
  for await (const chunk of res.body) {
    buffer += decoder.decode(chunk, { stream: true });
    let sep;
    while ((sep = buffer.indexOf('\n\n')) !== -1) {
      const block = buffer.slice(0, sep);
      buffer = buffer.slice(sep + 2);
      const dataLine = block.split('\n').find(line => line.startsWith('data: '));
      if (!dataLine) continue; // e.g. the retry: line

      const event = JSON.parse(dataLine.slice(6));
      onProgress(event);
      if (event.phase === 'done' || event.phase === 'failed') return event;
    }
  }
  return null; // cut off at the maximum duration
}

// Usage: submit a batch and show progress
const submitResp = await fetch(`${API_BASE}/api/pdf/batch`, {
  method: 'POST',
  headers: { ...authHeaders, 'Content-Type': 'application/json' },
  body: JSON.stringify({ items: [{ type: 'html', html: '<h1>Hello</h1>' }] }),
});
const { data } = await submitResp.json();

await streamProgress(data.batch_id, ({ phase, progress, message }) => {
  // Relay progress (0.0 to 1.0) to your own browser-facing endpoint
  console.log(phase, `${Math.round(progress * 100)}%`, message);
});

To show a progress bar in the browser, relay from this server-side code to the browser through an endpoint on your own origin. For full implementation details, see the PDF Real-Time Progress Streaming Guide.

Decision Matrix: All Three Strategies

Scenario Recommendation
Browser UI with live progress bar SSE (relayed through your backend)
Receive finished PDFs and process them on the backend Webhook
Simple job check, CLI script, or cron job Polling
No receiving server available SSE or Polling
Long-running batch (minutes or more) SSE + Webhook combined (SSE is cut after 600 seconds by default; reconnect with Last-Event-ID)
Many simultaneous jobs Webhook (SSE keeps one connection open per job)

Combining SSE and Webhooks: SSE handles progress display while the user is watching; webhooks trigger backend processing of the finished PDFs. Progress via SSE plus storage or Slack notification via webhooks is the standard production pattern.

Hybrid: Webhooks Plus Polling as a Check

Let webhooks deliver the PDFs, and use polling to confirm that the batch finished and whether any items failed. Webhooks have neither a failure event nor a batch-completed event, so the two complement each other.

async function waitForBatchWithFallback(batchId, { timeoutMs = 10 * 60_000, intervalMs = 5_000 } = {}) {
  const startTime = Date.now();

  while (Date.now() - startTime < timeoutMs) {
    const response = await fetch(`${API_BASE}/api/pdf/batch/${batchId}`, { headers: authHeaders });
    if (!response.ok) throw new Error(`Status check failed: ${response.status}`);
    const { data } = await response.json();

    if (data.status === 'completed' || data.status === 'failed') {
      return {
        completed: data.completed_items,
        failedItems: data.items.filter(item => item.status === 'failed'),
      };
    }

    await new Promise(r => setTimeout(r, intervalMs)); // 5-second poll interval
  }

  throw new Error(`Batch ${batchId} did not finish within timeout`);
}

The webhook handler records received PDFs in a shared store (database or cache), and this function returns the completed count and the failed items. Including retries, the last webhook attempt can arrive about 6 minutes after completion, so if the number of received PDFs falls short of completed, wait a little and then check the delivery history in the dashboard (the payload carries no batch ID, so match by time received or similar).

Error Handling and Retry

Both polling and webhook handlers should implement retry logic for transient failures.

// Fetch the PDF bytes from /api/pdf/download/{filename} with your API key.
// The webhook's download_url (/dl/...) is a download page (HTML) meant for people,
// so use the filename when downloading from code.
// Each download counts toward max_downloads and the rate limit.
async function downloadPdfWithRetry(filename, { maxRetries = 3 } = {}) {
  const url = `${API_BASE}/api/pdf/download/${filename}`;
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    const response = await fetch(url, { headers: authHeaders }).catch(() => null);
    if (response?.ok) return Buffer.from(await response.arrayBuffer());

    // 4xx (expired, download limit reached, etc.) will not be fixed by retrying
    if (response && response.status < 500 && response.status !== 429) {
      throw new Error(`HTTP ${response.status}`);
    }
    if (attempt === maxRetries) throw new Error(`Download failed after ${maxRetries} attempts`);
    // Exponential backoff: 1s, 2s, 4s
    await new Promise(r => setTimeout(r, 1000 * 2 ** (attempt - 1)));
  }
}

For comprehensive error handling patterns including rate-limit handling and 5xx recovery, see the PDF API error handling guide.

Summary

Polling Webhooks SSE
Setup complexity Low Medium Low–Medium
Real-time notification No (interval delay) Yes Yes
Requires public endpoint No Yes No
Wasted API calls Yes (status checks consume the rate limit) No No (not rate limited)
Works directly in browser No (needs the API key; go through your backend) No No (header auth only; go through your backend)
Intermediate progress Item count (completed_items) Per-PDF completion only Per phase (0 to 1)
Delivers the finished PDF's filename No Yes No
Good for scripts/CLI Yes No Possible
Idempotency handling Not needed Required Not needed

For a few PDFs, calling the synchronous API directly is simplest. When you use batches, start with polling to know when they finish. Use SSE when you want a progress bar. Use webhooks to receive the finished PDFs. In production, SSE for progress, webhooks for receiving PDFs, and polling to check for failures is a dependable combination.

Related

Powered by FUNBREW PDF