skip to content

When you must inspect live data in a ski-rental Rails 8.1 app, what does bin/rails console --sandbox protect against, and what does it leave exposed?

level: seniorimportance: should knowfreq 38%

answer

  1. transaction opened on every connection checkout
  2. never committed, discarded on exit
  3. row locks held until you quit
  4. after_commit still fires inside sandbox
  5. sandbox_by_default and disable_sandbox

basics

~20 s

--sandbox opens a transaction on every database connection the console checks out and never commits it, so row changes vanish on exit. Locks, after_commit side effects, emails, HTTP calls and heavy reads still reach production.

solid answer

~40 s

With `--sandbox` (`-s`) Rails installs a checkout callback that begins a non-joinable transaction on each connection, so every `INSERT`, `UPDATE` and `DELETE` you run stays uncommitted and is discarded when the console exits. That protects the rows, nothing more. The writes still execute and hold row locks for as long as the session stays open, so Puma requests or job workers touching the same `rentals` rows wait on you. Because the outer transaction is not joinable, each `save` runs in its own savepoint and Active Record fires `after_commit` callbacks when that inner transaction finishes, so broadcasts, mail sent with `deliver_now` and calls to a payment API still happen. Reads are unrestricted, too. Rails 7.1 added `config.sandbox_by_default` (sandbox outside development and test unless `--no-sandbox`) and `config.disable_sandbox` refuses sandbox sessions outright.

code

ruby · 4 lines
ruby
# config/environments/production.rb
Rails.application.configure do
  config.sandbox_by_default = true   # bin/rails console is sandboxed; --no-sandbox to write
end

go deeper

for a junior

Know that --sandbox discards database changes on exit and that it is the habit for poking at real data.

for a middle

Explain the mechanism: a transaction begun on connection checkout and never committed. Know sandbox_by_default and disable_sandbox exist.

for a senior

Name the gaps on a live system: row locks held until exit, after_commit side effects, external calls, unbounded reads and data exposure. Prefer preventing writes or a replica for pure reading.

for a principal

Set the team's policy for production consoles: sandbox by default, who may open --no-sandbox, how sessions are audited, and when a console fix must become reviewed code.

## The situation A ski-rental shop's app shows a customer's booking with the wrong return date. You need to look at the `Rental`, its `Booking` and the customer's `Payment` rows on production, and perhaps try the fix before writing it properly. The production console is the fastest tool and the most dangerous one: one mistyped `update_all` changes real bookings. ## What --sandbox does mechanically `bin/rails console --sandbox` (or `-s`) sets `Rails.application.sandbox = true`. When the console loads, Active Record requires `active_record/railties/console_sandbox`, which adds one callback to every adapter: - after a connection is **checked out**, it calls `begin_transaction(joinable: false)`; - nothing ever commits that transaction, so when the console process exits, the database discards it; - the banner says so: `Any modifications you make will be rolled back on exit`. Because the callback is on checkout, it covers every database the console touches, including the `queue`, `cache` and `cable` databases a Rails 8.1 production config declares. ## What it protects - **Row changes.** Creates, updates and deletes through any model or raw SQL on those connections are never committed. - **Your own transactions.** A `transaction do ... end` in your code becomes a savepoint inside the sandbox transaction, so even an explicit commit in your code does not reach the database. ## What it leaves exposed | Exposure | Why | |---|---| | **Row locks** | An uncommitted `UPDATE rentals ...` holds its row locks until you exit; web requests and job workers updating those rows block. | | **Database resources** | A transaction held open for the whole session ties up database resources; Rails' configuration guide warns a long sandbox session can make the database server run out of memory. | | **after_commit side effects** | Inner transactions nested in a non-joinable one run their commit callbacks when they finish, so `after_commit` broadcasts, mail and enqueue-after-commit logic all run. | | **Anything outside the database** | `deliver_now` mail, HTTP calls to a payment provider, files written to disk, an external cache: none of it is transactional. | | **Reads** | `Rental.all.to_a` still loads every row into memory and still loads the database. | | **Inspecting data** | The console sets `attributes_for_inspect` to `:all`; `filter_attributes` still masks names in `filter_parameters` such as `email`, but `customer.email` returns the raw value. | The sandbox is a safety net for **row changes**, not a read-only mode and not an isolation boundary for side effects. ## Making it the default, or forbidding it Two settings shape console behaviour per environment: `sandbox_by_default`, added in Rails 7.1, and the older `disable_sandbox`: 1. `config.sandbox_by_default = true` makes `bin/rails console` start sandboxed **outside development and test**; `--no-sandbox` is then needed to write for real. Put it in `config/environments/production.rb` so the risky path takes an explicit flag. 2. `config.disable_sandbox = true` makes `--sandbox` refuse to start (`Unable to start console in sandbox mode as sandbox mode is disabled`), for teams that would rather not have long-lived sandbox transactions at all. ## A safer routine for the ski-rental case 1. Open the console sandboxed (or rely on `sandbox_by_default`), and confirm the red `prod` tag in the prompt. 2. Read first: `Rental.find(...)`, `.where(...).limit(20)`, `.pluck(...)`, never unbounded `.all`. 3. If you try a fix, keep the session short so locks clear quickly, and expect any `after_commit` work, including mail or a payment call, to fire. 4. For pure reading, `ActiveRecord::Base.while_preventing_writes { ... }` raises `ActiveRecord::ReadOnlyError` on write queries (Rails documents it as a guard against accidents, weaker than a read-only database user), and a replica connection keeps the load off the primary. 5. Ship the real fix as reviewed code (a migration or a task), not as console history. ## What an interviewer is listening for The weak answer is "sandbox makes it safe". The strong answer names the mechanism (a non-joinable transaction opened on checkout and never committed) and then the edges: locks held for the session, commit callbacks that still fire, side effects outside the database, unbounded reads, and the data you can see. It ends with the guardrails a team can configure.

  • With sandbox_by_default enabled, does bin/rails console start sandboxed in development?
    No. The console only applies `sandbox_by_default` when the environment is not local, so development and test start normally unless you pass `--sandbox`. In production it starts sandboxed, and `--no-sandbox` is the explicit opt-out for real writes.
  • Why can a sandbox session make web requests time out on the same records?
    Each write runs for real inside the uncommitted sandbox transaction and takes the database's row locks. Those locks are held until the transaction ends, which is when the console exits. A request or job that updates the same row waits for the lock, so a forgotten sandbox session after one `update!` can stall checkouts on that rental.
  • If you only need to read production data, what is stricter than --sandbox?
    Wrap the session's work in `ActiveRecord::Base.while_preventing_writes { ... }`, which raises `ActiveRecord::ReadOnlyError` on write queries instead of executing them, or connect to a replica with a read-only database user, the stronger of the two. Both stop the write rather than rolling it back later, so no lock is taken.

  • --sandbox makes the production console read-only
  • after_commit callbacks never fire inside a sandbox console
  • Sandbox writes take no locks because they are rolled back
  • sandbox_by_default also sandboxes the development console
  • Mail sent with deliver_now in a sandbox is rolled back too
  • --sandbox only covers the primary database, not queue or cache

Assumes Rails 8.1; config.sandbox_by_default and its non-local scope arrived in Rails 7.1.