May 21, 2026

PDF API in Ruby: Rails, Sidekiq & Production Patterns

RubyRailsPDF APISidekiqproduction

Ruby's ecosystem — Faraday for HTTP, Sidekiq for async jobs, Rails for the web layer — maps cleanly onto PDF API integration. This guide focuses on production-grade Ruby patterns: a reusable service object, retry middleware, async PDF generation via Sidekiq, batch processing, and testing. To receive a webhook when a PDF has been generated, see the Webhook integration guide.

For a quick comparison of Ruby and Go with basic code examples, see the Ruby and Go quickstart guide. For Node.js, Python, and PHP, see the language quickstart guide. If you prefer Go's goroutine-based approach, see the Go PDF API Guide. FUNBREW PDF's official SDKs are for PHP, Node.js and Python; there is no official Ruby SDK, so this guide calls the API directly with Faraday.

Prerequisites

# Set your API key
export FUNBREW_PDF_API_KEY="sk-your-api-key"
# Gemfile
gem 'faraday'
gem 'faraday-retry' # In Faraday 2 the retry middleware is a separate gem
gem 'sidekiq'       # For async generation
gem 'parallel'      # For batch generation

Sign up for free to get your API key. See the API documentation for the full option reference.

How the API works

Getting a PDF takes two requests:

  1. POST https://pdf.funbrew.cloud/api/pdf/generate-from-html (generate-from-url for URLs, generate-from-template for templates) with Authorization: Bearer <API key> returns JSON — not the PDF bytes — shaped like {"success": true, "data": {"download_url": ..., "filename": ...}}
  2. Fetch data.download_url (GET /api/pdf/download/{filename}) with the same API key to get the PDF

Page settings go inside options. The main keys are page-size (A3, A4, A5, Letter, Legal), orientation (Portrait, Landscape), margin-top/margin-right/margin-bottom/margin-left (mm, 0–50) and engine (fast, quality). The quality engine is available on Pro and above; on Free it returns 403. Both the generate and the download request count toward the per-minute request limit.

Service Object Pattern

Encapsulate all PDF API calls in a single service class. This makes it easy to swap implementations, add logging, and test in isolation.

# app/services/pdf_generator.rb
require 'faraday'
require 'faraday/retry'

class PdfGenerator
  BASE_URL = 'https://pdf.funbrew.cloud'.freeze

  # Retry only transient server errors and network errors.
  # 429 is not listed: the monthly-quota and storage 429s do not clear by waiting.
  # faraday-retry does not retry POST by default, so add post to methods.
  RETRY_OPTIONS = {
    max: 3,
    interval: 1.0,
    backoff_factor: 2,
    methods: %i[get post],
    retry_statuses: [500, 502, 503, 504]
  }.freeze

  DEFAULT_OPTIONS = { 'page-size' => 'A4' }.freeze

  class PdfGenerationError < StandardError
    attr_reader :status, :body, :retry_after

    def initialize(response)
      @status      = response.status
      @body        = response.body
      @retry_after = response.headers['Retry-After']&.to_i
      message = @body.is_a?(Hash) ? @body['message'] : @body.to_s[0, 200]
      super("PDF API error #{@status}: #{message}")
    end

    # Only a 429 with Retry-After (per-minute limit) and 5xx can succeed later
    def retryable?
      (@status == 429 && !@retry_after.nil?) || @status >= 500
    end
  end

  def initialize(api_key: ENV.fetch('FUNBREW_PDF_API_KEY'))
    @conn = Faraday.new(url: BASE_URL) do |f|
      f.request :json   # Send hashes as JSON
      f.request :retry, RETRY_OPTIONS
      f.response :json  # Parse JSON responses into a Hash (the PDF is left as is)
      f.options.timeout      = 60
      f.options.open_timeout = 10
      f.headers['Authorization'] = "Bearer #{api_key}"
      f.headers['Accept']        = 'application/json'
    end
  end

  # Generate from raw HTML. Returns PDF binary on success, raises on error.
  # Pass filename, expiration_hours, etc. as params.
  def from_html(html, options: DEFAULT_OPTIONS, **params)
    generate('/api/pdf/generate-from-html', { html: html, options: options, **params })
  end

  # Generate from a template registered in the dashboard (by slug).
  def from_template(slug, variables, options: DEFAULT_OPTIONS)
    generate('/api/pdf/generate-from-template', { template: slug, variables: variables, options: options })
  end

  # Convert a URL to PDF (there is no option to wait for JavaScript rendering).
  def from_url(url, options: DEFAULT_OPTIONS)
    generate('/api/pdf/generate-from-url', { url: url, options: options })
  end

  private

  # 1. Generate (JSON with download_url)  2. Download with the same API key
  def generate(path, payload)
    response = @conn.post(path, payload)
    raise PdfGenerationError.new(response) unless response.success?

    download = @conn.get(response.body.dig('data', 'download_url'))
    raise PdfGenerationError.new(download) unless download.success?

    download.body
  end
