Active Job and Action Cable
Two features that look unrelated and share a failure mode: both move work outside the request cycle, and both fail in ways the request never sees. A job that silently retried five times looks like a success. A broadcast nobody received looks like a working page until someone refreshes.
The 60-second answer
Section titled “The 60-second answer”“Active Job is an abstraction over queue backends. You write a job class with a perform method and call ChargeOrderJob.perform_later(order); the adapter — Sidekiq, GoodJob, Solid Queue — serialises the arguments, stores them, and a separate process executes them. Arguments must be simple types, so pass records (GlobalID) not relations. Jobs must be idempotent, because every backend retries and delivery is at-least-once. Action Cable is the WebSocket layer: a channel handles subscribed, received and unsubscribed, clients connect through a consumer, and broadcast_to pushes a payload to everyone on that stream. With more than one server process, broadcasts must go through a shared adapter such as Redis or Postgres, because a broadcast originates in one process and subscribers may be connected to another.”
Active Job
Section titled “Active Job”class ChargeOrderJob < ApplicationJob queue_as :payments
retry_on PaymentGateway::Timeout, wait: :polynomially_longer, attempts: 5 discard_on ActiveJob::DeserializationError
def perform(order) PaymentGateway.new.charge!(order) endendperform_later serialises a record as a GlobalID (gid://app/Order/42) and re-loads it in the worker. If the record was deleted in between, ActiveJob::DeserializationError is raised — decide deliberately whether to discard_on or retry.
Only primitives, arrays and hashes of them, dates/times and GlobalIDs can be serialised. A relation, a Proc or an arbitrary object raises ActiveJob::SerializationError at enqueue time.
| Adapter | Backing store | Notes |
|---|---|---|
:async |
In-process thread pool | Development and tests; jobs lost on restart |
:sidekiq |
Redis | Mature, high throughput, needs Redis |
:good_job |
PostgreSQL | Reuses the database, has a web UI |
:solid_queue |
PostgreSQL/MySQL/SQLite | Rails 8 default; database-backed |
Rails 8’s default is Solid Queue, processed by a forked worker (bin/jobs). “You need Redis for background jobs” is no longer true by default.
Retries and idempotency
Section titled “Retries and idempotency”Every real backend guarantees at-least-once: a worker can crash after doing the work but before acknowledging, and the job runs again.
def perform(order_id) order = Order.find_by(id: order_id) return if order.nil? || order.charged?
PaymentGateway.new.charge!(order, idempotency_key: "order-#{order_id}")endTwo independent protections: a state guard, and an idempotency key the provider uses to deduplicate. Both are needed — the state check is a race, the provider key is what makes the charge safe. retry_on re-enqueues on the listed exception, discard_on drops it, and anything uncaught falls through to the adapter’s own retry policy. Two retry systems interacting is a common source of duplicate work.
Order.transaction do order.save! ChargeOrderJob.perform_later(order)endBy default a job can be picked up before the transaction commits. Rails 7.2 added config.active_job.enqueue_after_transaction_commit, and Rails 8 defers enqueueing until after commit by default. On older versions, enqueue from after_commit.
Action Cable
Section titled “Action Cable”class RoomChannel < ApplicationCable::Channel def subscribed stream_for current_user.rooms.find(params[:room_id]) end
def speak(data) Message.create!(room_id: params[:room_id], user: current_user, body: data["body"]) endendThe payload is JSON; the client decides what to do with it. With Turbo you rarely write a channel by hand — turbo_stream_from and broadcast_*_to generate both the channel and the HTML payload (see Hotwire and Turbo).
Scaling
Section titled “Scaling”The Cable server keeps the subscription registry in that process. With two Puma processes, a broadcast in process A reaches nobody connected to process B. The fix is a shared adapter:
production: adapter: redis url: <%= ENV.fetch("REDIS_URL") %> channel_prefix: myapp_productionRedis is the classic choice; PostgreSQL (solid_cable) is the Rails 8 default. Beyond that: sticky sessions cap you at one process, connection count is the real limit (each WebSocket holds a file descriptor, so thousands per node rather than hundreds of thousands), and authorisation must happen in subscribed because the channel name and params come from the browser.
Follow-up questions
Section titled “Follow-up questions”- Why must job arguments be primitives or GlobalIDs?
- What does at-least-once delivery imply for every job you write?
- What happens if you enqueue a job inside a transaction that then rolls back?
- How does a broadcast reach a user connected to a different Puma worker?
- What is the difference between
retry_onand the adapter’s own retries?
Common traps
Section titled “Common traps”- Passing a relation to
perform_later. Raises at enqueue time; pass ids and query in the job. - Non-idempotent jobs with automatic retries. Double charges, double emails.
deliver_nowin a request. Blocks on an external SMTP server.- The
:asyncadapter in production. Jobs vanish on deploy. - Broadcasting from a callback without
after_commit. Subscribers see updates that were rolled back. - Assuming
stream_foris private. Anyone passingsubscribedgets the messages.