In a multi-tenant Rails CRM, why is Current.account nil inside a job enqueued during the request, and how should the job get the account?
answer
- Current is not part of the job payload
- a worker runs in its own execution
- pass account and user as arguments
- Current.set(...) { } inside perform
- perform_now in a request hides the bug
basics
~20 sEnqueuing serializes only the job's arguments; Current lives in the request's thread and is cleared when the request ends. The worker runs the job in a fresh execution with an empty Current, so pass account and user explicitly and set Current inside perform if needed.
solid answer
~40 s`perform_later` serializes the job class and its arguments, nothing else. `Current` is per-thread state of the request, cleared by the executor when the request completes. A worker thread or process later runs the job inside its own executor-wrapped execution, where `Current` starts from its defaults, so `Current.account` is `nil` and `Contact.create!` fails its required `belongs_to :account`, or worse, an unscoped query runs across tenants. The fix is explicit data: `ContactImportJob.perform_later(account, Current.user, file)`, then inside `perform` wrap the work in `Current.set(account: account, user: user) { ... }` so model defaults and audit callbacks still find them. The bug can hide in development: `perform_now` inside a request runs in the request's execution and still sees `Current`.
code
ruby · 10 linesclass ApplicationJob < ActiveJob::Base
around_perform do |job, block|
account = job.arguments.first
if account.is_a?(Account)
Current.set(account: account) { block.call }
else
block.call
end
end
endgo deeper
Recall that Current is not available in background jobs unless the job sets it, and that jobs should receive what they need as arguments.
Explain why: arguments are the only payload, the executor clears Current after the request, and each job runs in a new execution.
Spot the silent failure, an unscoped cross-tenant query, and establish a pattern such as passing the account and wrapping perform in Current.set.
Set the team rule for tenant context crossing async boundaries, and decide whether a shared around_perform or explicit arguments everywhere fits the codebase.
## The symptom A CRM lets a user upload a spreadsheet of contacts. The controller enqueues a job: ```ruby class ContactImportsController < ApplicationController def create ContactImportJob.perform_later(params.expect(:file_id)) redirect_to contacts_path, notice: "Import started" end end class ContactImportJob < ApplicationJob def perform(file_id) rows = ImportFile.find(file_id).rows rows.each { |row| Current.account.contacts.create!(row) } # NoMethodError on nil end end ``` In the request, `Current.account` was set by a `before_action`. In the job it is `nil`. ## Why the value is gone Three facts combine: 1. **Enqueuing serializes arguments only.** `perform_later` turns the job class, queue, and arguments into a payload. `Current` is not an argument, so it is not in the payload. 2. **`Current` belongs to the request's execution.** Its values live in a per-thread execution context, and the executor clears them when the request completes, often before the job even starts. 3. **The job runs in a new execution.** Active Job wraps each execution in the application's reloader and executor, so on a worker (Solid Queue, or the `:async` adapter's thread pool) the job begins with a fresh `Current`, holding only defaults. So the job sees nothing the request set, by design. ## What failure looks like The failure depends on how the code reads `Current`: | Code in the job | Result when `Current.account` is `nil` | |---|---| | `Current.account.contacts.create!` | `NoMethodError` on `nil` | | `Contact.create!(row)` with `belongs_to :account, default: -> { Current.account }` | validation error: account must exist | | `Contact.where(email: ...)` meant to be scoped by tenant | runs across **all** accounts | The last row is the dangerous one: no error, wrong data. ## The fix: pass it, then optionally re-establish it The job's inputs should be explicit arguments. Active Record objects can be passed directly, since Active Job serializes them as global IDs and loads them again when the job runs: ```ruby class ContactImportJob < ApplicationJob def perform(account, user, file_id) Current.set(account: account, user: user) do ImportFile.find(file_id).rows.each { |row| Contact.create!(row) } end end end ContactImportJob.perform_later(Current.account, Current.user, file_id) ``` `Current.set` restores the previous values when the block ends, and the executor clears everything when the job's execution completes. Inside the block, model defaults and audit callbacks that read `Current` behave as they would in the request. Teams with many tenant-aware jobs often move the pattern into `ApplicationJob`, for example an `around_perform` that reads the account from the first argument and wraps the job in `Current.set`. The principle stays the same: the job's arguments are the source of truth, and `Current` is rebuilt from them. ## Why it can pass in development Whether the bug shows depends on where the job runs: - **`perform_now` inside a controller action** runs in the request's thread while the request's executor is active, so no new execution starts and `Current` still holds the request's values. - **`perform_later` with a real backend** runs later, elsewhere, with an empty `Current`. A developer who tests with `perform_now`, or with an inline setup, sees the import work and ships code that fails in production. Tests that run jobs through Active Job's test helpers, such as `perform_enqueued_jobs`, start each job in a fresh execution and do surface the missing account. ## A checklist for tenant-aware jobs 1. Every job that touches tenant data takes the account (and, if it audits, the user) as arguments. 2. `perform` re-establishes them with `Current.set`, or a shared `around_perform` does. 3. Queries inside the job go through the account, such as `account.contacts`, rather than relying on `Current` alone. 4. Tests run the job through Active Job's test helpers, not `perform_now` inside a block that already set `Current`. ## The same trap elsewhere Anything that runs after or outside the request has the same problem: `after_commit` callbacks that enqueue jobs, mailers delivered with `deliver_later`, Action Cable broadcasts rendered in a job, and recurring tasks. Pass the tenant along explicitly every time it crosses into a job.
- Why not serialize the whole `Current.attributes` hash into every job automatically?It hides each job's real inputs, copies values that may be stale by the time the job runs, and makes jobs depend on whatever the request happened to set. Explicit arguments document what the job needs, survive retries unchanged, and let the job be enqueued from places with no request at all, such as a recurring task or the console.
- A `deliver_later` mailer renders `Current.user.name` in its template. What happens?`deliver_later` enqueues a mail delivery job, which runs in its own execution with an empty `Current`, so `Current.user` is `nil` and the template raises. Pass the user to the mailer as a parameter, for example `NoticeMailer.with(user: Current.user).import_done.deliver_later`, and read it from `params` in the mailer.
- Active Job serializes Current along with the job's arguments.
- An enqueued job runs later in the request's own thread, so Current is still set.
- If the job works with perform_now in development, it will work with perform_later in production.
- A nil Current.account in a job always raises, so tenant leaks are impossible.
- Calling Current.set inside perform leaks the values into the next job on the worker.