Rails provides shards as a way to connect with multiple databases,
much more complex than replicating.
Each shard can either be a vertical
or a horizontal splice of the entire application database.
With vertical sharding, one can read
and write to more tables than available in the primary one.
Horizontal sharding allows one to split the data on the primary database
based on defined resolvers (id greater than x
or domain equal to x).
Here’s how the database is configured,
We will use an example of horizontal sharding,
configured in ApplicationRecord,
Each ActiveRecord connection (essentially a thread)
contains information about the database that it is currently accessing.
The connection information is stored in,
ActiveRecord provides connect_to to easily swap out shards.
Let’s swap to shard_two.
Zero blogs since this shard has not been written to yet!
we can prevent attempts to change the shard within a block.
When using sharded databases for the lifecycle of an entire request,
it’s often desirable to ensure that the databases’
shard is not unintentionally changed.
This option is also thread-safe.