In Rails, how do connects_to shards: and connected_to(shard:) route an abstract class's models to horizontal shards, and what does the ShardSelector middleware add?
answer
- one database.yml entry per shard
- connects_to shards: on an abstract class
- first shard key is default_shard
- shard_resolver proc per request
- lock: true prohibits shard swapping
basics
~20 sEach shard gets its own database.yml entries, and an abstract class maps them with connects_to shards: { shard_one: { writing:, reading: }, ... }. Code picks one with connected_to(role:, shard:) { }, and ShardSelector does it per request from config.active_record.shard_resolver, locking the choice by default.
solid answer
~40 sIn `database.yml` every shard is a writer entry (plus an optional `replica: true` entry), all sharing one `migrations_paths` so they get the same schema. An abstract class such as `ShardRecord` calls `connects_to shards: { shard_one: { writing: :primary_shard_one, reading: :primary_shard_one_replica }, ... }`; the first key becomes `default_shard`. Code switches with `ShardRecord.connected_to(role: :writing, shard: :shard_one) { ... }`, and an unknown shard raises `ActiveRecord::ConnectionNotEstablished`. `connected_to_all_shards` runs a block on every shard and returns an array. For per-request routing, set `config.active_record.shard_resolver` to a proc from request to shard name; Rails then inserts `ActiveRecord::Middleware::ShardSelector`, which wraps the request in `connected_to(shard:)`. Its `shard_selector` options are `lock:` (default true, which makes a nested shard switch raise `ArgumentError`) and `class_name:` for the connection class.
go deeper
Know that Rails can connect one abstract model class to several identical databases, called shards, and switch between them in a block.
Explain the database.yml entries, connects_to shards:, default_shard and connected_to(role:, shard:), including the error for an unknown shard.
Wire ShardSelector with a resolver and lock: true, keep lookup tables unsharded, and make jobs pick their shard explicitly.
Judge whether Rails' shard routing is enough or a database-side router fits better, given cross-shard reporting and rebalancing needs.
## What Rails provides, and what it leaves to you **Horizontal sharding** splits the rows of the same tables across several databases with identical schemas. How to choose a shard key and how to rebalance are system-design questions. Rails' part is narrower: it lets one abstract class hold **a pool per shard and role**, lets code pick the shard for a block, and offers a middleware that picks it per request. ## 1. database.yml: one entry per shard ```yaml production: primary: database: payroll_production adapter: postgresql primary_shard_one: database: payroll_shard_one adapter: postgresql migrations_paths: db/migrate_shards primary_shard_one_replica: database: payroll_shard_one adapter: postgresql replica: true primary_shard_two: database: payroll_shard_two adapter: postgresql migrations_paths: db/migrate_shards ``` - Every shard writer points at the **same `migrations_paths`** (and leaves `schema_dump` alone), so one set of migrations keeps them identical. Generating a migration with `--database primary_shard_one` writes into that shared path. - A shard can have its own replica entry with `replica: true`. ## 2. Mapping shards with connects_to ```ruby class ShardRecord < ApplicationRecord self.abstract_class = true connects_to shards: { shard_one: { writing: :primary_shard_one, reading: :primary_shard_one_replica }, shard_two: { writing: :primary_shard_two } } end class Payslip < ShardRecord end ``` - `connects_to` accepts **either** `database:` **or** `shards:`, never both; passing both raises `ArgumentError`. - The **first key** becomes the class's `default_shard`, so code that never switches uses `shard_one` here. - `ShardRecord.sharded?` is true and `ShardRecord.shard_keys` returns `[:shard_one, :shard_two]`. ## 3. Switching shards in code ```ruby ShardRecord.connected_to(role: :writing, shard: :shard_two) do Payslip.create!(employee_id: 42, period: "2026-09", net_pay: 3_150) end ``` - Pass the role together with the shard; the guide writes them as a pair. - A shard name the class never configured raises **`ActiveRecord::ConnectionNotEstablished`**. - `ShardRecord.connected_to_all_shards(role: :reading) { Payslip.count }` runs the block on each shard and returns an **array** of the results; summing them is your job. - A record created on one shard is invisible from another; `Payslip.find(id)` on the wrong shard raises `ActiveRecord::RecordNotFound`. ## 4. Per-request switching with ShardSelector Setting `config.active_record.shard_resolver` makes Rails insert **`ActiveRecord::Middleware::ShardSelector`**. For each request it calls the resolver with the request, converts the result to a symbol and wraps the request in `connected_to(shard: ...)`. ```ruby Rails.application.configure do config.active_record.shard_selector = { lock: true, class_name: "ShardRecord" } config.active_record.shard_resolver = ->(request) { Employer.find_by!(subdomain: request.subdomain).shard } end ``` | Option | Default | Effect | |---|---|---| | `lock:` | `true` | wraps the request in `prohibit_shard_swapping`; any nested `connected_to(shard:)` raises `ArgumentError` ("cannot swap `shard` while shard swapping is prohibited") | | `class_name:` | `ActiveRecord::Base` | the abstract connection class to switch; set it when the sharded models live under their own class | The same generator as automatic role switching, `bin/rails g active_record:multi_db`, writes these lines commented out in `config/initializers/multi_db.rb`. ## How it differs from replicas Replicas copy **all** rows of one database, and switching roles changes *which copy* answers. Shards hold **different** rows, and switching shards changes *which data exists* for the query. That is why a missed role switch only costs freshness or load, while a missed shard switch returns wrong or missing records. Both can be combined: each shard can have its own reading role, chosen with `connected_to(role: :reading, shard: :shard_one)`. ## Inspecting the current shard Inside a block, `ShardRecord.current_shard` returns the active shard key and `ShardRecord.current_role` the active role, while `ShardRecord.connected_to?(role: :writing, shard: :shard_two)` answers both at once. Logging `current_shard` next to each request id makes tenant routing auditable, and it is the first thing to check when a payslip "disappears" because it was written to a different shard than the one being read. ## Pitfalls - **Tenant leaks.** With `lock: false`, any code path can switch to another tenant's shard mid-request; keep `lock: true` for tenant-per-shard designs. - **Unsharded tables.** Lookup tables (like `Employer` above) must live in a database that is not sharded, or the resolver cannot find the shard. - **Background work.** Jobs and the console do not pass through the middleware, so they must call `connected_to(shard:)` themselves. - **No cross-shard queries.** Joins and transactions stay inside one shard's connection. - **Schema drift.** Running migrations against only one shard leaves the others behind; the shared `migrations_paths` exists so `db:migrate` treats every shard writer the same way.
- With ShardSelector configured as lock: true, what happens when a controller action calls ShardRecord.connected_to(role: :reading, shard: :shard_two)?It raises `ArgumentError` ("cannot swap `shard` while shard swapping is prohibited"). The middleware runs the request inside `prohibit_shard_swapping(true)`, and `connected_to` refuses any entry that names a shard while that flag is set. A role-only switch, such as `connected_to(role: :reading)`, is still allowed.
- How do you run a report across every shard in Rails?Call `ShardRecord.connected_to_all_shards(role: :reading) { Payslip.where(period: "2026-09").sum(:net_pay) }`. Rails runs the block once per key in `shard_keys` and returns an array of the per-shard results, which you combine yourself. Run it outside a locked ShardSelector request, for example in a job.
- connects_to can take database: and shards: together on the same class.
- Without a switch, queries fan out to every configured shard automatically.
- ShardSelector's lock option defaults to false, so code may switch tenants freely.
- connected_to_all_shards merges the per-shard results into one relation.
- Each shard needs its own separate migrations_paths directory.