end

Note that retrying a POST can create a duplicate PDF if the server had already finished generating it, and the duplicate also counts toward your monthly quota.

Usage anywhere in your Rails app:

generator = PdfGenerator.new

# On-demand HTML generation
pdf = generator.from_html('<h1>Invoice</h1><p>Total: $1,000</p>')
File.binwrite('invoice.pdf', pdf)

# Template-based generation (pass variables as strings)
pdf = generator.from_template('invoice-v1', {
  company_name:   'Acme Corp',
  invoice_number: 'INV-2026-0042',
  total:          '3,000'
})

Templates only replace variables such as {{company_name}} with HTML-escaped values; there are no loops or conditionals. For documents with a variable number of rows, such as invoice line items, build the HTML in a Rails view and pass it to from_html (the examples below do this). A missing template returns 404 and missing required variables return 422.

Rails Controller Integration

Serve PDFs as inline previews or forced downloads from a Rails controller.

# app/controllers/invoices_controller.rb
class InvoicesController < ApplicationController
  before_action :set_invoice, only: [:pdf]

  # GET /invoices/:id.pdf
  def pdf
    html = render_to_string(template: 'invoices/pdf', layout: 'pdf', formats: [:html])
    pdf_bytes = PdfGenerator.new.from_html(html, filename: "invoice-#{@invoice.number}.pdf")

    respond_to do |format|
      format.pdf do
        send_data pdf_bytes,
          filename:    "invoice-#{@invoice.number}.pdf",
          type:        'application/pdf',
          disposition: params[:download] ? 'attachment' : 'inline'
      end
    end
  rescue PdfGenerator::PdfGenerationError, Faraday::Error => e
    Rails.logger.error("PDF generation failed: #{e.message}")
    render json: { error: 'PDF generation failed' }, status: :service_unavailable
  end

  private

  def set_invoice
    @invoice = Invoice.find(params[:id])
    authorize @invoice  # Pundit / CanCanCan authorization
  end
end

Loop over @invoice.line_items in app/views/invoices/pdf.html.erb to build the line-item table. Rails registers the :pdf MIME type by default, so nothing needs to be added to config/initializers/mime_types.rb.

Sidekiq Async PDF Generation

Move large or low-priority PDF generation off the request thread. Sidekiq workers let you generate PDFs without tying up web request time.

# app/models/invoice.rb
class Invoice < ApplicationRecord
  has_one_attached :pdf_file
  after_commit :enqueue_pdf_generation, on: :create

  private

  def enqueue_pdf_generation
    GenerateInvoicePdfJob.perform_async(id)
  end
end
# app/jobs/generate_invoice_pdf_job.rb
class GenerateInvoicePdfJob
  include Sidekiq::Job

  sidekiq_options queue: 'pdf', retry: 3

  # Sidekiq arguments must be simple JSON types (no keyword arguments)
  def perform(invoice_id, notify_user = true)
    invoice = Invoice.find(invoice_id)
    html    = ApplicationController.render(template: 'invoices/pdf', assigns: { invoice: invoice })

    pdf_bytes = PdfGenerator.new.from_html(html, filename: "invoice-#{invoice.number}.pdf")

    # Store in Active Storage (backed by S3 / GCS, etc.)
    invoice.pdf_file.attach(
      io:           StringIO.new(pdf_bytes),
      filename:     "invoice-#{invoice.number}.pdf",
      content_type: 'application/pdf'
    )

    invoice.update!(pdf_generated_at: Time.current)

    # Email the customer
    InvoiceMailer.pdf_ready(invoice).deliver_later if notify_user
  rescue PdfGenerator::PdfGenerationError => e
    Rails.logger.error("[GenerateInvoicePdfJob] Invoice #{invoice_id} failed: #{e.message}")
    raise if e.retryable?  # Let Sidekiq retry only 5xx and the per-minute 429
    # Monthly/storage 429s and other 4xx will not succeed on retry, so stop here
  end
end

Sidekiq Configuration

# config/sidekiq.yml
:queues:
  - [critical, 3]
  - [default, 2]
  - [pdf, 1]        # PDF generation — lower priority than critical paths

:concurrency: 10

