April 1, 2026

PDF API Production Guide 2026: Rate Limits & Cost Control

productionAPIPDF generationmonitoringbest practices

Getting PDF API integration to work in development is one thing. Keeping it stable in production is another. APIs that behave perfectly in testing can start timing out under traffic spikes, rate limit violations can halt batch jobs mid-run, and unexpected costs can show up at the end of the month.

This article is a 2026 production guide for teams deploying FUNBREW PDF or any PDF generation API to production. It integrates and extends the detailed guidance from three companion articles — error handling, security, and batch processing — into a single pre-launch reference. Updated for 2026 with new sections on observability metrics, cost estimation, and modern monitoring tooling.

If you are new to PDF APIs, start with the HTML to PDF complete guide or the quickstart by language.


1. API Key Management and Rotation

Your API key is the credential to your PDF generation service. A leaked key means unauthorized usage that eats into your plan's monthly cap and potential exposure of generated documents.

Separate Keys per Environment

# Production (a key issued for production)
FUNBREW_PDF_API_KEY=sk-xxxxxxxxxxxxxxxxxxxx

# Staging (a separate key issued for staging)
FUNBREW_PDF_API_KEY=sk-yyyyyyyyyyyyyyyyyyyy

# Local development (a separate key issued for development)
FUNBREW_PDF_API_KEY=sk-zzzzzzzzzzzzzzzzzzzz

FUNBREW PDF API keys are issued on the API keys page of the dashboard, and each key gets its own permissions (generate, download, and so on). If the same key generates PDFs and downloads them, give it both permissions.

Sharing one key across environments means developer laptops consume production quota and mistakes in local testing can affect production state.

Secret Management Tools

.env files work fine for small teams. As the team grows, adopt a dedicated secrets manager.

Tool Best for
AWS Secrets Manager Applications hosted on AWS
HashiCorp Vault Multi-cloud or on-premise environments
Doppler Small-to-medium teams wanting centralized secrets
GitHub Actions Secrets CI/CD pipelines only

Automating Key Rotation

FUNBREW PDF has no REST API for issuing or deleting API keys. Issue the new key in the dashboard and script only the secret swap.

import boto3

def store_new_pdf_api_key(new_key: str) -> None:
    """Store a key issued in the dashboard in AWS Secrets Manager."""
    client = boto3.client('secretsmanager', region_name='us-east-1')

    # Update Secrets Manager (the app picks up the new key on its next read)
    client.put_secret_value(
        SecretId='funbrew-pdf-api-key-prod',
        SecretString=new_key,
    )
    print("New API key stored. Delete the old key in the dashboard after the overlap window")

FUNBREW PDF API keys do not expire, so pick the rotation interval from your own security policy (for example, 90 days). For a recurring reminder you can use a scheduler such as Amazon EventBridge Scheduler, which supports cron expressions. After switching to the new key, do not delete the old one immediately; keep an overlap window so in-flight requests do not fail during deployment.

For the full security guide including IP restrictions and input validation, see PDF API Security Guide.

Checklist

  • Separate API keys for production, staging, and development
  • .env excluded from version control via .gitignore
  • No API keys in frontend JavaScript
  • Rotation interval (for example, 90 days) and owner decided
  • Key revocation procedure documented

2. Rate Limits and Application-Side Throttling

PDF generation APIs usually cap requests per plan. FUNBREW PDF has two caps per company (account): requests per minute and PDFs generated per month. Exceeding either returns 429 Too Many Requests.

Plan Requests per minute PDFs per month
Free 10 30
Pro 120 1,000
Business 300 10,000

For high-volume or dedicated environments, limits are arranged individually (contact us).

The per-minute cap applies to downloads of generated PDFs (GET /api/pdf/download/{filename}) as well as to generation. Generating one PDF and downloading it costs two requests.

Inspect Your Rate Limit Headers

# Check rate limit status from response headers (this request also generates one PDF)
curl -s -D - -o /dev/null -X POST "https://pdf.funbrew.cloud/api/pdf/generate-from-html" \
  -H "Authorization: Bearer $FUNBREW_PDF_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"html": "<h1>test</h1>"}' | grep -i "x-ratelimit"

