With Rails' automatic role switching (config.active_record.database_selector = { delay: 2.seconds }), how does each request end up on the primary or the replica?
answer
- bin/rails g active_record:multi_db
- GET and HEAD count as reads
- session[:last_write] timestamp
- delay window keeps you on primary
- reads still prevent writes
basics
~20 sThe DatabaseSelector middleware treats GET and HEAD as reads. Other verbs write to the primary and stamp a last-write time in the session; a read uses the replica unless that session wrote within the delay, then the primary, with writes blocked.
solid answer
~40 s`bin/rails g active_record:multi_db` writes `config/initializers/multi_db.rb` with the settings commented out; uncommenting `database_selector = { delay: 2.seconds }` makes Rails insert `ActiveRecord::Middleware::DatabaseSelector`. For each request the default `Resolver` checks the verb: GET and HEAD are reading requests, everything else runs under `connected_to(role: :writing)` and then stores `session[:last_write]`. A reading request goes to the replica unless less than `delay` has passed since that session's last write, in which case it reads from the primary. Either way a reading request runs with `prevent_writes: true`, so a GET action that writes raises `ActiveRecord::ReadOnlyError`. The protection is per session: other users, jobs and the console do not pass through it. You can swap `database_resolver` or `database_resolver_context` (for example, a cookie instead of the session).
go deeper
Know that Rails can switch GET requests to a replica automatically once the multi_db initializer is enabled.
Explain the GET/HEAD rule, the session last_write timestamp, the delay window and why reading requests block writes.
Name its limits (per-session only, fixed delay, nothing outside requests) and fix GET writes, session-less clients and jobs deliberately.
Decide whether request-wide automatic switching or explicit per-query routing fits the app, given how stale each screen may be.
## What the feature is Rails can choose the database role for each web request automatically. It is off by default. Turning it on inserts **`ActiveRecord::Middleware::DatabaseSelector`** into the middleware stack, and that middleware wraps the rest of the request in `ActiveRecord::Base.connected_to(...)` with a role it picks. You enable it with a generator and three settings: ```bash bin/rails g active_record:multi_db ``` The generator writes `config/initializers/multi_db.rb` with everything commented out. Uncommented, it reads: ```ruby Rails.application.configure do config.active_record.database_selector = { delay: 2.seconds } config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session end ``` Rails adds the middleware only when `database_selector` is set. The app must already have a reading role mapped with `connects_to`. The three keys split the job cleanly. `database_selector` is the options hash (the default resolver reads only `delay`). `database_resolver` is the class that decides between primary and replica for a request. `database_resolver_context` is the class that remembers when the client last wrote. Keeping them apart lets you replace one without rewriting the others. ## The decision, step by step For every request: 1. The **context** class (`Resolver::Session` by default) wraps the request's session. 2. The **resolver** asks `reading_request?`, which is true for **GET and HEAD** only. 3. **Not a reading request** (POST, PATCH, PUT, DELETE): run under `connected_to(role: :writing, prevent_writes: false)`, then store the time in `session[:last_write]` (milliseconds since the epoch), even if the action raised. 4. **Reading request, recent write**: if less than `delay` has passed since `session[:last_write]`, run under `connected_to(role: :writing, prevent_writes: true)`. 5. **Reading request, no recent write**: run under `connected_to(role: :reading, prevent_writes: true)`. The resolver publishes `database_selector.active_record.read_from_replica`, `read_from_primary` and `wrote_to_primary` notifications, so you can count where requests went. ## What it guarantees and what it does not | Situation | Outcome | |---|---| | An employee submits a timesheet correction, then is redirected to the payslip page | Their GET falls inside the delay, so it reads from the primary and sees the correction | | Their manager opens the same payslip one second later | The manager's session has no recent write, so the GET goes to the replica | | A GET action updates `last_seen_at` | `ActiveRecord::ReadOnlyError`, because reading requests always block writes | | A background job or the console | No middleware runs, so code stays on the default writing role | | A client that does not send the session cookie back | Each request looks write-free, so it reads from the replica | The guide states it plainly: Rails guarantees "read your own write" within the delay window, not "read a recent write" for other users. The `delay` is a fixed guess about how far replicas trail; it is not measured. ## Customising it - **Change the delay** to match your infrastructure. - **Change the context** with `database_resolver_context`: any class whose `call(request)` returns an object with `last_write_timestamp`, `update_last_write_timestamp` and `save(response)`. A cookie-based context suits clients without a server session. - **Change the rules** by subclassing `ActiveRecord::Middleware::DatabaseSelector::Resolver` and overriding `reading_request?`, for instance to treat a GET under `/admin` as a write. - **Allow one deliberate write in a GET** by wrapping it in `ActiveRecord::Base.connected_to(role: :writing) { ... }`; an explicit block beats the middleware's because it is pushed later on the role stack. ## Watching it in production Because the resolver instruments each decision, you can subscribe to the three notifications and count how many GETs actually reach the replica. A low share usually means users send a non-GET request on almost every page (autosave forms, tracking POSTs), which keeps their sessions inside the delay window. Two other checks pay off: 1. Confirm that the middleware is present with `bin/rails middleware`; if `database_selector` is unset, nothing switches. 2. Confirm that the app has a reading role at all. Without `connects_to ... reading:`, the first query in a reading request cannot find a pool and raises `ActiveRecord::ConnectionNotEstablished`. 3. Tune `delay` from evidence, not from the default: if users report stale pages after saving, the replicas trail by more than the window, and raising the delay keeps more reads on the primary. ## How to talk about it in an interview A good answer names the generator, the three config keys, the GET/HEAD rule, the session timestamp and the delay. It then says where it falls short: per-session only, a guessed delay, no coverage outside HTTP requests, and a hard failure for GET actions that write. That shows you know the mechanism is a simple default Rails expects you to adapt.
- A GET action in a payroll app records that a payslip was viewed and starts raising ActiveRecord::ReadOnlyError after automatic switching is enabled. Why, and what are the fixes?Reading requests always run with `prevent_writes: true`, even when they are routed to the primary within the delay, so the INSERT is refused. Move the write to a non-GET request, or wrap that one statement in `ActiveRecord::Base.connected_to(role: :writing) { ... }`, which pushes a writing role with writes allowed.
- How would you keep read-your-writes for an API client that never sends a session cookie?Replace the context. Set `config.active_record.database_resolver_context` to a class whose `call(request)` reads a last-write time from somewhere the client does carry (a signed cookie, or a key derived from the API token in a cache) and implements `last_write_timestamp`, `update_last_write_timestamp` and `save(response)`. The default resolver logic then works unchanged.
- database_selector routes every SELECT to the replica, whatever the HTTP verb.
- After a write, all users read from the primary for the delay window.
- A GET routed to the primary inside the delay window may write freely.
- The middleware also routes Active Job and console queries to the replica.
- Rails measures replica lag and adjusts the delay automatically.