How long a single job waits is bounded by the Faraday timeout in PdfGenerator (60 seconds, multiplied by the number of retries). The per-minute request limit is per company — 10 on Free, 120 on Pro — and each PDF takes two requests (generate and download), so keep the concurrency of the pdf queue small enough for your plan.

Batch PDF Generation

For month-end invoice runs or bulk certificate issuance, generate PDFs in parallel using Ruby threads.

# lib/pdf_batch_processor.rb
require 'parallel'

class PdfBatchProcessor
  DEFAULT_CONCURRENCY = 3

  def initialize(concurrency: DEFAULT_CONCURRENCY)
    @concurrency = concurrency
  end

  # Generate PDFs for all items concurrently.
  # Returns an array of { id:, status: :ok/:error, path:, error: } hashes.
  def run(items, &html_builder)
    Parallel.map(items, in_threads: @concurrency) do |item|
      # Use a separate connection per thread
      generator = (Thread.current[:funbrew_pdf_generator] ||= PdfGenerator.new)

      begin
        html      = html_builder.call(item)
        pdf_bytes = generator.from_html(html, options: { 'page-size' => 'A4', 'engine' => 'fast' })
        path      = write_pdf(item[:id], pdf_bytes)
        { id: item[:id], status: :ok, path: path, bytes: pdf_bytes.bytesize }
      rescue PdfGenerator::PdfGenerationError, Faraday::Error => e
        { id: item[:id], status: :error, error: e.message }
      end
    end
  end

  private

  def write_pdf(id, bytes)
    path = Rails.root.join('tmp', 'pdfs', "#{id}.pdf")
    FileUtils.mkdir_p(path.dirname)
    File.binwrite(path, bytes)
    path.to_s
  end
end

Usage for a month-end invoice run:

invoices = Invoice.where(period: Date.today.beginning_of_month..)

processor = PdfBatchProcessor.new(concurrency: 3)
results   = processor.run(invoices.map { |i| { id: i.id, invoice: i } }) do |item|
  ApplicationController.render(
    template: 'invoices/pdf',
    assigns:  { invoice: item[:invoice] }
  )
end

success_count = results.count { |r| r[:status] == :ok }
Rails.logger.info("Batch complete: #{success_count}/#{results.size} generated")

Items that failed with the per-minute 429 (the one with Retry-After) will succeed if you rerun them after waiting. On every plan you can also use the batch API (POST /api/pdf/batch), which accepts up to 100 HTML or URL items per request. For queue-based patterns, see the PDF API Batch Processing Guide.

Error Handling

The service object raises PdfGenerator::PdfGenerationError when the API returns an error, and Faraday::TimeoutError or Faraday::ConnectionFailed (both descendants of Faraday::Error) on timeouts and connection failures. Error responses look like {"success": false, "message": "..."}. To stop calling the API while it keeps failing, add a circuit breaker on top of Faraday's retry middleware:

# lib/pdf_generator_with_circuit_breaker.rb
class PdfGeneratorWithCircuitBreaker
  class CircuitOpenError < StandardError; end

  MAX_FAILURES  = 5
  OPEN_DURATION = 60  # seconds

  def initialize(generator: PdfGenerator.new)
    @generator = generator
    @failures  = 0
    @opened_at = nil
    @mutex     = Mutex.new
  end

  def from_html(html, **opts)
    @mutex.synchronize do
      if @opened_at
        raise CircuitOpenError, 'PDF API circuit breaker is open' if Time.current - @opened_at < OPEN_DURATION

        # Half-open: allow one attempt; a failure reopens the circuit
        @opened_at = nil
        @failures  = MAX_FAILURES - 1
      end
    end

    result = @generator.from_html(html, **opts)
    @mutex.synchronize { @failures = 0 }
    result
  rescue PdfGenerator::PdfGenerationError, Faraday::Error => e
    # 4xx (bad input, limits reached) is not an API outage, so do not count it
    server_side = !e.is_a?(PdfGenerator::PdfGenerationError) || e.status >= 500
    if server_side
      @mutex.synchronize do
        @failures += 1
        if @failures >= MAX_FAILURES
          @opened_at = Time.current
          Rails.logger.warn("PDF circuit breaker opened after #{@failures} failures")
        end
      end
    end
    raise
  end
end

For complete error handling patterns including retry strategies, see the PDF API Error Handling Guide.

Secure API Key Management

Never hard-code your API key. Use Rails credentials or environment variables:

# .env (never commit to Git)
FUNBREW_PDF_API_KEY=sk-xxxxxxxxxxxxxxxx
# config/credentials.yml.enc (edit with bin/rails credentials:edit; encrypted, safe to commit)
# Never commit config/master.key
# Access via: Rails.application.credentials.funbrew_pdf_api_key
funbrew_pdf_api_key: sk-xxxxxxxxxxxxxxxx
# Initializer — choose one source
api_key = ENV['FUNBREW_PDF_API_KEY'] ||
          Rails.application.credentials.funbrew_pdf_api_key
generator = PdfGenerator.new(api_key: api_key)

For production security including IP restrictions and SSRF prevention, see the PDF API Security Guide.

Testing

Use WebMock or VCR to avoid real API calls in tests. Stub both requests: the generate call (JSON) and the download (PDF).

# spec/services/pdf_generator_spec.rb
require 'webmock/rspec'

RSpec.describe PdfGenerator do
  let(:generator)    { described_class.new(api_key: 'test-key') }
  let(:fake_pdf)     { '%PDF-1.4 fake'.b }
  let(:generate_url) { 'https://pdf.funbrew.cloud/api/pdf/generate-from-html' }
  let(:download_url) { 'https://pdf.funbrew.cloud/api/pdf/download/test.pdf' }

  before do
    stub_request(:post, generate_url)
      .with(
        headers: { 'Authorization' => 'Bearer test-key' },
        body: hash_including('html' => '<h1>Test</h1>')
      )
      .to_return(
        status: 200,
        body: { success: true, data: { filename: 'test.pdf', download_url: download_url } }.to_json,
        headers: { 'Content-Type' => 'application/json' }
      )

    stub_request(:get, download_url)
      .with(headers: { 'Authorization' => 'Bearer test-key' })
      .to_return(status: 200, body: fake_pdf, headers: { 'Content-Type' => 'application/pdf' })
  end

  it 'returns PDF bytes on success' do
    result = generator.from_html('<h1>Test</h1>')
    expect(result).to eq(fake_pdf)
  end

  context 'per-minute 429 (with Retry-After)' do
    before do
      stub_request(:post, generate_url)
        .to_return(
          status: 429,
          body: { success: false, message: 'rate limited', retry_after: 30 }.to_json,
          headers: { 'Content-Type' => 'application/json', 'Retry-After' => '30' }
        )
    end

    it 'treats it as retryable' do
      expect { generator.from_html('<h1>Test</h1>') }
        .to raise_error(PdfGenerator::PdfGenerationError) { |err|
          expect(err.status).to eq(429)
          expect(err.retry_after).to eq(30)
          expect(err.retryable?).to be true
        }
    end
  end

  context 'monthly-quota 429 (no Retry-After)' do
    before do
      stub_request(:post, generate_url)
        .to_return(
          status: 429,
          body: { success: false, message: 'Monthly PDF generation limit reached. Limit: 30' }.to_json,
          headers: { 'Content-Type' => 'application/json' }
        )
    end

    it 'treats it as not retryable' do
      expect { generator.from_html('<h1>Test</h1>') }
        .to raise_error(PdfGenerator::PdfGenerationError) { |err|
          expect(err.retryable?).to be false
        }
    end
  end
end

Production Checklist

Before deploying to production, verify:

Item Detail
API key in env vars or credentials Never in source code; if you use credentials, never commit config/master.key
Faraday retry configured retry_statuses: [500, 502, 503, 504], methods: %i[get post] and backoff; decide on 429 by the presence of Retry-After
Sidekiq queue isolated Separate pdf queue so PDF backlog doesn't block critical jobs
Timeout set At least 60 s for complex HTML
Concurrency Fits the per-minute request limit (per company; two requests per PDF for generate and download)
Error logging PdfGenerationError captured in Sentry/Bugsnag with invoice ID
Active Storage or S3 Generated PDFs stored externally, not in Rails tmp
IP allowlisting On the Business plan, configure production server IPs in the FUNBREW PDF dashboard

For the full production checklist covering monitoring, scaling, and cost management, see the PDF API Production Guide.

Summary

Ruby's strengths — Faraday's middleware chain, Sidekiq's reliable async processing, Rails' conventions — make it straightforward to build a robust PDF generation pipeline:

  • Service object: Keeps the generate-then-download flow in one class, injectable and testable
  • Faraday retry: Automatic backoff on 5xx and network errors; decide on 429 by Retry-After
  • Sidekiq worker: Move generation off the request thread and retry only errors that can succeed later
  • Batch with Parallel: One connection per thread and a concurrency that fits the per-minute limit
  • Circuit breaker: Prevent cascade failures during API outages

Related

Powered by FUNBREW PDF