Background PDF Jobs with ActiveJob: Sidekiq, Solid Queue, and Storage Adapters

HtmlToPdf 4.0 adds a second way to generate a PDF: in the background, via plain ActiveJob, with job status tracking and S3/ActiveStorage storage — without touching how the synchronous, in-request path already works.

Why render in the background at all

The original design — include HtmlToPdf + around_action :html_to_pdf — renders inline: the request that asks for the PDF holds a connection open while headless Chrome converts the view, then gets the bytes back directly. That's the right model for a one-page invoice a user clicks "download" for. It stops being the right model once the PDF is slow enough that holding a request open for it is wasteful (a 40-page report, many images, a long javascript_delay for async-rendered content), or once the PDF's destination isn't "stream it to this one browser tab" but "attach it to a record" or "drop it in S3 for something else to pick up later." HtmlToPdf.generate_later exists for exactly that second case.

job = HtmlToPdf.generate_later(
  controller: InvoicesController,
  action: :show,
  assigns: { invoice: invoice },
  pdf_options: { title: "invoice", print_options: { format: "A4" } },
  store: { adapter: :active_storage, record: invoice, attachment: :pdf },
  metadata: { invoice_id: invoice.id }
)

HtmlToPdf::JobStatus.find(job.job_id)
# => #<HtmlToPdf::JobStatus state: "completed", result: {...}, metadata: {invoice_id: 1}>

The architecture

Four pieces, each independently usable, with generate_later as the convenient default that wires them together:

HtmlToPdf::GenerateJob is a plain ActiveJob::Base subclass built on exactly these pieces, using only retry_on/discard_on/ queue_as — ActiveJob's own public API. There is no Sidekiq- or Solid-Queue-specific code anywhere in this gem. "Compatible with Sidekiq and Solid Queue" is true by construction, not something verified by running two separate backends in CI — it runs under whichever adapter config.active_job.queue_adapter names.

Setting up Solid Queue

Rails 8's own default queue adapter. One config line:

config.active_job.queue_adapter = :solid_queue

Then run a worker as its own OS process, alongside your web server:

bin/jobs

That last part matters more than it looks: bin/jobs is a separate Ruby process from rails server, with its own memory. See "Job status tracking across processes" below for the one config change that separation actually requires.

Setting up Sidekiq

Not a dependency of this gem — add it to your own Gemfile, the same "bring your own adapter" stance the :s3 storage adapter takes with aws-sdk-s3:

gem "sidekiq"
# config/initializers/sidekiq.rb
Sidekiq.configure_server { |c| c.redis = { url: ENV.fetch("REDIS_URL") } }
Sidekiq.configure_client { |c| c.redis = { url: ENV.fetch("REDIS_URL") } }
# config/environments/production.rb
config.active_job.queue_adapter = :sidekiq
bundle exec sidekiq

Same separate-process caveat as Solid Queue applies — and if you're already running Redis for Sidekiq itself, pointing config.cache_store at that same instance (:redis_cache_store) is the path of least resistance for job status visibility.

Anything else ActiveJob supports — good_job, que, delayed_job — works the same way: set queue_adapter, run that backend's worker process, make sure the cache store is shared. Nothing else in this gem is adapter-specific.

Job status tracking across processes

HtmlToPdf::JobStatus defaults to HtmlToPdf::JobStatus::CacheStore — a thin wrapper over Rails.cache, namespaced under htmlToPdf:job_status:<job_id>. This is the single most common setup mistake with the whole feature, and it's not really an HtmlToPdf-specific gotcha — it's a Rails.cache one that this feature happens to expose immediately: a Rails app's default development cache store, :memory_store, lives in one process's memory. A web process and a Solid Queue/Sidekiq worker process are two different processes. The worker writes "completed" into its own in-memory cache; the web process, asked to look up that same job_id, consults its own separate in-memory cache, finds nothing, and reports a nil state forever — even though the job ran successfully and the log clearly shows it.

The fix is the same one any multi-process Rails deployment already needs for Rails.cache generally: a store that isn't tied to one process's memory. Solid Cache (SQLite/MySQL/Postgres-backed, ships with Rails 8 alongside Solid Queue), Redis, or Memcached all work — anything genuinely shared:

# config/environments/development.rb / production.rb
config.cache_store = :solid_cache_store   # or :redis_cache_store, :mem_cache_store

Swap the store itself, not just its backend, with any object responding to #read(job_id) / #write(job_id, attrs):

config.job_status_store = MyActiveRecordBackedStore.new

Storage adapters in detail

:active_storage

