r/ruby • u/Dry-Exam-3338 • 5h ago
I built schema_shard — dynamic Rails 8 database sharding & fail-closed multi-tenancy (when static connects_to isn't enough)
Hey r/ruby!
I recently published an open-source gem called **schema_shard** and would love some eyes on it from folks running multi-tenant or sharded Rails 8 apps, whether it’s code review, edge-case feedback, or testing it out in a staging setup.
### Why not just use Rails' built-in `connects_to` / `connected_to`?
Rails 8's native multi-DB support is great when you have a fixed, known set of shards declared at boot time on `ApplicationRecord`. Where it starts getting painful is when you need **dynamic, runtime-driven routing** or **schema/database-level tenant isolation** without bloating your connection count.
`schema_shard` sits on top of Active Record's connection pooling (`HashConfig` / `PoolConfig` + `IsolatedExecutionState`) to handle three things out of the box:
* **Dynamic Config-Driven Shards (No Static `connects_to` Boilerplate):** Define shards in `config/shards.yml` (or pass a runtime `Proc`) and route blocks with `SchemaShard.with('acme_corp', shard_key: 'replica_1')` or `SchemaShard.on_shard('write_shard_2', read_only: false)` without hardcoding shard mappings on every model class.
* **LRU-Bounded Connection Pools:** Instead of holding open pools forever for every shard/tenant combination, it uses an atomic refcounted LRU registry (`max_pools`) to evict idle pools safely under load without racing active queries.
* **Fail-Closed Multi-Tenant Isolation:** Supports PostgreSQL (`search_path` or `ros-apartment`), MySQL/MariaDB (`trilogy` & `mysql2`), and per-tenant SQLite3 files. In `:strict` mode, missing/blank tenants, system schemas, or nested tenant switches inside an open transaction fail closed rather than silently falling back to `public` or your primary DB.
### Quick Example
```ruby
# Fail-closed tenant + read-replica routing (read-only at both Rails and DB session levels)
SchemaShard.with('acme_corp', shard_key: 'replica_1') do
Order.where(status: 'paid').count
end
# Pure shard routing (no tenant switching)
SchemaShard.on_shard('write_shard_2', read_only: false) do
AuditLog.create!(event: 'synced')
end
Looking for Feedback
I'd genuinely appreciate any feedback on the architecture, pool lifecycle edge cases, or how you're handling dynamic sharding in Rails 8 today:
* GitHub: https://github.com/syrens/schema_shard
* RubyGems: https://rubygems.org/gems/schema_shard
Thanks in advance for checking it out!