May 12, 2026

PDF API Rate Limiting | 429 Errors & Exponential Backoff

APIrate limiting429 errorbackoffPDF generation

As your PDF generation volume grows, you'll eventually hit 429 Too Many Requests. Naive retries just repeat the same error. This guide explains how rate limits work and how to implement proper retry strategies — exponential backoff with jitter, preemptive throttling, and batch concurrency control.

This is a deep-dive companion to the rate limiting section in the PDF API Production Guide.

How Rate Limits Work

429 Response Headers

When you exceed the per-minute request limit and get 429 Too Many Requests, the response carries these headers and this body.

HTTP/1.1 429 Too Many Requests
Retry-After: 42
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1748736030
Content-Type: application/json

{
  "success": false,
  "error": "rate_limited",
  "message": "Rate limit exceeded. Please wait and try again.",
  "retry_after": 42
}
Header Meaning
Retry-After Seconds to wait before the next request (only on 429)
X-RateLimit-Limit Requests allowed per minute (unlimited under an individual contract with no per-minute cap)
X-RateLimit-Remaining Requests left in the current one-minute window (also on successful responses)
X-RateLimit-Reset UNIX timestamp when the window resets (only on 429)

Branch on the status code, error and Retry-After in your code, not on the message text.

Kinds of Limits

Some FUNBREW PDF 429s clear if you wait, and some do not. There are no hourly or daily request limits.

Limit Shape of the 429 Clears by waiting?
Requests per minute Has Retry-After and retry_after Yes (60 seconds at most)
PDFs generated per month No Retry-After No (wait for next month or upgrade)
Storage No Retry-After No (delete PDFs you no longer need)

The per-minute limit works like this:

  • It is counted per company (account). Separate API keys share the same limit.
  • Every request under /api/pdf/ counts once, including downloads (GET /api/pdf/download/{filename}). Generating and then downloading takes two requests per PDF.
  • The window is a fixed 60-second window starting at the first request.

Per-minute limits by plan:

Plan Requests per minute
Free 10
Pro 120
Business 300

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

Check what is left of the monthly quota with GET /api/usage or the X-Monthly-Limit / X-Monthly-Used headers on generation responses (see the API Documentation).

Shared Request Helper

The JavaScript examples below generate a PDF from HTML with this helper. Without Content-Type: application/json the JSON body is not read. The generation response is not the PDF itself but JSON containing data.download_url.

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

function apiHeaders() {
  return {
    'Authorization': `Bearer ${process.env.FUNBREW_PDF_API_KEY}`,
    'Content-Type': 'application/json',
    'Accept': 'application/json',
  };
}

// Send one generation request (fetch the PDF from data.download_url in the response)
function requestPdf(html, filename) {
  return fetch(`${API_BASE}/api/pdf/generate-from-html`, {
    method: 'POST',
    headers: apiHeaders(),
    body: JSON.stringify({ html, filename }),
  });
}

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

Basic Retry with Retry-After

The minimum correct implementation: when you receive a 429, wait as long as Retry-After specifies. A 429 without Retry-After (monthly or storage limit) will not clear by waiting, so stop instead of retrying.

async function callWithRetry(requestFn, maxAttempts = 5) {
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    const response = await requestFn();

    if (response.status === 429) {
      const retryAfterHeader = response.headers.get('retry-after');
      if (retryAfterHeader === null) {
        // Monthly or storage limit: waiting will not help
        const body = await response.json();
        throw new Error(`Quota exceeded: ${body.message}`);
      }

      const retryAfter = parseInt(retryAfterHeader, 10);
      console.log(`Rate limited. Waiting ${retryAfter}s (attempt ${attempt}/${maxAttempts})`);

      if (attempt === maxAttempts) {
        throw new Error(`Rate limit exceeded after ${maxAttempts} attempts`);
      }

      await sleep(retryAfter * 1000);
      continue;
    }

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

    return response;
  }
}

// Usage
const response = await callWithRetry(() => requestPdf('<h1>Hello</h1>', 'hello.pdf'));
const { data } = await response.json();
console.log(data.download_url);

Exponential Backoff with Jitter

For a more robust implementation that also handles transient errors (5xx, network errors), use exponential backoff with randomized jitter to prevent thundering-herd retries.

const RETRYABLE_STATUS_CODES = new Set([500, 502, 503, 504]);

