In a Rails payroll service, how do replica: true, connects_to and connected_to(role: :reading) send report queries to a read replica safely?
answer
- replica: true in database.yml
- connects_to on the abstract class
- writing and reading roles, one pool each
- connected_to block forces prevent_writes
- ActiveRecord::ReadOnlyError on any write
basics
~20 sMark the replica entry replica: true, map roles in the abstract class with connects_to database: { writing: :primary, reading: :primary_replica }, and wrap report code in ActiveRecord::Base.connected_to(role: :reading). Inside, queries use the replica pool and any write raises ActiveRecord::ReadOnlyError.
solid answer
~40 sIn `database.yml` the replica gets its own entry with the same database name, a read-only user and `replica: true`, which tells Rails to skip `db:` tasks for it and to refuse writes on its connections. `ApplicationRecord` (an abstract class) calls `connects_to database: { writing: :primary, reading: :primary_replica }`, giving every model a pool per role; `:writing` is the default. Report code then runs inside `ActiveRecord::Base.connected_to(role: :reading) { ... }`. Within the block every model under that class reads from the replica, Rails sets `prevent_writes`, and an INSERT, UPDATE or `lock!` raises `ActiveRecord::ReadOnlyError` before the SQL is sent. The block returns its value, and a relation it returns is loaded before the role switches back. The switch is per thread and fiber, so work started in another thread does not inherit it.
code
ruby · 13 linesclass ApplicationRecord < ActiveRecord::Base
primary_abstract_class
connects_to database: { writing: :primary, reading: :primary_replica }
end
class PayrollReportsController < ApplicationController
def show
@totals = ActiveRecord::Base.connected_to(role: :reading) do
Payslip.where(period: params.expect(:period))
.group(:department_id).sum(:net_pay)
end
end
endgo deeper
Know that a replica entry is marked replica: true and that connected_to(role: :reading) runs a block of queries against it.
Explain how connects_to maps writing and reading roles to entries, why it lives on an abstract class, and what ReadOnlyError means.
Choose which reads may go to the replica, keep writes and read-after-write on the primary, and back Rails' guard with a read-only user.
Decide where replica routing belongs (explicit blocks versus a request-wide policy) and how reporting load should be isolated from transactional traffic.
## The pieces Sending reads to a replica in Rails takes three pieces that each do one job: 1. **A replica entry in `config/database.yml`**, flagged with `replica: true`. 2. **Role mapping with `connects_to`** on an abstract connection class, usually `ApplicationRecord`. 3. **A role switch with `connected_to`** around the code that should read from the replica. Rails also offers an automatic switch by HTTP verb; this answer is about the manual building blocks it uses. ## 1. The replica entry ```yaml production: primary: adapter: postgresql database: payroll_production username: payroll primary_replica: adapter: postgresql database: payroll_production username: payroll_readonly replica: true ``` - The **database name is the same** as the primary's, because the replica holds the same data. - A **separate read-only user** is the real guard; Rails' own checks are a safety net, not a permission system. - `replica: true` matters twice. Rails skips database tasks for the entry, so `db:migrate` and `db:create` never touch it, and the adapter treats every connection from it as **preventing writes**. ## 2. Mapping roles with connects_to ```ruby class ApplicationRecord < ActiveRecord::Base primary_abstract_class connects_to database: { writing: :primary, reading: :primary_replica } end ``` - `connects_to` may only be called on `ActiveRecord::Base` or an abstract class; on a concrete model it raises `NotImplementedError`. - It establishes **one pool per role**. The role names are symbols; `:writing` and `:reading` are the defaults Rails uses (`ActiveRecord.writing_role`, `ActiveRecord.reading_role`). - Models inheriting from the class start on the **writing** role, so nothing changes until you switch. ## 3. Switching with connected_to ```ruby summary = ActiveRecord::Base.connected_to(role: :reading) do Payslip.where(period: "2026-09").group(:department_id).sum(:net_pay) end ``` What the block guarantees: - Every model under the connection class queries through the **reading pool** for the duration of the block, then the previous role is restored. - `prevent_writes` is forced on for the reading role. A write (an INSERT, UPDATE, DELETE, or a locking read through `lock!`) raises **`ActiveRecord::ReadOnlyError`** ("Write query attempted while in readonly mode") before the statement reaches the server. - The block's value is returned. If that value is an `ActiveRecord::Relation`, Rails **loads it inside the block**, so a lazy relation still reads from the replica. - `connected_to` must be called on `ActiveRecord::Base` or on the abstract class that called `connects_to`. A role that class never configured raises `ActiveRecord::ConnectionNotEstablished`. - The role stack lives in per-thread (or per-fiber) state, so a `Thread.new` inside the block starts on the default role. ## Pitfalls interviewers probe | Pitfall | What actually happens | |---|---| | A report action that also writes an audit row inside the reading block | `ActiveRecord::ReadOnlyError`; do the write outside the block, or wrap it in `connected_to(role: :writing)` | | Reading a row the same request just wrote | The replica may not have it yet; read-after-write belongs on the writing role | | Expecting one transaction to cover both roles | Each role is a different connection, so a transaction on the writing pool does not include replica reads | | Several replicas behind one app | Rails does not load-balance replicas; point `primary_replica` at a load balancer or a single endpoint | | Tests | With transactional tests (the default), Rails makes the reading role share the writing pool, so fixture data is visible inside `connected_to(role: :reading)` | ## Choosing what goes to the replica in a payroll service Good candidates are reads that tolerate slightly old data and are expensive: month-end payroll totals, department cost reports, CSV exports, dashboards. Poor candidates are reads that decide a write (checking a balance before paying it out), reads right after the user's own change, and anything inside a transaction that also writes. Wrapping only the report queries in `connected_to(role: :reading)` keeps that decision visible in code review, which is the main advantage of manual switching over a request-wide rule. ## Related tools - `ActiveRecord::Base.while_preventing_writes { ... }` keeps the current role but blocks writes, which is useful for a read-only console session. - `connected_to_many(Payslip, role: :reading)` switches only the listed connection classes when an app has several databases. - `ActiveRecord::Base.connected_to?(role: :reading)` and `current_role` report the active role.
- Inside connected_to(role: :reading), what happens if the report code calls payslip.lock!?It raises `ActiveRecord::ReadOnlyError` ("Lock query attempted while in readonly mode"). `lock!` checks `current_preventing_writes` before issuing `SELECT ... FOR UPDATE`, and the reading role always prevents writes. Row locks belong on the writing role, inside a transaction.
- Is prevent_writes enough to stop writes to the replica?No, it is a safety net. Rails inspects the SQL it is about to send and refuses statements that are not reads, and its own docs say `while_preventing_writes` is not the same protection as a read-only database user. Give the replica entry a user that can only read, so the database enforces it too.
- Adding replica: true is enough; Rails then sends reads to the replica automatically.
- Payslip.connected_to(role: :reading) works on any concrete model class.
- A relation returned from connected_to runs later on the primary because relations are lazy.
- Writes inside connected_to(role: :reading) are quietly redirected to the primary.
- Rails load-balances across several replica entries listed under the reading role.