skip to content

When a Rails controller calls perform_later inside I18n.with_locale(:fr), which locale does the Active Job run in, and why?

level: seniorimportance: should knowfreq 32%

answer

  1. captured at enqueue, not at perform
  2. the payload's "locale" field
  3. perform_now wraps I18n.with_locale
  4. set job.locale before enqueue
  5. scheduled enqueues use the default

basics

~10 s

French. Active Job writes I18n.locale into the job's serialized 'locale' field at enqueue time, and perform_now runs perform inside I18n.with_locale(locale), so the worker translates in fr whatever its own thread's locale is.

solid answer

~40 s

Active Job's `serialize` stores `"locale" => locale || I18n.locale.to_s` in the job payload, so the locale in effect when `perform_later` enqueues travels with the job. On the worker, `deserialize` restores it and `perform_now` runs `perform` inside `I18n.with_locale(locale)` (and `Time.use_zone(timezone)`), so `t` and `l` in the job use French even on a Solid Queue worker sitting in the default locale. Consequences: a job enqueued from a recurring schedule, a rake task or the console captures that process's locale, usually `default_locale`; to enqueue for another locale, wrap the call in `I18n.with_locale(guide.locale)` or set `locale` on a job instance before calling `enqueue`, because the block given to `perform_later` runs only after enqueueing. If the stored locale is removed from `available_locales` before the job runs, `with_locale` raises `I18n::InvalidLocale`.

code

ruby · 7 lines
ruby
class BookingsController < ApplicationController
  def create
    @booking = Booking.create!(booking_params)
    TourReminderJob.perform_later(@booking)  # payload "locale" => "fr" on a French request
    redirect_to @booking, notice: t(".created")
  end
end

go deeper

for a junior

Recall that a job enqueued during a French request runs in French because the locale is saved with the job.

for a middle

Explain the serialized locale field, the with_locale wrapper around perform, and what scheduled or console enqueues capture.

for a senior

Show how you enqueue for a recipient's locale, switch per recipient in batch jobs, and handle queued jobs when locales change.

for a principal

Weigh capturing the request's locale against reading recipients' preferences at send time for notifications across many markets.

## The short answer The job runs in **French**. Active Job treats the current locale as part of the job's execution context, the same way it treats the time zone: it captures it when the job is enqueued and re-applies it when the job runs. ## How the locale travels Three pieces of `ActiveJob::Base` cooperate: 1. **`locale` attribute.** Every job has an `attr_accessor :locale`, `nil` by default. 2. **`serialize`** writes the payload, including `"locale" => locale || I18n.locale.to_s`. An explicitly set `locale` wins; otherwise the locale current at enqueue time is recorded. 3. **`perform_now`** (through an internal module included last, so it wraps everything) runs `I18n.with_locale(locale) { Time.use_zone(timezone) { ... } }` around the job's callbacks and `perform`. ```ruby class TourReminderJob < ApplicationJob def perform(booking) BookingMailer.with(booking: booking).reminder.deliver_now Rails.logger.info I18n.t("tours.reminder_sent") # French if enqueued in :fr end end ``` On the worker, `deserialize` restores the stored string (or the worker's current locale if the payload has none), and the `with_locale` wrapper applies it for the duration of the job, then restores the worker thread's previous value. ## What this means in practice | Where `perform_later` is called | Locale the job gets | |---|---| | Inside the controller's `I18n.with_locale(:fr)` | `fr` | | From a Solid Queue recurring task | The scheduler's locale, normally `default_locale` | | From a rake task or the console | Whatever that process currently has | | Inside `I18n.with_locale(guide.locale) { ... }` | `guide.locale` | | After `job.locale = "de"` on an instance, then `job.enqueue` | `de` | Calling `perform_now` directly in a request gives a fresh job with no stored locale; `with_locale(nil)` changes nothing, so it simply runs in the request's current locale. ## Pitfalls - **The `perform_later` block is too late.** `perform_later(booking) { |job| job.locale = "de" }` yields the job **after** it has been enqueued, so the payload already holds the request's locale. Build the instance, set `locale`, then call `enqueue`, or wrap the call in `with_locale`. - **Fan-out jobs.** A nightly job that emails every guide captures one locale for the whole batch. Inside it, switch per recipient with `I18n.with_locale(guide.locale) { ... }`; mailers have their own conventions for this. - **Removed locales.** Jobs can wait in a queue across a deploy. If `:it` was dropped from `available_locales` meanwhile, `with_locale("it")` raises `I18n::InvalidLocale` when the job runs, and the job fails like any other error. - **Threads you start yourself** do not get this treatment; only Active Job records and restores the locale. ## Why not read the user's locale in the job instead? Both approaches exist. Capturing the locale at enqueue reflects the language of the request that caused the work, which suits "your booking is confirmed" messages. Reading `guide.locale` inside `perform` reflects the recipient's stored preference at send time, which suits scheduled reminders and digests. Many apps do both: enqueue inside `with_locale(record.locale)` so the payload is right, and still keep explicit per-recipient switching in batch jobs. ## Testing it With the test adapter, the serialized payload is visible, and running the job applies the stored locale: ```ruby I18n.with_locale(:fr) { TourReminderJob.perform_later(bookings(:old_town)) } assert_equal "fr", enqueued_jobs.last["locale"] perform_enqueued_jobs # runs inside I18n.with_locale("fr") ``` Asserting on the stored locale catches the common regression where a refactor moves the enqueue out of the request, for example into a rake task or a recurring schedule that runs in the default locale. ## Boundaries of this topic How arguments are serialized, how GlobalID passes records, and how retries work belong to Active Job itself; how mailers choose a recipient's language belongs to Action Mailer. The point here is narrower: the locale is part of the job's payload, captured when `perform_later` enqueues, and applied with `with_locale` when it runs.

  • Why doesn't TourReminderJob.perform_later(booking) { |job| job.locale = 'de' } change the job's locale?
    `perform_later` enqueues first and yields the job afterwards, so the payload already contains the request's locale when the block runs. Set `locale` on an instance before calling `enqueue`, or wrap `perform_later` in `I18n.with_locale(:de)`.
  • What happens to queued jobs when a locale is removed from available_locales?
    Each still carries the old locale string. When it runs, `perform_now` calls `I18n.with_locale` with it, enforcement rejects it and `I18n::InvalidLocale` is raised, so the job fails. Drain those jobs before removing a locale, or map retired values by overriding `deserialize` in `ApplicationJob` (call `super`, then replace `locale`), because the `with_locale` wrapper runs before any `around_perform` callback.

  • Jobs run in the worker's default locale unless perform reads it from the user.
  • Active Job reads I18n.locale again on the worker when perform starts.
  • The perform_later block can set job.locale before the job is enqueued.
  • A recurring Solid Queue task inherits the last web request's locale.
  • perform_now inside a request always switches to default_locale.