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,

Rails allows for both manual and automatic shard switching in both vertical and horizontal sharding.

Each ActiveRecord connection (essentially a thread) contains information about the database that it is currently accessing. The connection information is stored in,

## Before

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!

## After

Using ActiveRecord::Base.prohibit_shard_swapping, 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.

Let’s see this in action!