Database read replicas for scaling reads

6818
0

As applications grow, read operations often dominate database load. Directing reads to replica databases while keeping writes on the primary reduces contention and improves response times. Rails makes this straightforward with connects_to and role-based routing. I configure database.yml with separate connection pools for primary and replica, and use ActiveRecord::Base.connected_to(role: :reading) blocks to route queries to replicas. The framework automatically routes writes to primary regardless of the current role. For API endpoints that only read data, I set a controller-level around_action to use the reading role by default. Replica lag is a consideration—I use primaries for reads immediately after writes to avoid stale data.