What is database sharding in the context of Rails?

Answer

Sharding horizontally partitions data across multiple databases based on a key (e.g., user ID), with each shard holding a subset of the data. Rails 6.1+ introduced first-class horizontal sharding support via ActiveRecord::Base.connected_to(shard: :shard_one) { ... }. Configure shards in database.yml. A shard resolver determines which shard to connect to for a given request. Sharding solves write scalability (each shard handles only a portion of writes) and can keep data geographically close to users. Challenges: cross-shard queries are complex, schema changes must be applied to all shards, and re-sharding existing data is painful.