async function fetchWithExponentialBackoff(url, options = {}, config = {}) {
  const {
    maxAttempts = 5,
    baseDelayMs = 500,
    maxDelayMs = 30000,
    backoffMultiplier = 2,
    jitterFactor = 0.2, // random extra wait to spread concurrent retries
  } = config;

  let delay = baseDelayMs;

  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    let response;
    try {
      response = await fetch(url, options);
    } catch (networkError) {
      if (attempt === maxAttempts) throw networkError;
      await sleep(delay);
      delay = Math.min(delay * backoffMultiplier, maxDelayMs);
      continue;
    }

    if (response.status === 429) {
      const retryAfterHeader = response.headers.get('retry-after');
      // Do not retry a 429 without Retry-After (monthly or storage limit)
      if (retryAfterHeader === null) return response;

      if (attempt === maxAttempts) throw new Error('Max attempts reached (429)');

      // Honor Retry-After; jitter only adds to it (never wait less)
      const waitMs = parseInt(retryAfterHeader, 10) * 1000;
      const jitter = waitMs * jitterFactor * Math.random();
      await sleep(waitMs + jitter);
      continue;
    }

    if (RETRYABLE_STATUS_CODES.has(response.status) && attempt < maxAttempts) {
      const jitter = delay * jitterFactor * Math.random();
      await sleep(delay + jitter);
      delay = Math.min(delay * backoffMultiplier, maxDelayMs);
      continue;
    }

    return response;
  }
}

Retrying a POST can create the same PDF twice if the server had already finished generating it (and it counts twice toward the monthly quota).

Delay progression on 5xx (baseDelayMs=500, backoffMultiplier=2, jitterFactor=0.2). Jitter adds 0–20%, and with maxAttempts=5 there are four waits.

Wait Theoretical delay With jitter
After 1st failure 500ms 500–600ms
After 2nd failure 1s 1–1.2s
After 3rd failure 2s 2–2.4s
After 4th failure 4s 4–4.8s

Preemptive Throttling

Rather than waiting for a 429, control your request rate proactively to avoid hitting the limit in the first place.

Fixed-Interval Throttling

The class below starts requests at a fixed interval (60 seconds ÷ requests per minute). It does not wait for the previous request to finish, so slow responses do not lower your rate. Unlike a token bucket it allows no bursts; it is the simplest approach.

class RateLimiter {
  constructor({ requestsPerMinute }) {
    this.interval = (60 * 1000) / requestsPerMinute; // ms between request starts
    this.lastRequestTime = 0;
    this.queue = [];
    this.processing = false;
  }

  schedule(fn) {
    return new Promise((resolve, reject) => {
      this.queue.push({ fn, resolve, reject });
      this.processQueue();
    });
  }

  async processQueue() {
    if (this.processing) return;
    this.processing = true;

    while (this.queue.length > 0) {
      const elapsed = Date.now() - this.lastRequestTime;
      const waitTime = Math.max(0, this.interval - elapsed);

      if (waitTime > 0) {
        await sleep(waitTime);
      }

      const { fn, resolve, reject } = this.queue.shift();
      this.lastRequestTime = Date.now();

      // Move on to the next start without waiting for completion
      Promise.resolve().then(fn).then(resolve, reject);
    }

    this.processing = false;
  }
}

// Example: 48 requests per minute, 40% of the Pro plan (120 per minute), leaving room for other jobs in the same company
const limiter = new RateLimiter({ requestsPerMinute: 48 });

function generatePdf(html, filename) {
  return limiter.schedule(() => requestPdf(html, filename));
}

The per-minute limit is per company, so when several processes or servers call the API, split requestsPerMinute so their total stays under the limit. Downloads count against the same limit, so it is safest to send download requests through the same limiter.

Adaptive Throttling from X-RateLimit-Remaining

Read the remaining capacity from response headers and slow down automatically when it gets low. Successful responses carry no X-RateLimit-Reset, so when the remaining count reaches 0 wait up to the window length (60 seconds).

class AdaptiveRateLimiter {
  constructor({ safetyMargin = 0.2 } = {}) {
    this.safetyMargin = safetyMargin; // brake below 20% of the limit
    this.limit = null;
    this.remaining = null;
    this.resetTime = null;
  }

  updateFromHeaders(headers) {
    const limit = headers.get('x-ratelimit-limit');
    const remaining = headers.get('x-ratelimit-remaining');
    const reset = headers.get('x-ratelimit-reset'); // only on 429

    this.limit = limit === null || limit === 'unlimited' ? null : parseInt(limit, 10);
    this.remaining = remaining === null ? null : parseInt(remaining, 10);
    this.resetTime = reset === null ? null : parseInt(reset, 10) * 1000; // ms
  }

  async waitIfNeeded() {
    if (this.limit === null || this.remaining === null) return; // unlimited or unknown

    if (this.remaining <= 0) {
      // Wait until Reset if known, otherwise the window length (60 seconds)
      const waitMs = this.resetTime ? Math.max(0, this.resetTime - Date.now()) : 60 * 1000;
      console.log(`Rate limit reached. Waiting ${Math.ceil(waitMs / 1000)}s.`);
      await sleep(waitMs + 100); // 100ms buffer
      this.remaining = null;
      return;
    }

    // Add a delay once remaining drops below 20% of the limit
    if (this.remaining < this.limit * this.safetyMargin) {
      await sleep(500);
    }
  }
}

const adaptive = new AdaptiveRateLimiter();

async function generatePdfAdaptive(html, filename) {
  await adaptive.waitIfNeeded();

  const response = await requestPdf(html, filename);

  adaptive.updateFromHeaders(response.headers);
  return response;
}

Batch Processing with Concurrency Control

When generating many PDFs, limit parallelism to stay within rate limits.

