Rails 6.1 adds support for role switching and sharding in database
Jan 8, 2021 , by Alkesh Ghorpade
2 minute read
Rails 6.1 adds the ability to
switch a role or shard for an application with multiple databases.
This means it is possible to switch connections for one database instead of
all databases globally.
To use this feature, we need to set the below config in our application.
Let’s say we have two databases, primary and vehicles.
And we have shards and replica configured for each of them in database.yml as below:
We have two models User and Car. User is stored in the primary database and
Car in the vehicles database.
The corresponding model and abstract classes will look as below:
When legacy_connection_handling is set to false, any abstract connection class will
be able to switch connections without affecting other connections.
In both the above VehiclesRecord.connected_to and ApplicationRecord.connected_to
blocks the connection was changed to shard_one of the corresponding database.
As seen above, when we connect VehiclesRecord to shard_one only Car queries
are executed on shard_one whereas User queries are executed on primary
The addition of this granular switching is useful in cases like:
Suppose replica or shard_one is not configured for primary
database. A connection is made to shard_one and User queries are executed
under the shard_one block, then an error would be thrown. This is because the
connection was changed globally across all databases.
If two shards shard_one and shard_two are configured for both databases,
user_a exists on shard_one and user_b on shard_two. If VehiclesRecord
connection is changed to shard_two and we query for user_a under that block
it will return incorrect result.