I moved our background jobs from Redis to Solid Queue, partly so there would be one less service to secure. That worked. The queue is now exactly as secure as our database, which is the system every SQL injection tutorial is about.
Here's the line I write in every app:
def export authorize @account, :export? ExportInvoicesJob.perform_later(@account.id, current_user.id) end The policy passes and the job is enqueued. What follows is everything wrong with that line, in the order I found out.
1. Your queue is a table, and anyone who can write to it runs code
Solid Queue stores each job as a row in solid_queue_jobs. The arguments column holds the full ActiveJob payload as JSON:
{ "job_class": "ExportInvoicesJob", "job_id": "2f9c1e1a-6a39-4c51-9a55-1f0e3b9b7c11", "queue_name": "default", "arguments": [42, 7], "executions": 0, "exception_executions": {}, "locale": "en", "timezone": "UTC", "enqueued_at": "2026-12-01T17:00:00.000000000Z" } A matching row in solid_queue_ready_executions makes it eligible. A worker claims it with FOR UPDATE SKIP LOCKED, constantizes job_class, deserializes arguments and calls perform. Nothing in that path asks who inserted the row.
So write access to the queue tables means you can run any job class with any arguments: two INSERT statements. Ways that write access appears:
- SQL injection anywhere in the app, if the app's DB user can reach the queue tables. In a single-database setup it always can.
- A leaked
DATABASE_URLin a CI log, a.envin a backup, a read-write replica credential someone shared "just for debugging". - An admin tool, BI connector or data pipeline holding a read-write role "because read-only didn't work".
It gets better with records. If you pass Active Record objects instead of IDs, ActiveJob serializes them as GlobalIDs:
"arguments": [ { "_aj_globalid": "gid://myapp/Account/42" }, { "_aj_globalid": "gid://myapp/User/1" } ] These are plain, unsigned GlobalIDs. Changing 42 to 43 is the entire attack. ActiveJob will load any record of any model you name.
Separate the database, separate the credentials
The Rails 8 default puts Solid Queue in its own database (connects_to: { database: { writing: :queue } }). Use that, and give it its own credentials. Then a SQL injection through the primary connection can't touch the queue tables at all. Section 5 covers the price you pay for this.
Sign your jobs
ActiveJob lets you extend what gets serialized, so you can put an HMAC into the payload and refuse anything that doesn't verify:
class ApplicationJob < ActiveJob::Base SIGNED_FIELDS = %w[job_class job_id arguments actor_id tenant_id].freeze SIGNING_KEY = Rails.application.key_generator.generate_key("active-job-signing") attr_reader :actor_id, :tenant_id def initialize(...) super @signature_ok = true # perform_now never deserializes; trust in-process calls end def serialize data = super.merge( "actor_id" => @actor_id || Current.user&.id, "tenant_id" => @tenant_id || Current.account&.id ) data.merge("sig" => self.class.sign(data)) end def deserialize(job_data) super @actor_id = job_data["actor_id"] @tenant_id = job_data["tenant_id"] @signature_ok = job_data["sig"].is_a?(String) && ActiveSupport::SecurityUtils.secure_compare(job_data["sig"], self.class.sign(job_data)) end def signature_ok? = @signature_ok around_perform do |job, block| unless job.signature_ok? Rails.logger.error("Rejected forged job #{job.class.name} job_id=#{job.job_id}") next # skip perform; the job finishes without doing anything end Current.set( user: job.actor_id && User.find_by(id: job.actor_id), account: job.tenant_id && Account.find_by(id: job.tenant_id) ) { block.call } end def self.sign(data) OpenSSL::HMAC.hexdigest("SHA256", SIGNING_KEY, data.slice(*SIGNED_FIELDS).to_json) end end Some notes from the time I spent being wrong about this:
- Don't raise on a bad signature. A raised job lands in failed executions, where someone will eventually click "Retry".
- Test the round trip. You're signing the Ruby hash at enqueue and verifying the parsed JSON at perform. Custom serializers, floats and time formats can make an honest job fail verification. Write a spec that enqueues, reloads the row and performs it.
- Know its limits. Signing stops forged arguments. It doesn't stop replay: anyone who can read the table can copy a valid row with a new
idand the same signed payload. The signature includesjob_id, so a unique index or a "seen job_ids" check on the side-effect table (section 4) helps. A key-rotation plan is extra credit.
2. The job doesn't know who asked
Without that ApplicationJob, here's what perform knows about authorization:
class ExportInvoicesJob < ApplicationJob def perform(account_id, user_id) account = Account.find(account_id) user = User.find(user_id) csv = InvoiceExporter.new(account).to_csv InvoiceMailer.export(user, csv).deliver_now end end Nothing. It takes two integers and obeys them.
Multi-tenancy makes this worse. Current.account, ActsAsTenant.current_tenant and default scopes live in the request. ActiveJob doesn't carry them over, and the Rails executor resets Current around every job. Inside perform, the tenant is nil. Depending on your configuration, nil means "no filter", so Invoice.where(status: "unpaid") returns every customer's unpaid invoices.
Recurring tasks are where this hurts most. A job defined in config/recurring.yml has no request, no user and no tenant behind it. It runs as "the system", and the system has access to everything:
production: nightly_overdue_reminders: class: OverdueRemindersJob schedule: every day at 3am If OverdueRemindersJob queries through tenant-scoped models without setting a tenant, it either crashes (good) or reminds everyone about everyone (bad).
Fail closed: with acts_as_tenant, set require_tenant = true so an unscoped query raises. Recurring jobs should iterate tenants explicitly and enter each one with ActsAsTenant.with_tenant(account) { ... }. A crash gives you a bug report. A silent unscoped query gives you a breach notification.
3. The authorization check happened in the past
The controller checked permission at enqueue time. The job runs later. How much later depends on settings you probably copied from a blog post.
Solid Queue doesn't retry anything itself. Retries come from ActiveJob's retry_on, whose defaults are short: 5 attempts, 3 seconds apart. Then someone writes this:
retry_on StandardError, wait: :polynomially_longer, attempts: 25 :polynomially_longer waits about executions**4 + 2 seconds plus jitter. Across 25 attempts that's roughly 20 days.
Then comes the part with no limit at all. When retries run out, or for any exception without a retry_on, the job goes to solid_queue_failed_executions. It stays there until a human retries or discards it. No expiry, no cap. Mission Control has a button for retrying one job and another for retrying all of them.
| Day | Event |
|---|---|
| 0 | User requests export. Policy passes. Job enqueued. |
| 0 | SMTP returns 4xx. retry_on schedules a retry. |
| 1 | User leaves the company. You remove their membership. |
| 9 | A retry succeeds. Former employee receives all invoices. |
The longer version:
| Day | Event |
|---|---|
| 20 | Retries exhausted. Job moves to failed executions. |
| 140 | Someone tidies up Mission Control with "Retry all". |
Statistically, that someone is me, on a Friday, feeling productive.
perform_later(wait: 1.week) has the same flaw on purpose: you are scheduling a decision made today to run next week.
Rule: every perform re-authorizes at run time, as if it were a controller action receiving untrusted input. It is one.
4. Everything runs at least twice, eventually
Solid Queue gives you at-least-once execution. I knew that and wrote exactly-once code anyway.
Ways a job runs twice without anyone asking:
- An exception after the side effect. The email goes out, then
update!fails a validation, andretry_onsends the email again on every attempt. - Deploys. On
TERM, workers waitshutdown_timeout(5 seconds by default), then release unfinished claimed jobs back to the queue. Your 30-second export already sent its email at second 20, and it runs again from the top. - Dead workers. Processes heartbeat into
solid_queue_processes. Once one misses its window (process_alive_threshold, 5 minutes by default), its claimed jobs are cleaned up. Depending on your version, they're released for another run or marked failed, where "Retry all" is waiting for them. Either way, the job may already have done half its work. - Nested enqueues.
deliver_laterorperform_laterinside a job that later raises will enqueue the child again on every retry.
limits_concurrency won't save you:
limits_concurrency to: 1, key: ->(account_id, *) { account_id }, duration: 15.minutes This is a semaphore with a lease. If the job runs longer than duration, the semaphore expires and the next job for that key is released while the first is still running. It also only stops concurrent runs. A job that runs, fails after its side effect and retries is never concurrent with itself, so the limit doesn't apply.
What helps: record the side effect, key it on something stable across retries, and check it first. job_id stays the same across retry_on attempts and Mission Control retries:
export = account.exports.create_or_find_by!(job_id: job_id) do |e| e.requested_by = user end return if export.delivered_at? Back it with a unique index on exports.job_id, so two simultaneous runs collide in Postgres instead of both succeeding. For payment providers and other APIs that accept idempotency keys, pass job_id. For email, a gap remains between "sent" and "recorded". Make it narrow and put the send last.
5. Transactions, and the database you just split off
There's a trade-off here that Solid Queue makes very concrete.
Queue in the same database as your data: enqueueing inside a transaction is transactional. If the transaction rolls back, the job row rolls back with it, and workers can't see uncommitted rows. This property is excellent, and Redis never had it.
Queue in a separate database (the Rails 8 default, and the one I recommended in section 1): the job insert commits on its own connection, immediately.
ActiveRecord::Base.transaction do membership.update!(role: "admin") ProvisionAdminJob.perform_later(membership.user_id, "admin") AuditLog.create!(action: "promote", actor: current_user) # raises end The primary transaction rolls back, so the membership is still "member" and there's no audit log. The job is already committed in the queue database. A worker picks it up and provisions admin access for a promotion that never happened, with no audit trail of it either.
The reverse also happens: the job runs before the primary commits, find sees the old row or nothing at all, and you get RecordNotFound or work done on stale data.
So separate credentials give you SQL-injection isolation and cost you transactional enqueue. Pick one consciously, then cover the gap:
- Enqueue after commit. ActiveJob has
enqueue_after_transaction_commit, but its default and API have changed between Rails versions, so check yours. Otherwise useafter_commitcallbacks or an outbox table. - Pass references, not intent.
ProvisionAdminJob.perform_later(membership.id)lets the job read the role from the database. A"admin"argument is a decision frozen into a row that outlives the transaction that was supposed to justify it.
6. The small things that leak
- Arguments are plain JSON in your database. With
preserve_finished_jobs(on by default), finished jobs stay forclear_finished_jobs_after(1 day by default). Failed ones stay forever. All of it ends up in your database backups, so a reset token passed as an argument now lives in every nightly dump for as long as you keep them. Pass IDs only. Error trackers usually attach job arguments to exceptions too. - Mission Control is an admin panel that can inspect, discard and re-run anything, including those 140-day-old failed jobs. Put it behind your real admin auth instead of a shared basic-auth password:
# config/application.rb config.mission_control.jobs.base_controller_class = "Admin::BaseController" config.mission_control.jobs.http_basic_auth_enabled = false # config/routes.rb mount MissionControl::Jobs::Engine, at: "/jobs" Admin::BaseController should require an authenticated admin. Check that /jobs returns 403 or a redirect in an incognito window, rather than trusting this paragraph.
- User-triggered enqueues are database writes. A script clicking "Export" 50,000 times is 100,000 inserts and a queue backlog. If the queue shares a database with your app, it's load on your primary too. Use
rate_limitin the controller (Rails 7.2+), and give critical mail its own queue with dedicated workers inconfig/queue.ymlso password resets don't wait behind exports. - Never
constantizeuser input into a job class. I have seenparams[:job].constantize.perform_later. I won't say whose code it was.
The job, written as if it were public
class ExportInvoicesJob < ApplicationJob queue_as :exports retry_on Net::SMTPServerBusy, wait: :polynomially_longer, attempts: 8 def perform(account_id, user_id) account = Account.find_by(id: account_id) user = User.find_by(id: user_id) return unless account && user # records can vanish return unless AccountPolicy.new(user, account).export? # authorize now, not then ActsAsTenant.with_tenant(account) do # explicit tenant scope export = account.exports.create_or_find_by!(job_id: job_id) do |e| e.requested_by = user end return if export.delivered_at? # retries skip done work csv = InvoiceExporter.new(account).to_csv InvoiceMailer.export(user, csv).deliver_now export.update!(delivered_at: Time.current) end end end Around it: the signing ApplicationJob, a queue database with its own credentials, enqueue after commit, and Mission Control behind admin auth.
I moved the queue into the database to have one less thing to worry about. Now I worry about the same things, plus backups.
