Skip to content

About

Rails 8-first database sharding and read-replica routing with optional, fail-closed multi-tenant isolation (PostgreSQL, MySQL/Trilogy, SQLite3).

Resources

Stars

1 star

Watchers

1 watching

Forks

Repository files navigation

SchemaShard

Gem Version License: MIT Rails 8.0+

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')
end

Why schema_shard vs. Native ActiveRecord::Base.connected_to?

  • Dynamic, Config-Driven Shards: Load and reload shards dynamically from config/shards.yml (or a runtime Proc) without hardcoding static connects_to shard 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 silent public schema fallbacks.

Contents

Features

  • Multi-Database by Design: Auto-detects the database engine per shard from adapter: in config/shards.yml:
    • PostgreSQL (postgresql, postgis): ros-apartment or zero-dependency native search_path switching, default_transaction_read_only = on, and fail-closed PG::PQTRANS_IDLE verification.
    • MySQL / MariaDB (mysql2, trilogy): ros-apartment or native USE \tenant_db`switching,transaction_read_only = 1`, and open-transaction checks.
    • SQLite3 (sqlite3): Shard-only routing or per-tenant .sqlite3 file templates (storage/tenants/%{tenant}.sqlite3) backed by LRU pool eviction and PRAGMA query_only = ON.
    • Generic / Custom: Register custom database or tenant adapters via SchemaShard::DatabaseAdapters.register.
  • Flexible Tenant Modes:
    • :strict (default) — Fail-closed. nil, blank, system schemas (pg_*, information_schema), or accidental public fallback raise SchemaShard::InvalidTenantError.
    • :optional — nil tenant 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 of tenant_mode.
  • Dual-Layer Read-Only Protection: Combines ActiveRecord::Base.while_preventing_writes in 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 & :fiber safe), HashConfig/PoolConfig, Railtie lazy loading, Rails Executor cleanup, and Ruby 3.1+ Process._fork safety.
  • 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:install

Usage

Multi-Tenant + Shard Routing (PostgreSQL, MySQL, SQLite)

SchemaShard.with('acme_corp', shard_key: 'replica_1') do
  Order.where(status: 'paid').count
end

Shard-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
end

Explicit Default (public) Schema Access

SchemaShard.with_public(shard_key: 'replica_1') do
  Account.count
end

Writable Shards

SchemaShard.on_shard('write_shard_2', read_only: false) do
  AuditLog.create!(event: 'synced')
end

Sidekiq & Puma Integration

# config/initializers/sidekiq.rb
Sidekiq.configure_server do |config|
  config.server_middleware do |chain|
    chain.add SchemaShard::Middleware::Sidekiq
  end
end

In 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!
end