# Example response headers (Pro plan):
# X-RateLimit-Limit: 120
# X-RateLimit-Remaining: 119

A request made only to check the headers still counts toward your monthly PDFs, so in practice log the headers from the responses your app already receives. X-RateLimit-Reset and Retry-After are only sent when the cap is hit and a 429 is returned.

Implement a Token Bucket on Your Side

Rather than hitting the API limit and handling 429 responses reactively, throttle proactively from your application.

// Token bucket rate limiter (Node.js)
class RateLimiter {
  constructor(requestsPerMinute) {
    this.tokens = requestsPerMinute;
    this.maxTokens = requestsPerMinute;
    this.refillRate = requestsPerMinute / 60; // tokens per second
    this.lastRefill = Date.now();
  }

  async acquire() {
    this._refill();

    if (this.tokens < 1) {
      const waitMs = (1 - this.tokens) / this.refillRate * 1000;
      await new Promise(resolve => setTimeout(resolve, waitMs));
      this._refill();
    }

    this.tokens -= 1;
  }

  _refill() {
    const now = Date.now();
    const elapsed = (now - this.lastRefill) / 1000;
    this.tokens = Math.min(
      this.maxTokens,
      this.tokens + elapsed * this.refillRate
    );
    this.lastRefill = now;
  }
}

// Run at 80% of the Pro plan (120 requests/min)
// Generating and downloading costs two requests per PDF, so about 48 PDFs per minute
const limiter = new RateLimiter(96);

async function generatePdf(html) {
  await limiter.acquire();
  // call PDF API (acquire() again before the download)
}

Operating at 80% of your plan limit keeps a buffer for traffic spikes without triggering rate limit errors.

For plan-by-plan pricing, see PDF API Pricing Comparison.

Checklist

  • Per-minute rate limit and monthly PDF cap for your current plan are documented
  • Application-side throttling is implemented
  • Peak request volume is within plan limits
  • X-RateLimit-Remaining header is monitored

3. Error Handling and Retry Design

Production environments have transient failures. Network blips, API maintenance windows, and rendering timeouts happen. Your integration must handle them without losing data or crashing.

Classify Errors Before Retrying

FUNBREW PDF returns errors as JSON shaped like {"success": false, "message": "..."}. There are three kinds of 429, and only the per-minute cap, which comes with a Retry-After header, clears by waiting. A 429 from the monthly PDF cap or the storage cap has no Retry-After and will not clear by waiting.

NON_RETRYABLE_STATUS_CODES = {401, 403, 404, 422}

def should_retry(status_code: int, headers) -> bool:
    """Decide whether an error is worth retrying."""
    if status_code == 429:
        # Only a 429 with Retry-After (per-minute cap) clears by waiting
        return 'Retry-After' in headers
    return status_code >= 500
Status Code Meaning Retry? Action
422 Validation error No Fix html or option values
401 / 403 Auth error, missing permission, feature not in plan, IP restriction No Check the API key, its permissions, and your plan
404 Template or PDF not found, or expired No Check what you asked for
429 (with Retry-After) Per-minute cap Yes Wait for the Retry-After seconds
429 (no Retry-After) Monthly PDF or storage cap No Review your plan or stored PDFs
500 / 502 / 503 / 504 Server-side or in-path error Yes Exponential backoff

Exponential Backoff with Jitter

The generation API returns JSON that contains the PDF's download URL (data.download_url). Fetch the PDF itself with a GET to that URL using the same API key.

interface RetryConfig {
  maxRetries: number;
  initialDelayMs: number;
  maxDelayMs: number;
  backoffMultiplier: number;
}

const DEFAULT_RETRY_CONFIG: RetryConfig = {
  maxRetries: 5,
  initialDelayMs: 1000,
  maxDelayMs: 60000,
  backoffMultiplier: 2,
};

const BASE_URL = 'https://pdf.funbrew.cloud';

async function generatePdfWithRetry(
  html: string,
  apiKey: string,
  config: RetryConfig = DEFAULT_RETRY_CONFIG
): Promise<Buffer> {
  let delay = config.initialDelayMs;

  for (let attempt = 0; attempt <= config.maxRetries; attempt++) {
    const response = await fetch(`${BASE_URL}/api/pdf/generate-from-html`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      },
      body: JSON.stringify({ html }),
      signal: AbortSignal.timeout(120_000),
    });

    if (response.ok) {
      const { data } = await response.json();
      const pdfResponse = await fetch(data.download_url, {
        headers: { 'Authorization': `Bearer ${apiKey}` },
        signal: AbortSignal.timeout(120_000),
      });
      if (!pdfResponse.ok) {
        throw new Error(`PDF download failed: HTTP ${pdfResponse.status}`);
      }
      return Buffer.from(await pdfResponse.arrayBuffer());
    }

    // Retry only a 429 with Retry-After (per-minute cap) and 5xx
    const retryAfter = response.headers.get('retry-after');
    const isRetryable = (response.status === 429 && retryAfter !== null) || response.status >= 500;
    if (!isRetryable || attempt === config.maxRetries) {
      throw new Error(`PDF generation failed: HTTP ${response.status}`);
    }

    // Prefer the Retry-After seconds when present
    const waitMs = retryAfter
      ? parseFloat(retryAfter) * 1000
      : Math.min(delay + Math.random() * 1000, config.maxDelayMs);

    console.warn(`Retry ${attempt + 1}/${config.maxRetries}: waiting ${(waitMs / 1000).toFixed(1)}s`);
    await new Promise(resolve => setTimeout(resolve, waitMs));
    delay = Math.min(delay * config.backoffMultiplier, config.maxDelayMs);
  }

  throw new Error('Max retries exceeded');
}

POST is not guaranteed to be idempotent, so retrying after a timeout can generate the same PDF twice and use two of your monthly PDFs.

The full retry implementation in curl, Python, Node.js, and PHP is covered in the PDF API Error Handling Guide.

Checklist

  • Retryable vs. non-retryable errors are classified
  • Exponential backoff with jitter is implemented
  • Max retry count and max wait time are capped
  • Alerts fire when max retries are exhausted
  • The X-Job-Id response header is logged for traceability

4. Monitoring and Alerting

The goal is to detect problems before users report them. This requires tracking the right metrics and setting actionable alert thresholds.

Key Metrics to Track

Metric Warning Threshold Critical Threshold
PDF generation failure rate > 1% > 5%
p50 response time > 5s > 15s
p99 response time > 30s > 60s
Retry rate (per minute) > 10% > 30%
X-RateLimit-Remaining < 30% < 10%

Sending Metrics to Datadog

import os
import time
import functools
import requests
from datadog import initialize, statsd

# Where DogStatsD metrics go (the Datadog Agent)
initialize(statsd_host='localhost', statsd_port=8125)

def track_pdf_generation(func):
    """Decorator that auto-collects PDF generation metrics."""
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        tags = ['service:pdf-generator', 'env:production']

        try:
            result = func(*args, **kwargs)
            duration_ms = (time.perf_counter() - start) * 1000

            statsd.histogram('pdf.generation.duration_ms', duration_ms, tags=tags)
            statsd.increment('pdf.generation.success', tags=tags)
            return result

        except Exception as e:
            duration_ms = (time.perf_counter() - start) * 1000
            error_tags = tags + [f'error_type:{type(e).__name__}']

            statsd.histogram('pdf.generation.duration_ms', duration_ms, tags=error_tags)
            statsd.increment('pdf.generation.failure', tags=error_tags)
            raise

    return wrapper

@track_pdf_generation
def generate_invoice_pdf(customer_data):
    headers = {'Authorization': f"Bearer {os.environ['FUNBREW_PDF_API_KEY']}"}
    response = requests.post(
        'https://pdf.funbrew.cloud/api/pdf/generate-from-html',
        headers={**headers, 'Accept': 'application/json'},
        json={'html': build_invoice_html(customer_data)},  # build_invoice_html is your own HTML builder
        timeout=120,
    )
    response.raise_for_status()

    # The generation API returns JSON; GET download_url with the same key to fetch the PDF
    pdf = requests.get(response.json()['data']['download_url'], headers=headers, timeout=120)
    pdf.raise_for_status()
    return pdf.content

Combining Monitoring with Webhooks

Webhook integration (available on every plan) pushes PDF generated (pdf.generated), downloaded (pdf.downloaded), and expired (pdf.expired) events to your server. There is no event for a failed generation, so detect failures from your client-side logs and metrics. If you also need to show live progress in the browser while the backend waits for the webhook, you can pair it with the SSE progress streaming guide — webhooks handle the backend, SSE handles the UI.

// Example webhook payload (pdf.generated)
{
  "event": "pdf.generated",
  "timestamp": "2026-04-01T12:00:00.000000Z",
  "data": {
    "filename": "abc123.pdf",
    "download_url": "https://pdf.funbrew.cloud/dl/xxxxxxxx",
    "file_size": 245120,
    "source_type": "html",
    "expires_at": "2026-04-02T12:00:00.000000Z"
  }
}

Prometheus Alert Rules

# Prometheus alerting rules. Routing to PagerDuty etc. is configured in Alertmanager
groups:
  - name: pdf-api
    rules:
      - alert: PdfGenerationHighFailureRate
        expr: |
          rate(pdf_generation_failure_total[5m]) /
          rate(pdf_generation_total[5m]) > 0.05
        for: 2m
        labels:
          severity: critical
        annotations:
          summary: "PDF generation failure rate exceeds 5%"
          description: "Failure rate over last 5m: {{ $value | humanizePercentage }}"

      - alert: PdfGenerationHighLatency
        expr: histogram_quantile(0.99, rate(pdf_generation_duration_ms_bucket[5m])) > 30000
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "PDF generation p99 latency exceeds 30 seconds"

Checklist

  • Generation failure rate tracked in real time
  • Response time (p50 and p99) tracked
  • Rate limit headroom alert configured
  • On-call notification for critical failures
  • Job completion detected via the pdf.generated webhook or the batch status endpoint

5. Cost Optimization

FUNBREW PDF is not billed per request: plans are monthly subscriptions with a cap on PDFs generated per month (Free covers 30 per month). Cutting redundant generation uses less of that cap, so you can stay on a smaller plan.

Strategy 1: Cache Identical PDFs

For PDFs generated from static content (terms of service, standard agreements), caching is highly effective.

import hashlib
import redis
import requests
import os

class PdfCache:
    def __init__(self, redis_client, ttl_seconds=86400):
        self.redis = redis_client
        self.ttl = ttl_seconds  # Default: 24 hours

    def get_cache_key(self, html: str, options: dict) -> str:
        """Generate a deterministic cache key from HTML and options."""
        content = f"{html}{str(sorted(options.items()))}"
        return f"pdf_cache:{hashlib.sha256(content.encode()).hexdigest()}"

    def generate_with_cache(self, html: str, options: dict = None) -> bytes:
        options = options or {}
        key = self.get_cache_key(html, options)

        cached = self.redis.get(key)
        if cached:
            return cached

        # Cache miss: generate, then fetch download_url (two steps)
        headers = {'Authorization': f"Bearer {os.environ['FUNBREW_PDF_API_KEY']}"}
        response = requests.post(
            'https://pdf.funbrew.cloud/api/pdf/generate-from-html',
            headers={**headers, 'Accept': 'application/json'},
            json={'html': html, 'options': options},
            timeout=120,
        )
        response.raise_for_status()

        pdf = requests.get(response.json()['data']['download_url'], headers=headers, timeout=120)
        pdf.raise_for_status()
        pdf_bytes = pdf.content
        self.redis.setex(key, self.ttl, pdf_bytes)
        return pdf_bytes

cache = PdfCache(redis.Redis(host='localhost', port=6379))
pdf = cache.generate_with_cache(
    html='<h1>Terms of Service</h1><p>...</p>',
    options={'page-size': 'A4'}
)

Strategy 2: Batch Multiple PDFs per Request

Submitting several PDFs in one request saves requests against the per-minute cap (available on every plan, up to 100 items per call). The monthly cap still counts every PDF, so batching does not reduce monthly usage. See the PDF Batch Processing Guide for the full implementation.

# One API call submits three PDFs
curl -X POST "https://pdf.funbrew.cloud/api/pdf/batch" \
  -H "Authorization: Bearer $FUNBREW_PDF_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "items": [
      { "type": "html", "html": "<h1>Invoice #001</h1>", "options": { "page-size": "A4" } },
      { "type": "html", "html": "<h1>Invoice #002</h1>", "options": { "page-size": "A4" } },
      { "type": "html", "html": "<h1>Invoice #003</h1>", "options": { "page-size": "A4" } }
    ]
  }'

The response carries a batch_id and generation runs asynchronously. Check completion with GET /api/pdf/batch/{batch_id} or the pdf.generated webhook sent for each PDF.

Strategy 3: Regenerate Only When Data Changes

from datetime import datetime, UTC

class PdfGenerationRecord:
    """Track generation history and skip regeneration when data hasn't changed."""

    def generate_if_outdated(
        self,
        record_id: str,
        html: str,
        data_updated_at: datetime,
    ) -> bytes:
        last_generated = self._get_last_generated(record_id)

        if last_generated and last_generated >= data_updated_at:
            return self._get_cached_pdf(record_id)

        pdf_bytes = self._call_pdf_api(html)
        self._store(record_id, pdf_bytes, generated_at=datetime.now(UTC))
        return pdf_bytes

Estimated Savings

Monthly PDFs (no optimization) 30% cache hit 50% cache hit
1,000 700 (−300) 500 (−500)
10,000 7,000 (−3,000) 5,000 (−5,000)

Batching reduces requests per minute, not the number of PDFs generated per month.

For plan pricing details, see PDF API Pricing Comparison.

Checklist

  • Caching implemented for identical or rarely-changing PDFs
  • Bulk generation submitted as batch requests to save per-minute requests
  • Unnecessary re-generation prevented by checking data change timestamps
  • Monthly PDF count reviewed to confirm plan is appropriate

6. Scaling with Queues and Async Processing

Synchronous PDF generation (request → wait → response) works for small volumes. Under heavy load or batch jobs, queue-based async processing is more resilient.

When to Use Each Pattern

Scenario Recommended Pattern Reason
User clicks "Download" Synchronous (when the wait is acceptable) Immediate feedback required
Monthly invoice batch (1,000+) Async + queue Too slow to block a request
Scheduled report generation Async + scheduler Runs fully in background
Bulk certificate issuance Async + batch (every plan) Saves requests per minute

Redis Queue Pattern with BullMQ (Node.js)

import { Queue, Worker } from 'bullmq';
import { Redis } from 'ioredis';

// ioredis connections passed to a Worker must set maxRetriesPerRequest: null
const connection = new Redis({ host: 'localhost', port: 6379, maxRetriesPerRequest: null });

const pdfQueue = new Queue('pdf-generation', { connection });

// Enqueue a job (called from your API endpoint)
export async function enqueuePdfGeneration(jobData) {
  const job = await pdfQueue.add('generate', jobData, {
    attempts: 5,
    backoff: {
      type: 'exponential',
      delay: 1000, // 1s, 2s, 4s, ...
    },
    removeOnComplete: { count: 1000 },
    removeOnFail: { count: 500 },
  });

  return { jobId: job.id };
}

// Worker (horizontally scalable)
const worker = new Worker(
  'pdf-generation',
  async (job) => {
    const { html, options, webhookUrl } = job.data;

    const auth = { 'Authorization': `Bearer ${process.env.FUNBREW_PDF_API_KEY}` };
    const response = await fetch('https://pdf.funbrew.cloud/api/pdf/generate-from-html', {
      method: 'POST',
      headers: {
        ...auth,
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      },
      body: JSON.stringify({ html, options }),
      signal: AbortSignal.timeout(120_000),
    });

    if (!response.ok) {
      throw new Error(`API error: HTTP ${response.status}`);
    }

    // The generation API returns JSON; GET download_url with the same key to fetch the PDF
    const { data } = await response.json();
    const pdfResponse = await fetch(data.download_url, { headers: auth, signal: AbortSignal.timeout(120_000) });
    if (!pdfResponse.ok) {
      throw new Error(`Download error: HTTP ${pdfResponse.status}`);
    }
    const pdfBuffer = Buffer.from(await pdfResponse.arrayBuffer());
    const downloadUrl = await uploadToStorage(pdfBuffer);

    if (webhookUrl) {
      await notifyWebhook(webhookUrl, { downloadUrl, jobId: job.id });
    }

    return { downloadUrl };
  },
  {
    connection,
    concurrency: 10, // Tune so total workers × concurrency stays within rate limit
  }
);

worker.on('failed', (job, err) => {
  console.error(`Job ${job?.id} failed:`, err.message);
  // Trigger PagerDuty / Slack alert
});

Kubernetes Horizontal Pod Autoscaler

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: pdf-worker-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: pdf-worker
  minReplicas: 2
  maxReplicas: 20
  metrics:
    - type: External
      external:
        metric:
          name: bullmq_queue_size
          selector:
            matchLabels:
              queue: pdf-generation
        target:
          type: AverageValue
          averageValue: "50" # Max 50 queued jobs per worker pod

Using an External metric requires your monitoring system to expose the queue length to Kubernetes (for example through a metrics adapter).

When scaling out workers, remember the API rate limit stays fixed. Keep workers × concurrency within your plan's per-minute limit.

Checklist

  • Batch and bulk jobs processed via queue, not synchronous requests
  • Worker concurrency tuned to stay within API rate limits
  • Queue depth (backlog size) monitored
  • Dead Letter Queue configured for failed jobs
  • Worker auto-scaling (HPA or equivalent) verified

7. Large File Upload Operations

When your workflow involves receiving large PDF files from customers — rather than generating PDFs from HTML — you quickly run into server-side size limits such as PHP's upload_max_filesize and Nginx's client_max_body_size. On top of that, a dropped mobile connection mid-upload means starting over from scratch, which is a significant UX failure for users submitting multi-hundred-megabyte documents.

Limitations of Standard Multipart Uploads

Problem Symptom
Size limits Nginx returns 413 above client_max_body_size; PHP rejects uploads above upload_max_filesize / post_max_size
Proxy timeout Connection drops during long upload of large files
Network interruption Wi-Fi drops or mobile goes offline → must restart from zero
Progress reporting Accurate upload progress is hard to surface in the UI

tus.io Resumable Upload (Recommended)

FUNBREW PDF released support for the tus.io resumable upload protocol (/api/pdf/uploads) on May 31, 2026. tus is an open protocol that combines chunking, offset tracking, and resume, which eases the problems above.

  • Chunking: The file can be sent as several PATCH requests, so a single request is less likely to hit a size limit
  • Resume: After a network drop, the client sends a HEAD request to read the current Upload-Offset and continues from that byte
  • Parallel uploads: The Concatenation extension uploads several partial uploads in parallel and joins them into one at the end
# Reserve an upload slot and receive the Location URL
LOCATION=$(curl -s -D - -X POST "https://pdf.funbrew.cloud/api/pdf/uploads" \
  -H "X-API-Key: $FUNBREW_PDF_API_KEY" \
  -H "Tus-Resumable: 1.0.0" \
  -H "Upload-Length: $(wc -c < document.pdf | tr -d ' ')" \
  -H "Upload-Metadata: filename $(printf '%s' document.pdf | base64)" \
  | grep -i "^location:" | tr -d '\r' | awk '{print $2}')

# Send the body (this example sends it in one request; to split, repeat PATCH with an advancing Upload-Offset)
curl -X PATCH "$LOCATION" \
  -H "X-API-Key: $FUNBREW_PDF_API_KEY" \
  -H "Tus-Resumable: 1.0.0" \
  -H "Upload-Offset: 0" \
  -H "Content-Type: application/offset+octet-stream" \
  --data-binary @document.pdf

# Pass the upload key directly to a PDF processing endpoint (if compression is enabled on your plan)
curl -X POST "https://pdf.funbrew.cloud/api/pdf/compress" \
  -H "X-API-Key: $FUNBREW_PDF_API_KEY" \
  -H "Content-Type: application/json" \
  -d "{\"upload_id\": \"$(basename $LOCATION)\", \"quality\": \"medium\"}"

The key you get when the upload finishes (the last segment of the Location URL) can be passed as upload_id to compress, extract-text, and to-image, or in upload_ids to merge. The default per-file limit is 5 GB.

The browser JavaScript SDK (@funbrew/pdf-client) wraps tus-js-client, but as of November 14, 2026 it is not published on npm. It also sends the API key from the browser in the X-API-Key header, so check that this fits section 8's "no API keys in frontend code" before using it.

For the complete implementation guide — including tus-js-client code, chunk size recommendations, Nginx configuration, and GC behavior — see the tus Resumable Upload Complete Guide.

Checklist

  • tus resumable upload used for any workflow that receives large files from users
  • If uploads are relayed through your own Nginx, client_max_body_size (0 disables the check) and proxy_request_buffering off were considered
  • Chunk size chosen by measuring on real connections
  • Upload completion handled via the tus.upload.completed webhook event (webhooks are available on every plan)

8. Security Checklist

Before going live, verify the following security controls. The full guide with code examples is in PDF API Security Guide.

Input Validation

// Escape all user input before embedding in HTML
function escapeHtml(str) {
  return String(str)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#039;');
}

// Enforce an HTML size limit (e.g., 1MB; the API itself caps html at 5,000,000 characters by default and returns 422 above it)
const MAX_HTML_SIZE_BYTES = 1_048_576;

function validateHtmlInput(html) {
  if (Buffer.byteLength(html, 'utf8') > MAX_HTML_SIZE_BYTES) {
    throw new Error('HTML is too large. Maximum size is 1MB.');
  }
}

Security Checklist

Category Check Item Priority
Auth API keys in environment variables, not source code Required
Auth Separate keys for production, staging, and development Required
Transport HTTPS only Required
Input User input escaped before embedding in HTML Required
Input HTML size validated before sending to API Recommended
Access IP allowlisting to production servers only (Business plan) Recommended
Access API never called directly from frontend JavaScript Required
Data Expiry of generated PDFs (expiration_hours, default 24, max 168) and download limits confirmed Recommended
Audit All API calls logged with timestamps and user IDs Recommended

9. Pre-Launch Deployment Checklist

Use this as a PR template or release checklist before every production deployment.

Setup

  • Production API key issued on the API keys page of the dashboard
  • API key stored in secrets manager or environment variable, not in code
  • .env confirmed absent from Git history
  • E2E tests passing on staging environment

Error Handling

  • Request timeout set to 120 seconds or more
  • Exponential backoff retry logic implemented
  • Non-retryable errors trigger immediate alerts (no silent failures)
  • Error logs include the X-Job-Id, status code, and attempt count

Performance and Scaling

  • Batch and bulk jobs use queue-based async processing
  • Application-side throttling implemented
  • Worker concurrency stays within API rate limits
  • PDF caching implemented where appropriate

Monitoring and Alerting

  • Generation failure rate alert configured (threshold: 5%)
  • Response time alert configured (p99 > 30s)
  • Rate limit headroom alert configured
  • Queue depth monitored
  • Monthly usage visible in dashboard

Security

  • No API keys in frontend code
  • User input HTML-escaped before PDF generation
  • HTTPS enforced for all API calls
  • IP allowlisting configured for production servers (Business plan)

Cost Management

  • Monthly PDF volume estimated and within plan limits
  • Caching or change-detection prevents redundant generation
  • Monthly cost review process established

10. 2026 Observability and Cost Estimation Additions

The following observability and cost-management items were added in the 2026 edition.

OpenTelemetry traces for PDF generation latency

Instrumenting PDF generation spans with OpenTelemetry (OTel) lets you send them to an observability backend and look at which HTML templates, page sizes, or concurrency levels affect latency. Check each vendor's documentation to confirm it accepts OTel traces.

from opentelemetry import trace
from opentelemetry.trace import StatusCode
import time

tracer = trace.get_tracer("pdf-service")