Attaches the rendered PDF to any ActiveRecord model with a has_one_attached/has_many_attached association, through whichever service config/storage.yml already points your app at — local disk in development, S3/GCS/Azure in production, with no code difference between them. This is the right default if your app already uses ActiveStorage for anything else: one blob/attachment model, one place files get served from, variants and previews if you need them later.

HtmlToPdf.generate_later(
  controller: InvoicesController, action: :show, assigns: { invoice: invoice },
  store: { adapter: :active_storage, record: invoice, attachment: :pdf, filename: "invoice.pdf" }
)
# JobStatus#result => { adapter: :active_storage, blob_id:, key:, filename:, byte_size: }

:s3

Direct upload via aws-sdk-s3, for an app that doesn't use ActiveStorage at all and just wants a plain bucket/key/URL back — no blob/attachment table, no ActiveRecord association required on the model whose PDF this is. This gem does not depend on aws-sdk-s3; it's a true optional dependency, lazily required only when this adapter is actually used, so apps that only use :active_storage never need it in their bundle.

HtmlToPdf.generate_later(
  controller: InvoicesController, action: :show, assigns: { invoice: invoice },
  store: { adapter: :s3, key: "invoices/\#{invoice.id}.pdf" }  # bucket: or config.s3_bucket
)
# JobStatus#result => { adapter: :s3, bucket:, key:, url: }

Prefer leaving credentials out of config.s3_client_options entirely and letting the AWS SDK's default credential chain — an EC2/ECS instance or task role — resolve them. A static access key is a credential that outlives any single process, has to be rotated manually, and works identically whether the code that holds it is trustworthy or not; an instance role is scoped to the machine and never written to disk. Only fall back to explicit credentials when an instance role genuinely isn't an option, such as a bucket in a different AWS account.

Picking one

:active_storage:s3
Extra dependencynone (already in Rails)aws-sdk-s3, added yourself
Needs an AR association on the modelyesno
Backing servicewhatever storage.yml saysalways S3, directly
Result shapeblob id/key/filename/byte_sizebucket/key/URL
Best fitapp already uses ActiveStorageno ActiveStorage, or a non-AR-backed workflow

Retries, failures, and why attempts aren't a config option

GenerateJob retries the same transient Chrome errors BrowserPool itself already retries once internally (Ferrum::DeadBrowserError, ProcessTimeoutError, TimeoutError, NoSuchPageError) — up to 3 job-level attempts on top of that, with wait: :polynomially_longer. A bad print_options value raises ArgumentError, which is discarded immediately rather than retried, since retrying a validation failure can't change its outcome.

Those numbers are fixed literals in the gem's source, not a HtmlToPdf.configure option — on purpose, and the reason is a load-order subtlety worth understanding rather than hitting by surprise. retry_on is a class-level macro: it runs once, the moment generate_job.rb is required, which happens during Bundler.require — before your own config/initializers/html_to_pdf.rb has had any chance to run. A config value read at that exact moment would always see this gem's own default, never whatever your initializer later sets it to, which would be a confusing, silent footgun: the setting would appear to have no effect, and nothing would say why. Rather than ship something that looks configurable but isn't reliably, retry/discard semantics are fixed, and anyone who wants different ones defines their own small ActiveJob::Base subclass on the same Renderer/ Storage primitives GenerateJob itself is built from:

class MyPdfJob < ActiveJob::Base
  retry_on Ferrum::DeadBrowserError, wait: 10.seconds, attempts: 10

  def perform(...)
    pdf_bytes = HtmlToPdf::Renderer.render(...)
    HtmlToPdf::Storage.store(pdf_bytes, adapter: :s3, key: ...)
  end
end

config.job_queue_name doesn't have this problem and is safely dynamic: queue_as { HtmlToPdf.configuration.job_queue_name } uses ActiveJob's block form, which Rails evaluates per-enqueue rather than once at class-definition time.

config.on_job_success / config.on_job_failure are plain Procs called with the JobStatus (and the exception, for the failure callback) once a job finishes for good — after retries are exhausted, or a discard. They run in-process, so they're never serialized anywhere, which is also why they can't be passed per-call as job arguments the way store: or metadata: are; a Proc isn't something ActiveJob can serialize into a queue backend.

Concurrency

BrowserPool is one headless Chrome process per Ruby process, not per request (see Architecture). A web app under ordinary load rarely stresses that; a worker pool with several threads all calling generate_later-enqueued jobs at once is exactly the case that can. config.max_concurrent_renders (default nil, unbounded — unchanged from before this feature existed) caps how many conversions run against the shared browser concurrently, via a Concurrent::Semaphore. It applies to the synchronous controller path too, for the same reason: both paths share the identical one browser process.

Troubleshooting

Further reading