PDF API Error Handling: Retry & Exponential Backoff Guide
When you integrate a PDF generation API into production, you inevitably encounter errors that never appeared during development. Network timeouts, rate limiting during traffic spikes, request validation errors — if you don't handle these properly, users never receive their PDFs or batch jobs silently stop midway.
This guide organizes the errors that the FUNBREW PDF API actually returns, along with practical retry strategies using exponential backoff. Code examples in curl, Python, Node.js, and PHP will help you build resilient error handling from day one.
For error handling in large-scale batch jobs, see the PDF Batch Processing Guide. API key security is covered in the Security Guide. If you are new to the API, the HTML-to-PDF Complete Guide is a good starting point, and the Quickstart by Language gets you to your first working request in minutes. For Markdown-specific error handling, see the Markdown to PDF API Guide.
Common Error Patterns
The FUNBREW PDF API (https://pdf.funbrew.cloud) returns errors as JSON in the following shape. There is no separate error-code string scheme — identify errors by the HTTP status code and message.
{ "success": false, "message": "Unauthorized. Please provide a valid API key." }
PDF generation is a two-step flow. A successful POST /api/pdf/generate-from-html (or another generate endpoint) returns 200 with JSON containing data.download_url; a GET to that URL with the same API key returns the PDF itself. Both requests need error handling.
1. Timeouts (Client-Side / 504)
Generation is synchronous, so complex HTML or image-heavy templates take longer to respond. If your client timeout is too short, it drops the connection while the server is still working. A gateway or proxy in front of the API that does not get a timely response from upstream may also return 504 Gateway Timeout. 408 Request Timeout means the server wants to close an unused connection; the FUNBREW PDF application does not return it for slow generation.
| Cause | Solution |
|---|---|
| Slow external resource loading (images, fonts) | Inline with Base64 or use a fast origin |
| Large HTML / heavy CSS | Simplify the layout and split long documents |
| Client timeout set too short | Use a generous timeout (roughly 60–120 seconds) |
The quality engine (Chromium) conversion has a 30-second timeout inside the service; when it is exceeded, generation fails with 500.
2. Rate and Usage Limits (429 Too Many Requests)
FUNBREW PDF returns 429 for three different reasons, and only the first one should be retried.
(a) Requests per minute. The limit applies per account (company) and depends on the plan. Downloads from download_url are API requests too and count toward it.
| Plan | Requests per minute |
|---|---|
| Free | 10 |
| Pro | 120 |
| Business | 300 |
For high-volume or dedicated environments, limits are arranged individually (contact us).
When the limit is exceeded, the response includes Retry-After (seconds), X-RateLimit-* headers, and retry_after in the body. Wait for the Retry-After seconds, then retry.
HTTP/1.1 429 Too Many Requests
Retry-After: 42
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1711900800
{"success": false, "error": "rate_limited", "message": "Rate limit exceeded. Please wait and try again.", "retry_after": 42}
(Branch on the status code, error and Retry-After, not on the message text.)
(b) Monthly PDF generation limit (Monthly PDF generation limit reached. Limit: 30, etc.) and (c) storage limit (Storage limit reached. ...). Neither includes Retry-After, and waiting a few seconds will not clear them. Do not retry — alert, and consider changing plans or deleting PDFs you no longer need.
3. Validation Errors (422 Unprocessable Content)
Requests without the required html, with an options.page-size other than A3/A4/A5/Letter/Legal, or with margins outside 0–50 mm are rejected by validation. Send an Accept: application/json header. Without it, a validation failure may come back as a redirect to the previous URL instead of a JSON 422 (Laravel's default validation behavior). The JSON shape is:
{
"message": "Page size must be one of: A3, A4, A5, Letter, Legal",
"errors": {
"options.page-size": ["Page size must be one of: A3, A4, A5, Letter, Legal"]
}
}
On the other hand, the HTML content itself (unclosed tags and so on) is not validated. Broken HTML can still turn into a PDF without an error and simply look wrong, so check the output.
For CSS-related rendering problems, see PDF-Specific CSS Layout Tips. If you are migrating from wkhtmltopdf and seeing different rendering behaviour, the wkhtmltopdf vs Chromium Comparison explains the key differences to watch out for. For general output troubleshooting, see the Troubleshooting Guide.
4. Authentication and Permission Errors (401 / 403)
401: the API key is missing, unknown, or deactivated403: the key lacks the required scope (generatefor generation,downloadfor downloads), the feature is not on your plan (batch, for example), the client IP is not allowed by IP restrictions, or the account is inactive
Retrying won't fix any of these — alert immediately.
5. Server Errors (500 / 502 / 503)
If generation throws an exception, the API returns 500 with a body like {"success": false, "message": "PDF generation from HTML failed", "error": "An internal error occurred."}. Generate endpoints also return an X-Job-Id header — include it when contacting support. 502/503 may be returned when infrastructure in front of the API is temporarily unavailable. Treat all of these as transient and retry a limited number of times.
6. Not Found (404)
Returned when the template passed to generate-from-template does not exist, or the PDF behind download_url cannot be found (including expired files and files that reached their download limit). Retrying won't help.
Retry Strategy: Exponential Backoff Basics
Retrying at fixed intervals concentrates load on the server. Exponential backoff increases the wait time exponentially between retries, and adding random jitter spreads requests out over time.
wait = min(initial_delay × 2^(retry_count - 1) + random_jitter, max_wait)
| Retry | Example Wait (1s initial, 0–1s jitter, 60s max) |
|---|---|
| 1st | 1–2s |
| 2nd | 2–3s |
| 3rd | 4–5s |
| 4th | 8–9s |
| 5th | 16–17s |
Which Errors to Retry
| Status Code | Retry? | Reason |
|---|---|---|
429 (with Retry-After) |
Yes (wait Retry-After seconds) |
Per-minute limit; clears over time |
| 500, 502, 503, 504, connection errors, timeouts | Yes (limited) | Possibly transient |
429 (without Retry-After) |
No | Monthly and storage limits don't clear by waiting |
| 422 | No | The request itself is invalid |
| 401, 403 | No | Auth and permission issues won't resolve with retries |
| 404 | No | Resource doesn't exist |
Caution: generation uses POST, which is not guaranteed to be idempotent. If you retry after a client-side timeout, the first generation may already have finished on the server — you can end up with two PDFs, both counted toward your monthly limit. Keep the retry cap small.
Code Examples
The examples below generate a PDF, download it from download_url, and retry according to the table above.
curl (Shell Script)
Requires jq and curl 7.76 or later (--fail-with-body).
#!/bin/bash
set -u
API_BASE="https://pdf.funbrew.cloud"
API_KEY="${FUNBREW_PDF_API_KEY:?Set FUNBREW_PDF_API_KEY}"
MAX_RETRIES=5
INITIAL_DELAY=1
MAX_DELAY=60
TMP_DIR=$(mktemp -d)
trap 'rm -rf "$TMP_DIR"' EXIT
generate_pdf_with_retry() {
local payload="$1"
local output="$2"
local attempt=0
local delay=$INITIAL_DELAY
local http_code wait_sec retry_after download_url
while :; do
http_code=$(curl -sS -o "$TMP_DIR/body" -D "$TMP_DIR/headers" -w '%{http_code}' \
-X POST "$API_BASE/api/pdf/generate-from-html" \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
--data "$payload" \
--max-time 120) || http_code=000
case "$http_code" in
200)
download_url=$(jq -r '.data.download_url' "$TMP_DIR/body")
curl -sS --fail-with-body -o "$output" \
-H "Authorization: Bearer $API_KEY" \
"$download_url"
return $?
;;
429)
retry_after=$(grep -i '^retry-after:' "$TMP_DIR/headers" | tr -d '\r' | awk '{print $2}')
if [ -z "$retry_after" ]; then
echo "Monthly or storage limit reached, not retrying: $(jq -r '.message' "$TMP_DIR/body")" >&2
return 1
fi
wait_sec=$retry_after
;;
000|500|502|503|504)
# Exponential backoff with 0-1s jitter
wait_sec=$(( delay + RANDOM % 2 ))
delay=$(( delay * 2 ))
[ "$delay" -gt "$MAX_DELAY" ] && delay=$MAX_DELAY
;;
*)
echo "Non-retryable error: HTTP $http_code" >&2
cat "$TMP_DIR/body" >&2
return 1
;;
esac
attempt=$((attempt + 1))
if [ "$attempt" -gt "$MAX_RETRIES" ]; then
echo "Max retries reached (HTTP $http_code)" >&2
return 1
fi
echo "Retry $attempt/$MAX_RETRIES in ${wait_sec}s (HTTP $http_code)" >&2
sleep "$wait_sec"
done
}
PAYLOAD='{"html": "<h1>Invoice</h1>", "options": {"page-size": "A4"}}'
generate_pdf_with_retry "$PAYLOAD" invoice.pdf
Python
import random
import time
from dataclasses import dataclass
from typing import Optional
import requests
API_BASE = "https://pdf.funbrew.cloud"
RETRYABLE_STATUS_CODES = {500, 502, 503, 504}
class NonRetryableError(Exception):
"""Errors that retrying won't fix (422, 401, 403, 404, 429 without Retry-After)."""
@dataclass
class RetryConfig:
max_retries: int = 5
initial_delay: float = 1.0
max_delay: float = 60.0
backoff_multiplier: float = 2.0
jitter_range: float = 1.0
def _error_message(response: requests.Response) -> str:
try:
return response.json().get("message", "")
except ValueError:
return response.text[:200]
def generate_pdf_with_retry(
html: str,
api_key: str,
options: Optional[dict] = None,
config: Optional[RetryConfig] = None,
) -> bytes:
"""Generate a PDF with exponential backoff retry and return the PDF bytes."""
config = config or RetryConfig()
headers = {
"Authorization": f"Bearer {api_key}",
"Accept": "application/json",
}
payload = {"html": html, "options": options or {"page-size": "A4"}}
delay = config.initial_delay
last_error: Optional[Exception] = None
for attempt in range(config.max_retries + 1):
wait_time = None
try:
response = requests.post(
f"{API_BASE}/api/pdf/generate-from-html",
json=payload,
headers=headers,
timeout=120,
)
except (requests.exceptions.Timeout, requests.exceptions.ConnectionError) as e:
last_error = e
else:
if response.status_code == 200:
download_url = response.json()["data"]["download_url"]
pdf = requests.get(
download_url,
headers={"Authorization": f"Bearer {api_key}"},
timeout=120,
)
pdf.raise_for_status()
return pdf.content
message = _error_message(response)
retry_after = response.headers.get("Retry-After")
if response.status_code == 429 and retry_after:
# Per-minute limit: wait Retry-After seconds
wait_time = float(retry_after)
elif response.status_code not in RETRYABLE_STATUS_CODES:
raise NonRetryableError(f"HTTP {response.status_code}: {message}")
last_error = RuntimeError(f"HTTP {response.status_code}: {message}")
if attempt >= config.max_retries:
break
if wait_time is None:
# Exponential backoff + jitter
wait_time = min(delay + random.uniform(0, config.jitter_range), config.max_delay)
delay = min(delay * config.backoff_multiplier, config.max_delay)
print(f"Retry {attempt + 1}/{config.max_retries} in {wait_time:.2f}s")
time.sleep(wait_time)
raise RuntimeError(
f"Max retries ({config.max_retries}) reached"
) from last_error
# Usage
try:
pdf_bytes = generate_pdf_with_retry(
html="<h1>Invoice</h1><p>Total: $100.00</p>",
api_key="your-api-key",
options={"page-size": "A4", "margin-top": 20},
)
with open("invoice.pdf", "wb") as f:
f.write(pdf_bytes)
print("PDF generated successfully")
except NonRetryableError as e:
print(f"Fix the request or settings: {e}")
except (RuntimeError, requests.exceptions.RequestException) as e:
print(f"Transient error (retry later): {e}")
Node.js
Uses the built-in fetch in Node.js 18 or later (no extra packages).
const fs = require('node:fs/promises');
const API_BASE = 'https://pdf.funbrew.cloud';
const RETRYABLE_STATUS_CODES = new Set([500, 502, 503, 504]);
class NonRetryableError extends Error {}
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function readMessage(response) {
const text = await response.text();
try {
return JSON.parse(text).message ?? text;
} catch {
return text.slice(0, 200);
}
}
/**
* Generate a PDF with exponential backoff retry and return the PDF bytes.
*/
async function generatePdfWithRetry(html, apiKey, options = {}, retryConfig = {}) {
const {
maxRetries = 5,
initialDelay = 1000, // ms
maxDelay = 60000,
backoffMultiplier = 2,
} = retryConfig;
let delay = initialDelay;
let lastError;
for (let attempt = 0; attempt <= maxRetries; attempt++) {
let waitTime;
try {
const response = await fetch(`${API_BASE}/api/pdf/generate-from-html`, {
method: 'POST',
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({ html, options: { 'page-size': 'A4', ...options } }),
signal: AbortSignal.timeout(120000),
});
if (response.ok) {
const { data } = await response.json();
const pdfResponse = await fetch(data.download_url, {
headers: { Authorization: `Bearer ${apiKey}` },
signal: AbortSignal.timeout(120000),
});
if (!pdfResponse.ok) {
throw new NonRetryableError(
`Download failed: HTTP ${pdfResponse.status} - ${await readMessage(pdfResponse)}`
);
}
return Buffer.from(await pdfResponse.arrayBuffer());
}
const message = await readMessage(response);
const retryAfter = response.headers.get('retry-after');
if (response.status === 429 && retryAfter) {
// Per-minute limit: wait Retry-After seconds
waitTime = Number(retryAfter) * 1000;
} else if (!RETRYABLE_STATUS_CODES.has(response.status)) {
throw new NonRetryableError(`Non-retryable error: HTTP ${response.status} - ${message}`);
}
lastError = new Error(`HTTP ${response.status} - ${message}`);
} catch (error) {
if (error instanceof NonRetryableError) throw error;
lastError = error; // TimeoutError or network error
}
if (attempt >= maxRetries) break;
if (waitTime === undefined) {
// Exponential backoff + 0-1s jitter
waitTime = Math.min(delay + Math.random() * 1000, maxDelay);
delay = Math.min(delay * backoffMultiplier, maxDelay);
}
console.warn(`Retry ${attempt + 1}/${maxRetries} in ${(waitTime / 1000).toFixed(2)}s`);
await sleep(waitTime);
}
throw new Error(`Max retries (${maxRetries}) reached`, { cause: lastError });
}
// Usage
generatePdfWithRetry(
'<h1>Invoice</h1><p>Total: $100.00</p>',
process.env.FUNBREW_PDF_API_KEY,
{ 'page-size': 'A4' },
{ maxRetries: 3, initialDelay: 2000 }
)
.then(async (pdfBuffer) => {
await fs.writeFile('invoice.pdf', pdfBuffer);
console.log('PDF generated successfully');
})
.catch((err) => {
console.error('Error:', err.message);
process.exitCode = 1;
});
PHP
<?php
final class RetryableApiException extends \RuntimeException
{
public function __construct(string $message, int $code, public readonly ?int $retryAfter = null)
{
parent::__construct($message, $code);
}
}
class PdfApiClient
{
private const RETRYABLE_STATUS_CODES = [500, 502, 503, 504];
public function __construct(
private string $apiKey,
private string $baseUrl = 'https://pdf.funbrew.cloud',
private int $maxRetries = 5,
private float $initialDelay = 1.0,
private float $maxDelay = 60.0,
private float $backoffMultiplier = 2.0,
) {}
/**
* Generate a PDF with exponential backoff retry and return the PDF bytes.
*
* @throws \RuntimeException When max retries are exhausted
* @throws \InvalidArgumentException For non-retryable errors
*/
public function generateWithRetry(string $html, array $options = []): string
{
$delay = $this->initialDelay;
$lastError = null;
for ($attempt = 0; $attempt <= $this->maxRetries; $attempt++) {
try {
$body = $this->request('POST', '/api/pdf/generate-from-html', [
'html' => $html,
'options' => array_merge(['page-size' => 'A4'], $options),
]);
$downloadUrl = json_decode($body, true)['data']['download_url'];
return $this->request('GET', $downloadUrl);
} catch (RetryableApiException $e) {
$lastError = $e;
if ($attempt >= $this->maxRetries) {
break;
}
if ($e->retryAfter !== null) {
// Per-minute limit: wait Retry-After seconds
$waitTime = (float) $e->retryAfter;
} else {
// Exponential backoff with 0-1s jitter
$waitTime = min($delay + mt_rand(0, 1000) / 1000, $this->maxDelay);
$delay = min($delay * $this->backoffMultiplier, $this->maxDelay);
}
error_log('Retry '.($attempt + 1)."/{$this->maxRetries} in {$waitTime}s");
usleep((int) ($waitTime * 1_000_000));
}
}
throw new \RuntimeException(
"Max retries ({$this->maxRetries}) reached: ".$lastError?->getMessage(),
0,
$lastError
);
}
private function request(string $method, string $urlOrPath, ?array $json = null): string
{
$url = str_starts_with($urlOrPath, 'https://') ? $urlOrPath : $this->baseUrl.$urlOrPath;
$headers = ["Authorization: Bearer {$this->apiKey}", 'Accept: application/json'];
$retryAfter = null;
$ch = curl_init($url);
$curlOptions = [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 120,
CURLOPT_HEADERFUNCTION => function ($ch, string $line) use (&$retryAfter): int {
if (stripos($line, 'Retry-After:') === 0) {
$retryAfter = (int) trim(substr($line, strlen('Retry-After:')));
}
return strlen($line);
},
];
if ($json !== null) {
$curlOptions[CURLOPT_POSTFIELDS] = json_encode($json);
$headers[] = 'Content-Type: application/json';
}
$curlOptions[CURLOPT_HTTPHEADER] = $headers;
curl_setopt_array($ch, $curlOptions);
$body = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($body === false) {
throw new RetryableApiException('cURL error: '.curl_error($ch), 0);
}
if ($statusCode === 200) {
return $body;
}
$message = json_decode($body, true)['message'] ?? 'Unknown error';
if ($statusCode === 429 && $retryAfter !== null) {
throw new RetryableApiException($message, 429, $retryAfter);
}
if (in_array($statusCode, self::RETRYABLE_STATUS_CODES, true)) {
throw new RetryableApiException($message, $statusCode);
}
throw new \InvalidArgumentException("Non-retryable error: HTTP {$statusCode} - {$message}", $statusCode);
}
}
// Usage
$client = new PdfApiClient(apiKey: getenv('FUNBREW_PDF_API_KEY'));
try {
$pdf = $client->generateWithRetry(
html: '<h1>Invoice</h1><p>Total: $100.00</p>',
options: ['page-size' => 'A4']
);
file_put_contents('invoice.pdf', $pdf);
echo "PDF generated successfully\n";
} catch (\InvalidArgumentException $e) {
echo 'Fix the request or settings: '.$e->getMessage()."\n";
} catch (\RuntimeException $e) {
echo 'Transient error (retry later): '.$e->getMessage()."\n";
}
Error Logging Best Practices
Good logging makes it easy to detect problems early and pinpoint root causes.
What to Include in Logs
Generate endpoints return an X-Job-Id response header (you can also set your own by sending X-Job-Id with the request). Logging it lets you point to a specific request when you contact support.
{
"timestamp": "2026-03-31T12:00:00Z",
"level": "error",
"event": "pdf_generation_failed",
"job_id": "9b2f6c1e-4a7d-4c1b-9f0e-3d5a8b7c2e10",
"attempt": 3,
"max_retries": 5,
"status_code": 503,
"error_message": "Service Unavailable",
"html_size_bytes": 15420,
"duration_ms": 5230,
"will_retry": true
}
Log Level Guidelines
| Situation | Log Level | Action |
|---|---|---|
| Retryable error (in progress) | warn |
No alert needed |
| Max retries reached | error |
Trigger alert |
| Auth or permission error (401/403) | error |
Immediate alert |
Monthly or storage limit (429 without Retry-After) |
error |
Immediate alert |
| Input error (422) | warn |
Code fix needed |
| Success (after retries) | info |
Record only |
FUNBREW PDF-Specific Tips
FUNBREW PDF webhooks send three events — pdf.generated, pdf.downloaded, and pdf.expired — and there is no event for a failed generation. Raise failure alerts from client-side logs like the ones above. For how to use webhooks, see the Webhook Integration Guide. For real-world error handling patterns in production workflows, the Invoice PDF Automation Guide and Certificate PDF Automation Guide both include failure-recovery strategies. For Next.js/Nuxt-specific error handling patterns, see the Next.js & Nuxt PDF API Guide.
Handling Timeouts
If your HTML references external resources, inlining them as Base64 removes the external fetches during conversion.
{
"html": "<img src='data:image/png;base64,iVBORw0KGgo...' />",
"options": {
"page-size": "A4"
}
}
Avoiding Rate Limits
On every plan (including Free), batch processing (POST /api/pdf/batch) lets you submit up to 100 items in one request, saving requests against the per-minute limit. The response is 201 with a batch_id, and each PDF is generated asynchronously (each item still counts toward the monthly limit).
{
"items": [
{ "type": "html", "html": "<h1>Invoice #001</h1>", "options": { "page-size": "A4" } },
{ "type": "html", "html": "<h1>Invoice #002</h1>", "options": { "page-size": "A4" } }
]
}
Rotating API Keys
If authentication errors persist, issue a new API key in the dashboard, switch over, and delete the old key. If you restrict a key's scopes, give it both generate and download, or the second (download) step will fail with 403. Always use separate keys for production and staging. Rate limits vary by plan, so if you are hitting 429s frequently, check the Pricing Comparison to find a plan that fits your volume.
Browse real-world automation examples — invoices at /use-cases/invoices, reports at /use-cases/reports, and more at the full Use Cases gallery.
Summary
Key takeaways for robust PDF API error handling:
- Classify errors: Distinguish retryable (429 with
Retry-After, 5xx, connection errors) from non-retryable (422, 401, 403, 404, 429 withoutRetry-After) - Use exponential backoff: Increase wait time exponentially, add jitter, and honor
Retry-Afteron 429 - Set limits: Always define max retries and max wait time (retrying a
POSTcan create duplicates) - Log everything: Record
X-Job-Id, status code, and retry count - Alert on critical failures: Max retries reached, auth errors, and monthly limits should page someone
For the full production readiness picture — including error handling, monitoring, and scaling — see the PDF API Production Checklist. Check the FUNBREW PDF API reference for error status codes and recommended responses. Use the playground to test your HTML before integrating. To see certificate or invoice generation in action, visit the Use Cases gallery. For serverless PDF generation on AWS Lambda, see the Serverless PDF Guide. Django/FastAPI integration is covered in the Django/FastAPI Guide. For migration-specific error patterns, see the Puppeteer Migration Guide. Report generation error handling is in the Report PDF Generation Guide. Compare PDF API error handling approaches in the PDF API Comparison.