Skip to content

Lesson 7 of 9 · 26m

Background Jobs, Idempotency, and Queue Discipline

Design jobs around idempotent side effects, retries, queues, deadlines, and backpressure using Solid Queue or Sidekiq operational patterns.

A background job is not a slower controller action. It is a distributed systems problem with a nice Ruby class around it. Jobs are retried, duplicated, delayed, interrupted, and sometimes executed after the business meaning has changed. If you design them as fire-and-forget convenience, production will eventually teach you otherwise.

Job inputs should be small and stable

Pass IDs, not serialized objects:

class GenerateInvoicePdfJob < ApplicationJob
  queue_as :documents
  def perform(invoice_id)
    invoice = Invoice.find(invoice_id)
    Billing::InvoicePdf.new(invoice:).generate!
  end
end

Serialized models can deserialize into stale state, missing classes, or gigantic payloads. IDs force the job to load current truth at execution time.

Idempotency is the core design constraint

Assume perform runs twice. Payment capture, email sending, webhook delivery, file generation, and third-party writes all need idempotency keys, unique database states, or external API deduplication.

InvoiceDelivery.where(invoice:, recipient:).first_or_create! { |delivery| delivery.status = "sending" }

A unique index makes the guard real. Checking alone in Ruby leaves a race window.

Separate queues by urgency and blast radius

Do not put password resets behind video transcoding:

critical   auth emails, password resets, payment webhooks
default    normal user-facing asynchronous work
bulk/low   imports, exports, backfills, analytics, cleanup

Worker concurrency should reflect queue cost. One expensive bulk worker can consume every CPU while critical jobs wait.

Timeouts, retries, and dead jobs are policy

Retries with exponential backoff are appropriate for transient failure. They are harmful for deterministic validation failures. Discarding a malformed job can be correct, but only if it is logged and observable. A dead-letter queue without inspection is a landfill.

retry_on Net::OpenTimeout, wait: :polynomially_longer, attempts: 5
discard_on ActiveJob::DeserializationError

For business-critical workflows, alert on age, not just count. Ten jobs can be harmless; ten jobs stuck for four hours can mean checkout is broken.

Web requests should enqueue intent, not perform the work

A controller should create or transition durable state and enqueue the continuation. This gives you a recovery point. If the worker dies, the state still exists. If the client disconnects, the operation still proceeds. That is the difference between asynchronous architecture and merely moving slow code elsewhere.

Field notes

  • perform_later inside an uncommitted transaction can enqueue a job before the record is visible; use after_commit or orchestrate after persistence.
  • Unique jobs help some systems, but uniqueness is not a substitute for idempotent side effects; queue latency is often the first capacity signal users feel.
  • Job arguments are operational data; never put secrets, tokens, or large personal-data payloads in them.

Was this lesson helpful?

Sign in to rate