r/ruby • • 3d 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!

3 Upvotes

3 comments sorted by

2

u/KevinSaison 3d ago

Interesting project, but it appears to reimplement several responsibilities that Rails' connection implements.
What correctness or isolation guarantee does schema_shard provide that cannot be achieved with Rails' native connection management ?

2

u/Dry-Exam-3338 3d ago

Totally fair question. If you just have a static primary + replica known at boot with tenant_id columns, definitely just use connects_to / connected_to. Also fwiw, schema_shard doesn't write its own pooler - it still builds standard ActiveRecord::DatabaseConfigurations::HashConfig / PoolConfig and ConnectionPool instances under the hood.

I built it because connected_to stops at the pool boundary, which leaves a bunch of footguns when multiple tenants share a shard pool via schemas (SET search_path / Apartment / MySQL USE) or when pools aren't static at boot:

- connected_to switches databases, not schemas inside a pooled connection. When switching search_path on a shared replica pool, Rails won't reset the namespace on checkin, won't clear prepared statement caches on switch (clear_cache! - otherwise PG can run a cached plan still bound to the previous tenant's table OIDs), and won't check wire-level transaction state (PG::PQTRANS_IDLE / Trilogy in_transaction?) if raw SQL left a BEGIN open.

- In :strict mode it rejects nil/system schemas and accidental public fallbacks. If a nested switch happens mid-transaction or leaves a dirty session, it pulls that socket out of the pool before disconnecting and taints the execution frame (TaintedConnectionError) so even a rescue StandardError in app code can't keep querying on an uncertain tenant.

- connects_to registers every shard pool permanently for the life of the process. If you're routing across hundreds of per-tenant SQLite files (%{tenant}.sqlite3) or reloading shards.yml at runtime, you need refcounted LRU eviction so idle pools get reaped without racing active queries.

- Pairs while_preventing_writes (which is SQL-regex based in Ruby) with actual session flags (default_transaction_read_only = on / transaction_read_only = 1 / PRAGMA query_only = ON), blocks nested read_only: false escalation, and keeps global models like Account on primary without refactoring model inheritance trees.

So yeah, definitely overkill for a standard 2-DB setup, mainly built for Apartment-style multi-tenant + read-replica/dynamic-shard setups moving onto Rails 8

2

u/KevinSaison 2d ago

Thanks for the detailed explanation.