async function generateBatch(items, { concurrency = 5, requestsPerMinute = 48 } = {}) {
  const limiter = new RateLimiter({ requestsPerMinute });
  const results = [];
  const errors = [];

  // Libraries such as p-limit can also cap concurrency
  const chunks = chunkArray(items, concurrency);

  for (const chunk of chunks) {
    const chunkResults = await Promise.allSettled(
      chunk.map(item =>
        limiter.schedule(() => requestPdf(item.html, item.filename))
      )
    );

    for (const result of chunkResults) {
      if (result.status === 'fulfilled') {
        results.push(result.value);
      } else {
        errors.push(result.reason);
      }
    }
  }

  return { results, errors };
}

function chunkArray(arr, size) {
  const chunks = [];
  for (let i = 0; i < arr.length; i += size) chunks.push(arr.slice(i, i + size));
  return chunks;
}

On every plan (including Free), the batch API (POST /api/pdf/batch) bundles up to 100 items into one request. That saves per-minute requests, but every item still counts toward the monthly quota. See the PDF API Batch Processing Guide for details.

Python Implementation

import asyncio
import os
import time
from aiohttp import ClientSession

API_URL = "https://pdf.funbrew.cloud/api/pdf/generate-from-html"

class RateLimiter:
    def __init__(self, requests_per_minute: int):
        self.interval = 60.0 / requests_per_minute
        self.last_request_time = 0.0
        self._lock = asyncio.Lock()

    async def acquire(self):
        async with self._lock:
            elapsed = time.monotonic() - self.last_request_time
            wait_time = max(0, self.interval - elapsed)
            if wait_time > 0:
                await asyncio.sleep(wait_time)
            self.last_request_time = time.monotonic()

async def generate_pdf_with_retry(
    session: ClientSession,
    limiter: RateLimiter,
    payload: dict,
    max_attempts: int = 5,
) -> dict:
    for attempt in range(1, max_attempts + 1):
        await limiter.acquire()
        async with session.post(API_URL, json=payload) as resp:
            if resp.status == 429:
                retry_after = resp.headers.get("Retry-After")
                if retry_after is None:
                    # Monthly or storage limit: waiting will not help
                    body = await resp.json()
                    raise RuntimeError(f"Quota exceeded: {body['message']}")
                if attempt == max_attempts:
                    raise RuntimeError("Max retry attempts reached")
                await asyncio.sleep(float(retry_after))
                continue
            resp.raise_for_status()
            body = await resp.json()
            return body["data"]  # includes download_url
    raise RuntimeError("Exhausted retry loop")

async def main():
    headers = {
        "Authorization": f"Bearer {os.environ['FUNBREW_PDF_API_KEY']}",
        "Accept": "application/json",
    }
    limiter = RateLimiter(requests_per_minute=48)
    async with ClientSession(headers=headers) as session:
        data = await generate_pdf_with_retry(
            session, limiter, {"html": "<h1>Hello</h1>", "filename": "hello.pdf"}
        )
        print(data["download_url"])

asyncio.run(main())

Passing json=payload makes aiohttp send the body with Content-Type: application/json.

Monitoring Rate Limit Health

Track your rate limit hit rate over time to decide when to upgrade your plan or redesign batch jobs.

const metrics = { totalRequests: 0, rateLimitHits: 0 };

async function generatePdfWithMetrics(html, filename) {
  metrics.totalRequests++;
  try {
    return await fetchWithExponentialBackoff(
      `${API_BASE}/api/pdf/generate-from-html`,
      { method: 'POST', headers: apiHeaders(), body: JSON.stringify({ html, filename }) }
    );
  } catch (err) {
    if (err.message.includes('429')) metrics.rateLimitHits++;
    throw err;
  }
}

// Log hit rate every hour
setInterval(() => {
  const hitRate = metrics.totalRequests > 0
    ? (metrics.rateLimitHits / metrics.totalRequests * 100).toFixed(1)
    : 0;
  console.log(`Rate limit hit rate: ${hitRate}% (${metrics.rateLimitHits}/${metrics.totalRequests})`);
  if (parseFloat(hitRate) > 5) {
    console.warn('Hit rate above 5% — consider upgrading plan or reducing concurrency');
  }
}, 60 * 60 * 1000);

This example counts requests that were still getting 429 after all retries.

Summary

Key principles for rate limit handling:

  • Always read Retry-After: never retry sooner than the header specifies
  • Do not retry a 429 without Retry-After: monthly and storage limits do not clear by waiting
  • Add jitter to backoff: spreads retries from multiple workers to avoid synchronized hammering
  • Throttle preemptively: a local rate limiter prevents hitting the API limit in the first place
  • Keep the total rate under the limit: the per-minute limit is per company and includes downloads, so keep the sum across all workers below your plan's per-minute limit
  • Monitor X-RateLimit-Remaining: back off automatically before you hit zero

For broader production deployment advice, see the PDF API Production Guide. For error handling across all status codes, see the PDF API Error Handling Guide.

Related

Powered by FUNBREW PDF