
Background Jobs When Every Query Needs a Tenant
Background jobs start with no tenant set. Learn how to carry the account with each job, avoid GlobalID errors, and handle cross-account jobs safely.
Part 5 of a series on multi-tenant Rails with Postgres Row Level Security.
Part 3 set the tenant context once per request, in ApplicationController. Background jobs, however, never go through a controller, so they start with no account set. With RLS failing closed, a job that touches invoices either errors or finds nothing.
How you approach this problem depends on the job type. You can group the jobs into two different categories:
- Jobs per account, like sending an invoice or generating a report, should run with that account’s context, exactly like a request.
- Jobs that run across many accounts, like nightly billing or overdue reminders, need to touch every account’s data, which RLS is designed to prevent.
Category 1: jobs per account
The job needs to know which account it belongs to and set that context before it does any work. The issue is that when you pass an RLS-protected record to a tenant-scoped job, ActiveJob tries to deserialize the record arguments before the job runs and before the account context is set. Even worse, the arguments are also deserialized before any callbacks are called, so if you pass an RLS-protected record and set the account in around_perform, the record loads with no account set, RLS hides it, and the job fails with ActiveJob::DeserializationError.
There are two workarounds for the deserialization issue:
Option 1: pass the account ID and record IDs directly
When you queue the job, you can pass plain IDs, so ActiveJob has nothing to load, and set the context inside perform before loading anything.
class SendInvoiceJob < ApplicationJob
def perform(account_id:, invoice_id:)
TenantContext.with(account_id: account_id) do
invoice = Invoice.find(invoice_id)
InvoiceMailer.with(invoice: invoice).issued.deliver_now
end
end
end
SendInvoiceJob.perform_later(account_id: invoice.account_id, invoice_id: invoice.id)
This is the easiest, most straightforward solution, with nothing happening behind the scenes; it’s easy to read and test. The cost is repetition: every job takes an account_id and wraps its own work, and a job that forgets the wrapper fails closed every time it runs.
You can take the same approach with mailers. Pass the account ID along with the record IDs, and have the mailer set the context itself, for example with an around_action in ApplicationMailer that wraps each action in TenantContext.with(account_id: params[:account_id]). Then deliver_later works without overriding the default mail delivery job.
Option 2: set the account context during deserialization
If you’re like me and you’d rather keep passing RLS-protected records, you can set the account context before ActiveJob deserializes them with a custom concern. The concern must record the current account when the job is enqueued, store it with the job’s data, and set the account context with the same TenantContext.with helper from Part 3 whenever the job runs, including while its arguments are deserialized and loaded.
# app/jobs/concerns/tenant_job.rb
module TenantJob
extend ActiveSupport::Concern
included do
attr_writer :account
end
def account
@account ||= Current.account
end
def set(options = {})
self.account = options[:account] if options[:account]
super
end
def serialize
super.merge("account_id" => account&.id)
end
def deserialize(job_data)
super
self.account = Account.find_by(id: job_data["account_id"]) if job_data["account_id"]
end
def perform_now
with_tenant_context { super }
end
private
# Record arguments are loaded here, so the account has to be set first
def deserialize_arguments(serialized_args)
with_tenant_context { super }
end
def with_tenant_context(&block)
TenantContext.with(account_id: account&.id, &block)
end
end
Include it in ApplicationJob, and every job enqueued during a request automatically runs as that request’s account.
class ApplicationJob < ActiveJob::Base
include TenantJob
end
# In a controller, with Current.account set
SendInvoiceJob.perform_later(invoice)
If a job is enqueued with no account, the account is nil, the setting is empty, and the job’s queries fail closed. The concern sets the account context in perform_now and around deserialize_arguments, so records load with the account already in place, and jobs can take records as arguments like any other Rails job.
While overriding private methods isn’t ideal, ActiveJob’s private deserialize_arguments is the most direct place, as of this post, to set the account context during deserialization. It’s a short, stable method, but add a test that enqueues a job with a record argument and runs it through a real queue adapter to catch any issues when updating Rails.
Also, if your mailers depend on RLS-protected models, and you would rather pass the records directly, you’ll need to override the default action mailer delivery job. Create a new job that inherits from ActionMailer::MailDeliveryJob and includes the TenantJob concern, and point config.action_mailer.delivery_job to your mail delivery job class.
Category 2: jobs that run across many accounts
Cross-account jobs are where RLS can make tasks trickier and harder to accomplish. There are four common workarounds to this problem:
Option 1: a role that bypasses RLS
Connect the job through a separate database role with BYPASSRLS, using a second connection in database.yml. It’s simple, and the job can query everything in one pass.
The problem is that this simple solution opens a security hole, the very hole RLS is supposed to close; the job can read and change every account’s data, every bug in that job affects every account, and the role’s credential becomes the most powerful one your app has. I don’t recommend this route as it defeats the purpose of having RLS in the first place. However, if you do use it, limit it to a few small jobs and keep the credential off your web servers.
Option 2: a bypass flag in the policy
Add a second condition to every policy, like current_setting('app.bypass', true) = 'on', and have cross-account jobs set the flag. Like Option 1, I also do not recommend this option. The app_user can set any session variable it likes, so the flag turns RLS into a setting that any code path, or, if you’re not careful, any SQL injection, can switch off. It undoes the guarantee RLS is there to provide.
Option 3: loop over accounts
For most jobs, I use this option and loop over accounts before fanning the smaller tasks out. For instance, you can have a scheduler job that lists the accounts, then fans out so the work is done one account at a time, each with its own account context. The accounts table isn’t behind the tenant policy, so listing accounts works without any special access.
class NightlyRemindersJob < ApplicationJob
def perform
Account.active.find_each do |account|
AccountRemindersJob.set(account: account).perform_later
end
end
end
class AccountRemindersJob < ApplicationJob
def perform
Invoice.overdue.find_each do |invoice|
InvoiceMailer.with(invoice: invoice).overdue.deliver_now
end
end
end
set(account:) tells each job which account it’s for, and TenantJob stores it with the job. Every account’s work then runs with RLS fully in place. If one account’s job fails, it retries on its own without affecting the others, and the jobs can run in parallel across workers.
Option 4: a SECURITY DEFINER function for cross-account reads
Some work genuinely needs to read across accounts, like a nightly total for an admin report, or finding which accounts have overdue invoices before fanning out. For that, a SECURITY DEFINER function can answer one narrow question across every account, without giving the job a role that can read everything. Writing these functions safely takes care, and Part 6 covers it in detail. Combined with the loop above, the function finds which accounts need work, and each account’s job still runs under RLS.
Long jobs and big batches
If you’re setting the account context in the database transaction and not the database connection session, keep in mind how you implement long jobs and big batches. You don’t want to hold on to a long transaction that holds locks for the entire transaction, and you don’t want one failure to roll back all the work the job did.
Depending on the situation, you may want to:
- Split the job into smaller batches
- Make sure the transactions are short-lived and only perform one task at a time
- Use Active Job continuations (
include ActiveJob::Continuable, Rails 8.1 and newer, and Solid Queue 1.2.0 or newer if you use it) to keep track of what has been done. Pair them with Option 1 from Category 1 and set the context inside each step, since Option 2 from Category 1 wraps the whole job, every step included, in one transaction
Troubleshooting
ActiveJob::DeserializationError. A record argument was loaded before the account was set. Check that the job includesTenantJoband that the account ID survived serialization as a string key.- The job can’t find a record created in the same request. The job ran before the request’s transaction committed. Since Part 3 wraps the whole request in a transaction, enqueue jobs after it commits. Rails 7.2 and newer can do this for you with
enqueue_after_transaction_commit. - Recurring jobs see nothing. Jobs started by a scheduler, like Solid Queue’s recurring tasks, have no current account. Have them fan out per account, as in the reminders example.
- Jobs pass in tests but fail in production. Jobs performed inline in a test can run inside the test’s transaction, where the account is already set. Test them the way they really run, with the account coming from the job itself.
What’s coming in this series
- Why RLS for tenant isolation in Rails
- Your RLS policies might not be doing anything: superusers, table owners, and the roles you actually need
- Setting tenant context per request with
SET LOCAL - Designing a schema around RLS
- Background jobs when every query needs a tenant (this post)
- Cross-tenant reads without punching holes:
SECURITY DEFINERdone safely - Proving isolation: testing RLS in Rails
If your background jobs need to work across tenants, or you’re not sure how they’ll behave once RLS is in place, I’d be glad to help. I can review how your jobs handle tenant context or help you restructure them. Get in touch.



