A Rails city-guide app assigns I18n.locale = params[:locale] in EventsController's before_action; why do visitors to other pages sometimes see German?
answer
- per-thread state, reused server threads
- nothing resets I18n.locale between requests
- Fiber[:i18n_config] in i18n 1.15
- Current attributes are reset, I18n is not
- one thread makes it reproducible
basics
~20 sI18n.locale is per-thread state and Puma reuses threads across requests. Rails never resets it, so German set during an events request stays on that thread and shows up on the next request whose controller sets no locale.
solid answer
~40 s`I18n.locale=` writes into the i18n configuration for the current execution context; with i18n 1.15 on Ruby 3.2 and later that object lives in fiber storage (`Fiber[:i18n_config]`), earlier setups used a thread variable. Puma serves requests from a small pool of long-lived threads, and while Rails' executor clears `ActiveSupport::CurrentAttributes` after each request, nothing resets `I18n.locale`. After `/events?locale=de`, that thread keeps `:de`; the next request it serves, say the museums page, whose controller sets nothing, renders German, while requests on other threads stay English. That makes the bug intermittent and easy to reproduce with a single thread. The fix is to set the locale on every request from `ApplicationController`, ideally with `I18n.with_locale` in an `around_action`, so each request starts from an explicit value and restores it afterwards.
code
ruby · 8 lines# The bug
class EventsController < ApplicationController
before_action { I18n.locale = params[:locale] || I18n.default_locale }
end
class MuseumsController < ApplicationController
# sets nothing: renders in whatever locale this thread still holds
endgo deeper
Recall that assigning I18n.locale does not undo itself and that with_locale is the safe way to switch.
Explain that the locale is per-thread state, that Puma reuses threads, and why only some requests show the wrong language.
Show how you reproduce with one thread, fix it in ApplicationController with with_locale, and audit tests, threads and console code for the same leak.
Weigh ambient per-thread context against passing the locale explicitly through services, jobs and mailers as the codebase grows.
## Where `I18n.locale` lives The i18n gem keeps one **configuration object per execution context**. In i18n 1.15, on Ruby 3.2 and later, `I18n.config` is stored in Ruby's fiber storage under `Fiber[:i18n_config]`; on older Rubies it used a thread variable. The gem's own comment is explicit: the locale is the only configuration value that is not global. `default_locale`, `available_locales`, the backend and the load path are process-wide. So `I18n.locale = :de` changes the value for **the current thread's context only**, and it stays changed until something assigns it again. ## Why it survives the request Three facts combine: 1. **Puma reuses threads.** A Rails app in production runs a few threads per Puma process (3 in the generated `config/puma.rb`), each serving request after request. 2. **Rails resets other per-request state, not this one.** The Rails executor clears `ActiveSupport::CurrentAttributes` when a request completes. There is no matching reset for `I18n.locale`. 3. **The controller's I18n proxy writes through.** During an action Rails swaps in an `ActionView::I18nProxy` so template lookup tracks the locale, but assigning `I18n.locale` through it still sets the locale on the real configuration object underneath. The value remains on the thread after the action. The result is a **leak**: the German locale from an events request sits on thread 2; the next request handled by thread 2, maybe a museum page with no locale code, renders in German. ## Recognising and reproducing it | Symptom | What it points to | |---|---| | Wrong language on random requests | Different threads hold different leftover locales | | Starts only after someone visits one particular page | That page's controller assigns without restoring | | Disappears when every request sets a locale | The bug is a leftover value, not bad translation data | Reproduce deterministically by running the server with one thread (`RAILS_MAX_THREADS=1 bin/rails server`), visiting `/events?locale=de`, then `/museums`: the second page renders German every time. ## The fix - Move locale selection into **`ApplicationController`** so every request sets it, including pages that do not care about `params[:locale]`. - Use **`I18n.with_locale` in an `around_action`**, which saves the previous value and restores it in an `ensure`. - Resolve a **concrete fallback** (`I18n.default_locale`) rather than passing `nil`, because `with_locale(nil)` changes nothing and would inherit a leftover value from a thread that was polluted earlier. ```ruby class ApplicationController < ActionController::Base around_action :switch_locale private def switch_locale(&action) locale = I18n.locale_available?(params[:locale]) ? params[:locale] : I18n.default_locale I18n.with_locale(locale, &action) end end ``` After the fix, every request sets an explicit locale for its own duration, so a leftover value cannot be observed even if some other code assigns one. ## The same leak elsewhere - **Tests.** A test that sets `I18n.locale = :fr` without restoring it changes later tests in the same thread; wrap such tests in `I18n.with_locale`. - **Threads you start.** A `Thread.new` inside a request inherits the request's fiber storage, so it starts with the request's i18n configuration rather than `default_locale`; pass the locale explicitly instead of relying on either. - **Background jobs** are the exception that works: Active Job records the locale at enqueue time and restores it around `perform`. - **Console and rake tasks** keep whatever locale they last assigned for the life of the process. ## Auditing a codebase A quick review finds most leaks: - Search for `I18n.locale =` outside `config/` and tests; each hit should be a `with_locale` block or sit inside one. - Check that the locale is chosen once, in `ApplicationController` or a concern it includes, not per controller. - Look at helpers, presenters and service objects that switch locale to render one string; they should pass `locale:` to `t` and `l` instead of changing the ambient value. - In the test suite, wrap locale-specific tests in `I18n.with_locale` so their order cannot change results. ## What the interviewer is checking This scenario tests whether a candidate can connect an intermittent symptom to per-thread state on a reused thread, name the Rails-specific reason it is not reset, and choose `with_locale` in the base controller rather than patching the one controller that showed the bug.
- Why doesn't the leak show up when you test one page at a time in development?With several Puma threads, a leftover locale only shows when the next request lands on the same thread and its controller sets nothing. Single page loads rarely line up that way. Running with one thread, or a request spec that hits the assigning page and then another page, reproduces it reliably.
- Would moving the assignment into ApplicationController's before_action be enough?It stops the visible symptom, because every request now overwrites the leftover value. It still leaves the locale set after the request, which code running later on that thread, outside a controller, can observe. `with_locale` in an `around_action` sets and restores, so nothing is left behind.
- I18n.locale is reset to default_locale at the start of every request.
- The leak means I18n.locale is one global value shared by all threads.
- Rails stores I18n.locale in the session, so it follows the visitor.
- Rails' executor clears I18n.locale along with Current attributes.
- Fixing EventsController alone is enough; other controllers inherit the default.