Observability (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 descriptors

Configuration

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?
end

How ConfigLoader & PoolRegistry Resolve Shard Entries

  • No inheritance from config/database.yml: Shard entries do not inherit host, username, password, pool, or any other settings from Rails's primary config/database.yml. Every shard entry is isolated to config/shards.yml (plus the SchemaShard.configuration fallbacks below) so shard routing can never accidentally fall back to your primary database.
  • ERB & YAML anchors: config/shards.yml is evaluated through ERB and parsed with YAML.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 matching Rails.env (falling back to config.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:), set config.config_root_key = 'shards' (shards → <env> → <shard_key>).
    • Instead of a YAML file, you can assign a Ruby Hash (or a Proc returning a Hash) with the same <env> → <shard_key> structure to config.shards.
  • url: expansion & overrides: When a shard defines url:, SchemaShard expands it via Rails's ActiveRecord::DatabaseConfigurations::ConnectionUrlResolver and merges any explicit sibling keys on top (for example, url: for credentials plus explicit pool: 10 or sslrootcert:).
  • Active Record passthrough vs. gem-managed options: SchemaShard validates the required connection locator (url or host + database, depending on adapter), applies pool defaults and read-only session settings, builds an ActiveRecord::DatabaseConfigurations::HashConfig, and hands the hash to ActiveRecord::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, and encoding.

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: require

PostgreSQL-Specific Notes

  • Use username, not user: Active Record's PostgreSQLAdapter (and SchemaShard's pool-identity digest) reads username and maps it to libpq's user parameter internally.
  • SSL options (Active Record / pg passthrough): sslmode (disable, allow, prefer, require, verify-ca, verify-full), sslrootcert, sslcert, and sslkey are passed straight through to PostgreSQLAdapter / libpq and tracked in the pool identity digest.
  • Session & adapter options (passthrough): Standard PostgreSQLAdapter options such as prepared_statements, advisory_locks, schema_search_path, connect_timeout, and variables are forwarded to Active Record. When read_only: true (the default), SchemaShard automatically sets variables.default_transaction_read_only = 'on' while preserving any other entries in variables (such as statement_timeout).
  • Tenant schema isolation: Switches search_path to "<tenant>" (plus persistent_schemas) via ros-apartment or native SET search_path, rejects pg_* and information_schema, and verifies PG::PQTRANS_IDLE before returning connections to the pool.
  • PostGIS (adapter: postgis): postgis is registered to the built-in PostgreSQL adapter. Add your PostGIS extension schema to config.persistent_schemas = %w[postgis] (or Apartment.persistent_schemas when using ros-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: false

MySQL / MariaDB-Specific Notes

  • Driver recommendation on MySQL 8.0: Prefer trilogy >= 2.12.0 on MySQL 8.0 so SchemaShard can inspect live Trilogy::Result#in_transaction? protocol flags for raw SQL BEGIN statements. mysql2 0.5.x on MySQL 8.0 (like trilogy < 2.12.0) only detects Active Record-managed transactions (open_transactions > 0). MariaDB automatically falls back to SELECT @@in_transaction on both drivers.
  • database: is the default namespace: Native tenant switching executes USE `<tenant>` on the connection and restores USE `<database>` on exit (rejecting mysql, information_schema, performance_schema, and sys). If you configure url:, 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 TrilogyAdapter expects ssl_mode (e.g. disabled, preferred, required, verify_ca, verify_identity) plus sslca / sslcert / sslkey, whereas Mysql2Adapter accepts ssl_mode / sslmode plus sslca / sslcert / sslkey. Both ssl_mode and sslmode are tracked in SchemaShard'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}.sqlite3

SQLite-Specific Notes

  • Shared vs. %{tenant} template (fail-closed): Calling SchemaShard.with('acme_corp', shard_key: 'analytics_sqlite') on a SQLite shard without %{tenant} in database or url raises SchemaShard::ConfigurationError rather than running tenant queries against a shared file. Use SchemaShard.on_shard for 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 by config.max_pools and config.cleanup_threshold. Prefer absolute paths (via Rails.root.join(...) in ERB) so file resolution never depends on the process working directory.
  • Read-only & busy timeout: SchemaShard executes PRAGMA query_only = ON (or OFF when read_only: false) on every checkout. Active Record SQLite options such as timeout (busy timeout in milliseconds) and pragmas pass directly through to SQLite3Adapter.

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: Generic works immediately with SchemaShard.on_shard (or config.tenant_mode = :none) for routing queries to secondary databases or replicas on other Active Record adapters.
  • Fail-closed on .with(tenant): Because Generic cannot assume how an unknown engine isolates tenants, calling SchemaShard.with(tenant) raises SchemaShard::ConfigurationError unless you register a custom subclass of SchemaShard::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.yml and version control. Supply them at runtime through your platform's secret store or process environment (Kubernetes Secrets, AWS SSM / Secrets Manager, Docker/Kamal env, systemd EnvironmentFile, or an untracked .env in local development) so both Puma and background workers (Sidekiq / SolidQueue) inherit them.
  • Prefer ENV.fetch('VAR') in deployed environments: Note that bin/rails generate schema_shard:install scaffolds ENV['SHARD01_DATABASE_URL'] in production so 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 blank url:.
  • Redacted pool identifiers & logs: PoolRegistry hashes password with 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: true enforces both ActiveRecord::Base.while_preventing_writes and 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 granted SELECT-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')
end

If 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: Omitting host or username because they exist in database.yml — shard entries are completely independent (use YAML &default anchors inside shards.yml to share settings across shards).
  • Writing user: instead of username:: Active Record adapters and SchemaShard expect username:; user: is ignored.
  • Blank ENV['...'] URL in production: If url: <%= ENV['SHARD01_DATABASE_URL'] %> evaluates to nil and neither host nor database is set, ConfigLoader raises ArgumentError: Shard '...' must explicitly configure either 'url' or both 'host' and 'database'.
  • Unix socket without host or url: On PostgreSQL and MySQL, validate_config! requires url or host + database. For local Unix sockets, pass the socket directory as host: /var/run/postgresql (PostgreSQL) or include host: localhost alongside socket: (MySQL), or use a url:.
  • Environment or config_root_key mismatch: Raising Environment '<env>' not found usually means config/shards.yml is missing a block for the current Rails.env (for example staging:), or wraps environments under a top-level key without matching config.config_root_key.
  • Connection math across processes: Total connections to a database equal (web + worker processes) × pool (and up to max_pools distinct pools per process when using per-tenant SQLite or many shards, plus separate :reading and :writing pools if a shard is called with both read_only: true and read_only: false). Size pool and max_pools within your database's max_connections budget (or place PgBouncer in front of PostgreSQL shards).

Production Notes

  • Read-Only Defense in Depth: read_only: true applies both ActiveRecord::Base.while_preventing_writes (which prevents writes thread-wide for the duration of the block, including excluded_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 (trilogy vs mysql2): trilogy >= 2.12.0 is strongly recommended on MySQL 8.0 for live Trilogy::Result#in_transaction? protocol inspection of raw SQL BEGIN transactions; mysql2 0.5.x on MySQL 8.0 (like trilogy < 2.12.0) only detects ActiveRecord-managed transactions (open_transactions > 0). MariaDB automatically falls back to SELECT @@in_transaction on both drivers.
  • Fast-Path Live Verification: Set config.live_verify_fast_path = true if application code mutates search_path or USE via raw SQL outside SchemaShard.with. Avoid wrapping a nested SchemaShard.with inside an out-of-band Apartment::Tenant.switch call.
  • Metrics Cardinality: Per-shard metrics are bounded by config.max_tracked_shards (default 100, bucketing overflow into _other). Call SchemaShard.reset_metrics! if you rotate dynamic shard keys.
  • Rails 8 Relation#load_async: Do not call .load_async inside SchemaShard.with or SchemaShard.on_shard blocks; ActiveRecord's background async executor runs on separate worker threads that do not inherit the caller's ExecutionContext or tenant search_path / USE session state.
  • PostgreSQL $user Role Naming: PostgreSQL's built-in "$user, public" search_path is treated as equivalent to "public" when persistent_schemas is empty; ensure your database connection role name never matches a tenant schema name.
  • ros-apartment Persistent Schemas: When using ros-apartment, configure persistent schemas via Apartment.persistent_schemas and leave SchemaShard.configuration.persistent_schemas empty (or identical) so fast-path namespace checks match Apartment::Tenant.switch.
  • Fiber Concurrency (Falcon / Async): Set config.active_support.isolation_level = :fiber in Rails 8 so ActiveSupport::IsolatedExecutionState isolates shard context per Fiber.
  • Standalone / Non-Rails Apps: Call SchemaShard.install! once at boot to prepend SchemaShard::ConnectionPatch onto ActiveRecord::Base, and call SchemaShard.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.gemspec

License

The gem is available as open source under the terms of the MIT License.

About

Rails 8-first database sharding and read-replica routing with optional, fail-closed multi-tenant isolation (PostgreSQL, MySQL/Trilogy, SQLite3).

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages