SchemaShard
Rails 8-first database sharding and read-replica routing with optional, fail-closed multi-tenant isolation.
schema_shard gives Rails 8+ applications dynamic, LRU-managed shard and read-replica connection pooling across PostgreSQL, MySQL / MariaDB (mysql2 & trilogy), SQLite3, and custom ActiveRecord adapters — with flexible tenant isolation (ros-apartment, native DB switching, or pure shard-only routing).
# Route tenant queries to a read-only replica with fail-closed isolation
SchemaShard.with('acme_corp', shard_key: 'replica_1') do
Order.where(status: 'paid').count
end
# Route writes directly to a dedicated shard without tenant switching
SchemaShard.on_shard('write_shard_2', read_only: false) do
AuditLog.create!(event: 'synced')
endWhy schema_shard vs. Native ActiveRecord::Base.connected_to?
-
Dynamic, Config-Driven Shards: Load and reload shards dynamically from
config/shards.yml(or a runtimeProc) without hardcoding staticconnects_toshard maps on model classes at boot. -
Bounded LRU Pool Lifecycle: Enforce process-wide pool limits (
max_pools) with atomic Dekker-style refcounting so hundreds of shards or per-tenant databases never exhaust database connections. -
Fail-Closed Multi-Tenant Isolation: Combine shard/replica routing with verified tenant switching (
search_path,USE, or%{tenant}SQLite files) that blocks cross-tenant leaks, open-transaction switches, and silentpublicschema fallbacks.
Contents
- Features
- Installation
- Usage
- Configuration
- Shared Setup
- PostgreSQL
- MySQL / MariaDB
- SQLite3
- Generic & Custom Adapters
- Security Practices
- Validation & Common Mistakes
- Production Notes
- Development
- License
Features
-
Multi-Database by Design: Auto-detects the database engine per shard from
adapter:inconfig/shards.yml:-
PostgreSQL (
postgresql,postgis):ros-apartmentor zero-dependency nativesearch_pathswitching,default_transaction_read_only = on, and fail-closedPG::PQTRANS_IDLEverification. -
MySQL / MariaDB (
mysql2,trilogy):ros-apartmentor nativeUSE \tenant_db`switching,transaction_read_only = 1`, and open-transaction checks. -
SQLite3 (
sqlite3): Shard-only routing or per-tenant.sqlite3file templates (storage/tenants/%{tenant}.sqlite3) backed by LRU pool eviction andPRAGMA query_only = ON. -
Generic / Custom: Register custom database or tenant adapters via
SchemaShard::DatabaseAdapters.register.
-
PostgreSQL (
-
Flexible Tenant Modes:
-
:strict(default) — Fail-closed.nil, blank, system schemas (pg_*,information_schema), or accidentalpublicfallback raiseSchemaShard::InvalidTenantError. -
:optional—niltenant gracefully falls back to the shard's default schema/database. -
:none— Pure database sharding / read-replica routing with zero tenant switching. -
SchemaShard.on_shard('shard01')— Explicit shard-only routing regardless oftenant_mode.
-
-
Dual-Layer Read-Only Protection: Combines
ActiveRecord::Base.while_preventing_writesin Ruby with DB-level read-only session settings. -
Race-Free LRU Pool Lifecycle: Atomic Dekker-style refcounting (
PoolEntry) prevents races between active queries and concurrent pool eviction. -
Rails 8 Native: Uses
ActiveSupport::IsolatedExecutionState(:thread&:fibersafe),HashConfig/PoolConfig, Railtie lazy loading, Rails Executor cleanup, and Ruby 3.1+Process._forksafety. - Observability Out-of-the-Box: Lock-free counters with built-in Prometheus and StatsD formatters plus an opt-in SQL query logger.
Installation
Add to your Gemfile:
gem 'schema_shard'Install and generate the initializer and config/shards.yml template:
bundle install
bin/rails generate schema_shard:installUsage
Multi-Tenant + Shard Routing (PostgreSQL, MySQL, SQLite)
SchemaShard.with('acme_corp', shard_key: 'replica_1') do
Order.where(status: 'paid').count
endShard-Only Routing (No Schema/Tenant Selection)
# Uses the shard's default schema/database regardless of tenant_mode
SchemaShard.on_shard('replica_1') do
Order.where(status: 'paid').count
endExplicit Default (public) Schema Access
SchemaShard.with_public(shard_key: 'replica_1') do
Account.count
endWritable Shards
SchemaShard.on_shard('write_shard_2', read_only: false) do
AuditLog.create!(event: 'synced')
endSidekiq & Puma Integration
# config/initializers/sidekiq.rb
Sidekiq.configure_server do |config|
config.server_middleware do |chain|
chain.add SchemaShard::Middleware::Sidekiq
end
endIn Rails apps, fork safety is enabled automatically on Ruby 3.1+ via Process._fork (when config.auto_fork_safety = true). Standalone / non-Rails apps can call SchemaShard.install_fork_hook! at boot, or you can call SchemaShard.discard_pools_after_fork! explicitly in config/puma.rb:
on_worker_boot do
SchemaShard.discard_pools_after_fork!
endObservability (Prometheus & StatsD)
SchemaShard.metrics # => Hash snapshot (global, per_shard, pools, timestamp)
SchemaShard.prometheus_metrics # => Prometheus text exposition format
SchemaShard.statsd_metrics # => Array of StatsD/DogStatsD gauge descriptorsConfiguration
1. Shared Setup & How config/shards.yml Is Loaded
Configure global behavior in config/initializers/schema_shard.rb (generated by bin/rails generate schema_shard:install):
# config/initializers/schema_shard.rb
SchemaShard.configure do |config|
config.config_path = Rails.root.join('config', 'shards.yml')
config.config_root_key = nil # optional top-level YAML key (see structure below)
config.default_shard = 'replica_1' # scaffolded as 'shard01' by schema_shard:install
# :auto (Apartment on PostgreSQL if loaded, else :native), :apartment, :native, :none, or custom adapter
config.tenant_adapter = :auto
# :strict (fail-closed), :optional (fallback to default), or :none (shard-only)
config.tenant_mode = :strict
# Models that must never be routed to a shard connection
config.excluded_models = %w[Account]
config.default_schema = 'public'
# Native PostgreSQL persistent schemas (leave [] when using ros-apartment; set Apartment.persistent_schemas instead)
config.persistent_schemas = %w[shared_extensions]
# Default per-pool connection settings when omitted on an individual shard in shards.yml
config.default_pool_size = ENV.fetch('RAILS_MAX_THREADS', 5).to_i
config.checkout_timeout = 5
config.reaping_frequency = 10
# Process-wide LRU pool registry limits
config.max_pools = ENV.fetch('SCHEMA_SHARD_MAX_POOLS', 10).to_i
config.cleanup_threshold = ENV.fetch('SCHEMA_SHARD_CLEANUP_THRESHOLD', 8).to_i
config.log_shard_queries = Rails.env.development?
endHow ConfigLoader & PoolRegistry Resolve Shard Entries
-
No inheritance from
config/database.yml: Shard entries do not inherithost,username,password,pool, or any other settings from Rails's primaryconfig/database.yml. Every shard entry is isolated toconfig/shards.yml(plus theSchemaShard.configurationfallbacks below) so shard routing can never accidentally fall back to your primary database. -
ERB & YAML anchors:
config/shards.ymlis evaluated throughERBand parsed withYAML.safe_load(..., aliases: true), so<%= ENV.fetch(...) %>and YAML anchors (default: &default/<<: *default) work just like in Rails config files. -
Environment & optional root key:
- By default (
config.config_root_key = nil), top-level keys are environment names matchingRails.env(falling back toconfig.env,ENV['RAILS_ENV'],ENV['RACK_ENV'], or'development'), and second-level keys are your shard names (replica_1,write_shard_2, etc.). - If your YAML nests environments under a wrapper key (for example
shards:), setconfig.config_root_key = 'shards'(shards→<env>→<shard_key>). - Instead of a YAML file, you can assign a Ruby
Hash(or aProcreturning aHash) with the same<env>→<shard_key>structure toconfig.shards.
- By default (
-
url:expansion & overrides: When a shard definesurl:,SchemaShardexpands it via Rails'sActiveRecord::DatabaseConfigurations::ConnectionUrlResolverand merges any explicit sibling keys on top (for example,url:for credentials plus explicitpool: 10orsslrootcert:). -
Active Record passthrough vs. gem-managed options:
SchemaShardvalidates the required connection locator (urlorhost+database, depending on adapter), applies pool defaults and read-only session settings, builds anActiveRecord::DatabaseConfigurations::HashConfig, and hands the hash toActiveRecord::ConnectionAdapters::ConnectionPool. Additional adapter options supported by your Active Record driver (such as SSL parameters,variables,prepared_statements, or driver timeouts) are passed directly through to Active Record.- Pool deduplication hashes
shard_key,read_only,password(SHA-256), and these recognized connection keys:adapter,host,port,socket,database,username,url,sslmode,ssl_mode,sslrootcert,sslcert,sslkey,variables,pragmas,schema_search_path,prepared_statements,advisory_locks,pool,checkout_timeout,timeout,reaping_frequency, andencoding.
- Pool deduplication hashes
Shared Shard Settings Reference
| Key | Required? | Default (when omitted) | Handled by | What it controls |
|---|---|---|---|---|
adapter |
Recommended |
'postgresql' (or inferred from url: scheme) |
SchemaShard & Active Record |
Selects both the SchemaShard::DatabaseAdapters strategy and the Active Record connection adapter (postgresql, postgis, trilogy, mysql2, sqlite3, or custom). |
url |
Either url or host + database (SQLite/Generic: url or database) |
— |
SchemaShard (ConnectionUrlResolver) |
Full connection URI (e.g., postgres://..., trilogy://..., sqlite3://...). Explicit sibling keys override values parsed from url. |
host |
Required on PG & MySQL when url is omitted |
— |
SchemaShard & Active Record |
Database hostname, IP, or (on PostgreSQL) absolute Unix socket directory path. |
port |
Optional | Driver default (5432 PG, 3306 MySQL) |
Active Record / driver | TCP port of the database server. |
database |
Required when url is omitted |
— |
SchemaShard & Active Record |
Database name (or file path / %{tenant} template on SQLite3). On MySQL, also acts as the shard's default namespace. |
username |
Optional | Driver default (OS user / root) |
Active Record / driver | Database login role. Always use username (Active Record's key), not user. |
password |
Optional | nil |
Active Record / driver | Database password. Interpolate from ENV rather than committing plaintext. |
pool |
Optional |
config.default_pool_size (RAILS_MAX_THREADS or 5, min 1) |
SchemaShard & Active Record |
Max concurrent connections per Ruby process in this shard pool. Note that read-only (read_only: true) and writable (read_only: false) calls on the same shard maintain separate pools. |
checkout_timeout |
Optional |
config.checkout_timeout (5 seconds) |
SchemaShard & Active Record |
Seconds a thread waits for a free connection from the shard pool before raising ActiveRecord::ConnectionTimeoutError. |
reaping_frequency |
Optional |
config.reaping_frequency (10 seconds) |
SchemaShard & Active Record |
Interval in seconds at which Active Record's ConnectionPool::Reaper reclaims dead connections. |
encoding |
Optional |
'unicode' (PG), 'utf8mb4' (MySQL), unset (SQLite) |
SchemaShard & Active Record |
Client character encoding passed to Active Record. |
variables |
Optional | Merged with read-only flag when read_only: true
|
SchemaShard & Active Record |
Session variables set on new connections. On read-only pools, SchemaShard merges default_transaction_read_only: 'on' (PG) or transaction_read_only: 1 (MySQL) onto any custom variables hash. |
2. PostgreSQL (postgresql, postgis)
Add gem 'pg' to your application's Gemfile (schema_shard does not force-install database drivers).
A PostgreSQL shard requires either url or both host and database; all other keys are optional:
# config/shards.yml
default: &default
adapter: postgresql
encoding: unicode
pool: <%= ENV.fetch('RAILS_MAX_THREADS', 5) %>
checkout_timeout: 5
reaping_frequency: 10
development:
replica_1:
<<: *default
host: <%= ENV.fetch('REPLICA_1_DB_HOST', 'localhost') %>
port: <%= ENV.fetch('REPLICA_1_DB_PORT', 5432) %>
database: <%= ENV.fetch('REPLICA_1_DB_NAME', 'app_development') %>
username: <%= ENV.fetch('REPLICA_1_DB_USERNAME', 'postgres') %>
password: <%= ENV.fetch('REPLICA_1_DB_PASSWORD', '') %>
write_shard_2:
<<: *default
host: <%= ENV.fetch('WRITE_SHARD_2_DB_HOST', 'localhost') %>
port: <%= ENV.fetch('WRITE_SHARD_2_DB_PORT', 5432) %>
database: <%= ENV.fetch('WRITE_SHARD_2_DB_NAME', 'app_shard2_development') %>
username: <%= ENV.fetch('WRITE_SHARD_2_DB_USERNAME', 'postgres') %>
password: <%= ENV.fetch('WRITE_SHARD_2_DB_PASSWORD', '') %>
production:
# Option A: Discrete connection keys + libpq SSL verification
replica_1:
<<: *default
host: <%= ENV.fetch('REPLICA_1_DB_HOST') %>
port: <%= ENV.fetch('REPLICA_1_DB_PORT', 5432) %>
database: <%= ENV.fetch('REPLICA_1_DB_NAME') %>
username: <%= ENV.fetch('REPLICA_1_DB_USERNAME') %>
password: <%= ENV.fetch('REPLICA_1_DB_PASSWORD') %>
sslmode: verify-full
sslrootcert: <%= ENV.fetch('DB_SSL_ROOT_CERT', '/etc/ssl/certs/rds-ca.pem') %>
variables:
statement_timeout: 5000
# Option B: Connection URL with explicit pool/SSL overrides
write_shard_2:
<<: *default
url: <%= ENV.fetch('WRITE_SHARD_2_DATABASE_URL') %>
pool: <%= ENV.fetch('WRITE_SHARD_2_POOL', 10) %>
sslmode: requirePostgreSQL-Specific Notes
-
Use
username, notuser: Active Record'sPostgreSQLAdapter(andSchemaShard's pool-identity digest) readsusernameand maps it tolibpq'suserparameter internally. -
SSL options (Active Record /
pgpassthrough):sslmode(disable,allow,prefer,require,verify-ca,verify-full),sslrootcert,sslcert, andsslkeyare passed straight through toPostgreSQLAdapter/libpqand tracked in the pool identity digest. -
Session & adapter options (passthrough): Standard
PostgreSQLAdapteroptions such asprepared_statements,advisory_locks,schema_search_path,connect_timeout, andvariablesare forwarded to Active Record. Whenread_only: true(the default),SchemaShardautomatically setsvariables.default_transaction_read_only = 'on'while preserving any other entries invariables(such asstatement_timeout). -
Tenant schema isolation: Switches
search_pathto"<tenant>"(pluspersistent_schemas) viaros-apartmentor nativeSET search_path, rejectspg_*andinformation_schema, and verifiesPG::PQTRANS_IDLEbefore returning connections to the pool. -
PostGIS (
adapter: postgis):postgisis registered to the built-in PostgreSQL adapter. Add your PostGIS extension schema toconfig.persistent_schemas = %w[postgis](orApartment.persistent_schemaswhen usingros-apartment).
3. MySQL / MariaDB (trilogy, mysql2)
Both Rails 8's default trilogy driver (gem 'trilogy') and mysql2 (gem 'mysql2') are supported. Each shard requires either url or both host and database (default encoding is 'utf8mb4'):
# config/shards.yml
production:
mysql_replica:
adapter: trilogy # or: mysql2
host: <%= ENV.fetch('MYSQL_REPLICA_HOST') %>
port: <%= ENV.fetch('MYSQL_REPLICA_PORT', 3306) %>
database: <%= ENV.fetch('MYSQL_REPLICA_DB') %>
username: <%= ENV.fetch('MYSQL_REPLICA_USERNAME') %>
password: <%= ENV.fetch('MYSQL_REPLICA_PASSWORD') %>
pool: <%= ENV.fetch('RAILS_MAX_THREADS', 5) %>
checkout_timeout: 5
ssl_mode: verify_identity # Active Record TrilogyAdapter SSL option
prepared_statements: falseMySQL / MariaDB-Specific Notes
-
Driver recommendation on MySQL 8.0: Prefer
trilogy >= 2.12.0on MySQL 8.0 soSchemaShardcan inspect liveTrilogy::Result#in_transaction?protocol flags for raw SQLBEGINstatements.mysql20.5.x on MySQL 8.0 (liketrilogy < 2.12.0) only detects Active Record-managed transactions (open_transactions > 0). MariaDB automatically falls back toSELECT @@in_transactionon both drivers. -
database:is the default namespace: Native tenant switching executesUSE `<tenant>`on the connection and restoresUSE `<database>`on exit (rejectingmysql,information_schema,performance_schema, andsys). If you configureurl:, ensure the URL path includes the default database name (trilogy://user:pass@host:3306/app_production). -
SSL key names depend on the driver (passthrough): Active Record's
TrilogyAdapterexpectsssl_mode(e.g.disabled,preferred,required,verify_ca,verify_identity) plussslca/sslcert/sslkey, whereasMysql2Adapteracceptsssl_mode/sslmodeplussslca/sslcert/sslkey. Bothssl_modeandsslmodeare tracked inSchemaShard's pool identity digest. -
Read-only session flag: Read-only pools automatically inject
variables.transaction_read_only = 1.
4. SQLite3 (sqlite3)
Add gem 'sqlite3', '>= 2.0' to your Gemfile. SQLite shards require either database or url (host is not required) and support two distinct modes:
# config/shards.yml
production:
# 1. Shared single-file shard (use with SchemaShard.on_shard or tenant_mode: :none)
analytics_sqlite:
adapter: sqlite3
database: <%= Rails.root.join('storage', 'analytics_replica.sqlite3') %>
pool: 5
timeout: 5000
# 2. Per-tenant database file template (use with SchemaShard.with(tenant, shard_key: 'sqlite_tenants'))
sqlite_tenants:
adapter: sqlite3
database: <%= Rails.root.join('storage', 'tenants', '%{tenant}.sqlite3') %>
pool: 2
timeout: 5000
# URL templates are also supported:
# url: sqlite3://<%= Rails.root.join('storage', 'tenants') %>/tenant_%{tenant}.sqlite3SQLite-Specific Notes
-
Shared vs.
%{tenant}template (fail-closed): CallingSchemaShard.with('acme_corp', shard_key: 'analytics_sqlite')on a SQLite shard without%{tenant}indatabaseorurlraisesSchemaShard::ConfigurationErrorrather than running tenant queries against a shared file. UseSchemaShard.on_shardfor shared SQLite shards. -
Path traversal & LRU pooling:
%{tenant}templates validate tenant names against\A[a-zA-Z0-9][a-zA-Z0-9_-]{0,62}\z(blocking../traversal) and allocate one LRU-managed pool per tenant bounded byconfig.max_poolsandconfig.cleanup_threshold. Prefer absolute paths (viaRails.root.join(...)in ERB) so file resolution never depends on the process working directory. -
Read-only & busy timeout:
SchemaShardexecutesPRAGMA query_only = ON(orOFFwhenread_only: false) on every checkout. Active Record SQLite options such astimeout(busy timeout in milliseconds) andpragmaspass directly through toSQLite3Adapter.
5. Generic & Custom Adapters
Any adapter: name other than postgresql, postgis, trilogy, mysql2, or sqlite3 resolves to SchemaShard::DatabaseAdapters::Generic (requiring database or url):
-
Out-of-the-box shard-only routing:
Genericworks immediately withSchemaShard.on_shard(orconfig.tenant_mode = :none) for routing queries to secondary databases or replicas on other Active Record adapters. -
Fail-closed on
.with(tenant): BecauseGenericcannot assume how an unknown engine isolates tenants, callingSchemaShard.with(tenant)raisesSchemaShard::ConfigurationErrorunless you register a custom subclass ofSchemaShard::DatabaseAdapters::Base:
# config/initializers/schema_shard.rb
SchemaShard::DatabaseAdapters.register('cockroachdb', SchemaShard::DatabaseAdapters::Postgresql.instance)6. Environment Variables, Credentials & Security Practices
-
Never commit credentials: Keep passwords, connection URLs, and private keys out of
config/shards.ymland version control. Supply them at runtime through your platform's secret store or process environment (Kubernetes Secrets, AWS SSM / Secrets Manager, Docker/Kamal env,systemdEnvironmentFile, or an untracked.envin local development) so both Puma and background workers (Sidekiq / SolidQueue) inherit them. -
Prefer
ENV.fetch('VAR')in deployed environments: Note thatbin/rails generate schema_shard:installscaffoldsENV['SHARD01_DATABASE_URL']inproductionso a freshly generated app can boot before shards are provisioned. Once deployed, switch required production variables to<%= ENV.fetch('REPLICA_1_DB_PASSWORD') %>(or<%= ENV.fetch('WRITE_SHARD_2_DATABASE_URL') %>) so a missing secret fails immediately with the variable name instead of silently producing a blankurl:. -
Redacted pool identifiers & logs:
PoolRegistryhashespasswordwith SHA-256 and truncates the composite configuration digest (replica_1_9f86d081884c7d65), so plaintext hosts and passwords never appear in pool keys, logs, or Prometheus/StatsD labels. -
Database-level least privilege:
read_only: trueenforces bothActiveRecord::Base.while_preventing_writesand session-level read-only variables (default_transaction_read_only = on/transaction_read_only = 1/PRAGMA query_only = ON), and production read replicas should still connect with a database role grantedSELECT-only privileges.
7. Validating a Configuration & Common Setup Mistakes
You can verify config/shards.yml syntax, required keys, and live connectivity from bin/rails console or a deploy health check:
# 1. Validate ERB, YAML nesting, URL parsing, and adapter-required keys (no DB socket opened)
SchemaShard.config_loader.fetch!('replica_1')
# 2. Verify live connectivity, SSL, credentials, and read-only session setup
SchemaShard.on_shard('replica_1') do
ActiveRecord::Base.connection.select_value('SELECT 1')
endIf you rotate credentials or edit config/shards.yml at runtime, call SchemaShard.reload_config! to clear the cached config and retire unused pools while letting in-flight queries finish safely.
Common Setup Mistakes
-
Expecting fallback to
config/database.yml: Omittinghostorusernamebecause they exist indatabase.yml— shard entries are completely independent (use YAML&defaultanchors insideshards.ymlto share settings across shards). -
Writing
user:instead ofusername:: Active Record adapters andSchemaShardexpectusername:;user:is ignored. -
Blank
ENV['...']URL in production: Ifurl: <%= ENV['SHARD01_DATABASE_URL'] %>evaluates toniland neitherhostnordatabaseis set,ConfigLoaderraisesArgumentError: Shard '...' must explicitly configure either 'url' or both 'host' and 'database'. -
Unix socket without
hostorurl: On PostgreSQL and MySQL,validate_config!requiresurlorhost+database. For local Unix sockets, pass the socket directory ashost: /var/run/postgresql(PostgreSQL) or includehost: localhostalongsidesocket:(MySQL), or use aurl:. -
Environment or
config_root_keymismatch: RaisingEnvironment '<env>' not foundusually meansconfig/shards.ymlis missing a block for the currentRails.env(for examplestaging:), or wraps environments under a top-level key without matchingconfig.config_root_key. -
Connection math across processes: Total connections to a database equal
(web + worker processes) × pool(and up tomax_poolsdistinct pools per process when using per-tenant SQLite or many shards, plus separate:readingand:writingpools if a shard is called with bothread_only: trueandread_only: false). Sizepoolandmax_poolswithin your database'smax_connectionsbudget (or place PgBouncer in front of PostgreSQL shards).
Production Notes
-
Read-Only Defense in Depth:
read_only: trueapplies bothActiveRecord::Base.while_preventing_writes(which prevents writes thread-wide for the duration of the block, includingexcluded_models) and DB-level session read-only flags. In production, always back read replicas with a read-only database role/user as well. -
Open Transactions & Nested Switches: Nested different-tenant switches inside an open database transaction are rejected fail-closed (
SchemaShard::TaintedConnectionError), and the tainted pool frame blocks any further queries even if the error is rescued. -
MySQL 8 (
trilogyvsmysql2):trilogy >= 2.12.0is strongly recommended on MySQL 8.0 for liveTrilogy::Result#in_transaction?protocol inspection of raw SQLBEGINtransactions;mysql20.5.x on MySQL 8.0 (liketrilogy < 2.12.0) only detects ActiveRecord-managed transactions (open_transactions > 0). MariaDB automatically falls back toSELECT @@in_transactionon both drivers. -
Fast-Path Live Verification: Set
config.live_verify_fast_path = trueif application code mutatessearch_pathorUSEvia raw SQL outsideSchemaShard.with. Avoid wrapping a nestedSchemaShard.withinside an out-of-bandApartment::Tenant.switchcall. -
Metrics Cardinality: Per-shard metrics are bounded by
config.max_tracked_shards(default100, bucketing overflow into_other). CallSchemaShard.reset_metrics!if you rotate dynamic shard keys. -
Rails 8
Relation#load_async: Do not call.load_asyncinsideSchemaShard.withorSchemaShard.on_shardblocks; ActiveRecord's background async executor runs on separate worker threads that do not inherit the caller'sExecutionContextor tenantsearch_path/USEsession state. -
PostgreSQL
$userRole Naming: PostgreSQL's built-in"$user, public"search_pathis treated as equivalent to"public"whenpersistent_schemasis empty; ensure your database connection role name never matches a tenant schema name. -
ros-apartmentPersistent Schemas: When usingros-apartment, configure persistent schemas viaApartment.persistent_schemasand leaveSchemaShard.configuration.persistent_schemasempty (or identical) so fast-path namespace checks matchApartment::Tenant.switch. -
Fiber Concurrency (Falcon / Async): Set
config.active_support.isolation_level = :fiberin Rails 8 soActiveSupport::IsolatedExecutionStateisolates shard context per Fiber. -
Standalone / Non-Rails Apps: Call
SchemaShard.install!once at boot to prependSchemaShard::ConnectionPatchontoActiveRecord::Base, and callSchemaShard.install_fork_hook!if your process forks (in Rails, the Railtie installs both automatically).
Development
bundle install
bundle exec rspec
bundle exec rubocop
gem build schema_shard.gemspecLicense
The gem is available as open source under the terms of the MIT License.