skip to content

In a Rails controller, why apply a user's time zone with Time.use_zone in an around_action instead of assigning Time.zone in a before_action?

level: middleimportance: should knowfreq 48%

answer

  1. per thread, not per request
  2. Puma reuses its threads
  3. ensure puts the old zone back
  4. find_zone! raises ArgumentError
  5. jobs carry Time.zone.name

basics

~20 s

Time.zone= writes thread- or fiber-local state that Rails does not reset after a request, so a reused Puma thread hands it to the next request. Time.use_zone sets the zone only for its block and restores the previous one in an ensure.

solid answer

~40 s

`Time.zone=` stores the zone in `ActiveSupport::IsolatedExecutionState`, which is per thread (or per fiber), not per request, and Rails' executor does not clear it when the request ends. Puma serves many requests on the same threads, so a `before_action` that assigns `Time.zone` only for signed-in users leaks the last user's zone into the next anonymous request on that thread. `Time.use_zone(zone) { ... }` swaps the zone in, yields, and restores the old value in an `ensure`, so it is undone even when the action raises; an `around_action` gives it exactly the action's scope. Two details matter: `use_zone` calls `Time.find_zone!`, which raises `ArgumentError` for an unknown name, so validate the stored zone; and passing `nil` falls back to `config.time_zone`. Jobs enqueued inside the block record `Time.zone.name` and perform in that zone.

code

ruby · 9 lines
ruby
class ApplicationController < ActionController::Base
  include Authentication
  around_action :use_user_time_zone

  private
    def use_user_time_zone(&action)
      Time.use_zone(Current.user&.time_zone, &action)  # nil -> config.time_zone
    end
end

go deeper

for a junior

Know the idiom: an around_action that wraps the action in Time.use_zone(current user's zone), and that the block form puts the old zone back afterwards.

for a middle

Explain that Time.zone= is thread- or fiber-local state the executor does not reset, how Puma's thread reuse leaks it, and what find_zone! raises for a bad name.

for a senior

Cover the review details: validating stored zones, objects read before the block, callback order behind authentication, and jobs inheriting the zone through Active Job's timezone field.

for a principal

Decide where a request's zone comes from — user profile, tenant or site — and make one wrapper the only place it is set, so no code path assigns Time.zone directly.

## Where Time.zone actually lives `Time.zone` is not a request object. Its setter is: - `Time.zone = name` → `ActiveSupport::IsolatedExecutionState[:time_zone] = Time.find_zone!(name)` - `Time.zone` → that stored value, **or** `Time.zone_default` (from `config.time_zone`) when none is stored. `IsolatedExecutionState` is keyed by the current **thread**, or by the current **fiber** when `config.active_support.isolation_level = :fiber`. Rails' executor, which wraps each request, resets things such as `CurrentAttributes` and the query cache, but it does **not** clear `:time_zone`. Whatever a request assigns stays on that thread after the response is sent. ## The leak a before_action creates A Rails server such as Puma keeps a small pool of threads (three per process in the generated `config/puma.rb`) and runs request after request on each one. With this filter: 1. Request A from a signed-in Tokyo user runs `Time.zone = "Tokyo"` on thread 1. 2. Request A finishes; thread 1 still has Tokyo stored. 3. Request B, from an anonymous visitor, lands on thread 1. The filter skips assignment for guests, so `Time.zone` is still Tokyo. 4. The guest sees prices, cut-offs and "today" in Tokyo time — and the bug appears only under concurrency, never in a single-threaded test. Assigning a zone for **every** request, including guests, hides the problem, but the zone still outlives the request — in an exception path, a streaming response, or code that runs after the action on the same thread. ## What Time.use_zone does instead `Time.use_zone(zone) { ... }`: 1. Resolves the zone with `Time.find_zone!` before touching anything — an unknown name raises `ArgumentError` ("Invalid Timezone: ...") and the block never runs. 2. Saves the current `Time.zone`, assigns the new one, and **yields**. 3. Restores the saved zone in an **`ensure`**, so the reset happens whether the block returns, raises or is interrupted. An `around_action` gives the block exactly the action's extent: the filters declared after it, the action and its rendering run inside it. Passing `nil` is legal — `find_zone!(nil)` returns `nil`, and `Time.zone` then falls back to `Time.zone_default` — so a guest can simply get the app's default zone. ## Side by side | | `before_action` with `Time.zone =` | `around_action` with `Time.use_zone` | |---|---|---| | Scope | rest of the thread's life | the block only | | Reset after the response | never | always, in an `ensure` | | Request that skips the assignment | inherits the last zone | gets `config.time_zone` | | Exception in the action | zone stays set | zone restored | | Unknown zone name | `ArgumentError` | `ArgumentError`, before the block runs | ## Details that come up in review - **Validate the stored zone.** A typo in a user's `time_zone` column turns every request of that user into a 500 via `ArgumentError`. Validate with `inclusion: { in: ActiveSupport::TimeZone.all.map(&:name) }` if you only accept Rails' friendly names, or with `Time.find_zone(value)` (which returns `nil` instead of raising) if you also accept IANA identifiers such as `"America/Boise"` — `ActiveSupport::TimeZone.all` lists only Rails' mapped zones. - **Objects built earlier keep their zone.** A `TimeWithZone` created before the block, such as a timestamp read in an earlier filter, is not converted retroactively; read records inside the block or call `in_time_zone` on them. - **Jobs inherit the zone.** Active Job records `Time.zone&.name` in the serialized job and wraps `perform` in `Time.use_zone`, so a job enqueued inside the block runs in the user's zone on the worker. - **Order of callbacks.** Declare the `around_action` after the filter that identifies the user (the generated `Authentication` concern's `before_action`), or the user is not known yet. - **Console and scripts.** Outside a request, prefer `Time.use_zone` as well; a bare `Time.zone =` in a rake task or console changes that thread until it ends. rubocop-rails' `Rails/TimeZoneAssignment` cop (pending, so you opt in) flags such assignments.

  • A record is loaded in a before_action that runs before the around_action; which zone does its updated_at use in the view?
    The zone that was current when it was read — the default zone, not the user's. `Time.use_zone` changes `Time.zone` but does not convert `TimeWithZone` objects that already exist. Either declare the around_action first, load the record inside it, or call `in_time_zone` when displaying.
  • Does a job enqueued inside Time.use_zone run in the user's zone?
    Yes. Active Job stores `Time.zone&.name` as the job's `timezone` when it is created, serializes it with the job, and the worker runs `perform` inside `Time.use_zone(timezone)`.
  • Why can't a single-threaded test reproduce the Time.zone leak from a before_action?
    The leak needs two requests to share a thread: one that assigns a zone and a later one that does not. A test that runs one request per thread, or that assigns a zone on every path, never observes the stale value. It shows up in production under Puma's thread reuse.

A shared hotel room's thermostat: a guest who turns it to 18 °C and leaves it there hands that setting to the next guest, while a thermostat that resets itself at checkout gives every guest the default.

  • Rails resets Time.zone to config.time_zone after every request
  • Each Puma request runs on a brand-new thread, so Time.zone cannot leak
  • Time.use_zone silently falls back to UTC for an unknown zone name
  • Time.use_zone also converts TimeWithZone objects created before the block
  • Time.zone is stored in the session, so it follows the user between requests