def generate_pdf_traced(html: str, template_name: str = "unknown") -> bytes:
    with tracer.start_as_current_span("pdf.generate") as span:
        span.set_attribute("pdf.template",   template_name)
        span.set_attribute("pdf.html_bytes", len(html.encode()))

        start = time.perf_counter()
        try:
            result = call_pdf_api(html)
            span.set_attribute("pdf.duration_ms",  round((time.perf_counter() - start) * 1000))
            span.set_attribute("pdf.output_bytes", len(result))
            span.set_status(StatusCode.OK)
            return result
        except Exception as exc:
            span.set_status(StatusCode.ERROR, str(exc))
            span.record_exception(exc)
            raise

Per-template usage tracking

Track API calls per template to find optimization candidates. If a specific template accounts for 40% of your monthly PDFs, that is the highest-impact caching target.

interface PdfGenerationEvent {
  templateName:  string;
  durationMs:    number;
  outputBytes:   number;
  cached:        boolean;
  timestamp:     Date;
}

class PdfUsageTracker {
  private events: PdfGenerationEvent[] = [];

  record(event: PdfGenerationEvent) {
    this.events.push(event);
  }

  /** Monthly API calls per template and their share of the plan's monthly cap */
  monthlyReport(monthlyLimit: number) {
    const byTemplate = new Map<string, { requests: number; cachedRequests: number }>();

    for (const e of this.events) {
      const existing = byTemplate.get(e.templateName) ?? { requests: 0, cachedRequests: 0 };
      existing.requests++;
      if (e.cached) existing.cachedRequests++;
      byTemplate.set(e.templateName, existing);
    }

    console.table(
      [...byTemplate.entries()].map(([template, stats]) => ({
        template,
        totalRequests:   stats.requests,
        cachedRequests:  stats.cachedRequests,
        apiCalls:        stats.requests - stats.cachedRequests,
        shareOfLimit:    `${(((stats.requests - stats.cachedRequests) / monthlyLimit) * 100).toFixed(1)}%`,
      }))
    );
  }
}

Example alert thresholds

These are starting-point examples. Tune them to your own traffic and tolerance.

Alert Threshold Channel Action
X-RateLimit-Remaining below 20% of the cap Sustained 5 min PagerDuty (P2) Scale down concurrency or batch size
Generation failure rate > 2% 5-min window Slack #alerts Check recent deployments; HTML changes?
p95 latency > 20s 10-min window Slack #perf Check template complexity; reduce concurrency
Monthly PDFs reach 80% of the plan cap As it happens Slack #finance Review cache hit rate; reconsider the plan
Dead letter queue depth > 10 Instant PagerDuty (P1) Suspect an API outage; check the failed jobs' errors

Monthly volume estimation formula

Before choosing a plan, estimate your monthly PDF count with this formula. FUNBREW PDF plans are capped by PDFs per month (Free 30, Pro 1,000, Business 10,000; contact us for higher volumes).

Monthly PDFs = daily_pdf_volume × working_days × cache_miss_rate

Example:
  500 PDFs/day × 22 working days × 0.40 cache miss rate
  = 4,400 PDFs/month at 60% cache hit rate → fits the Business plan (10,000)

Sensitivity table:
  Cache hit 0%:  500 × 22 × 1.00 = 11,000 PDFs/month → exceeds Business (10,000)
  Cache hit 40%: 500 × 22 × 0.60 =  6,600 PDFs/month
  Cache hit 70%: 500 × 22 × 0.30 =  3,300 PDFs/month

Build a caching layer for any template that generates the same PDF more than twice in a 24-hour window. At a 70% cache hit rate, your monthly PDF count (and use of the plan cap) drops by 70%.

Checklist (2026 additions)

  • OTel spans or equivalent distributed traces configured for PDF generation calls
  • Per-template API calls tracked
  • Rate limit headroom alert threshold decided (for example, below 20%)
  • Monthly PDF estimate documented and checked against the plan cap
  • Dead Letter Queue depth alert configured

Conclusion

Moving from "it works" to "it works reliably in production" is the real work in PDF API integration. You do not need to implement everything at once. Start with the essentials — API key management, error handling, and basic monitoring — then layer in throttling, batching, caching, and queue-based scaling as traffic grows.

Each topic in this checklist has a dedicated deep-dive:

Try the API in the Playground, review the full API documentation, and explore real-world implementations in the use cases section.

Powered by FUNBREW PDF