Database multi-tenancy for Rack (and Rails) applications
Database multi-tenancy for Rack (and Rails) applications
Database-level multitenancy for Rails and ActiveRecord
Apartment isolates tenant data at the database level — using PostgreSQL schemas or separate databases — so that tenant data separation is enforced by the database engine, not application code.
Apartment::Tenant.switch('acme') do
User.all # only returns users in the 'acme' schema/database
endApartment uses schema-per-tenant (PostgreSQL) or database-per-tenant (MySQL/SQLite) isolation. This is one of several approaches to multitenancy in Rails. Choose the right one for your situation:
| Approach | Isolation | Best for | Gem |
|---|---|---|---|
Row-level (shared tables, WHERE tenant_id = ?) |
Application-enforced | Many tenants, greenfield apps, cross-tenant reporting | acts_as_tenant |
| Schema-level (PostgreSQL schemas) | Database-enforced | Fewer high-value tenants, regulatory requirements, retrofitting existing apps | ros-apartment |
| Database-level (separate databases) | Full isolation | Strictest isolation, per-tenant performance tuning | ros-apartment |
Use Apartment when you need hard data isolation between tenants — where a missed WHERE clause can't accidentally leak data across tenants. This is common in regulated industries, B2B SaaS with contractual isolation requirements, or when retrofitting an existing single-tenant app.
Consider row-level tenancy instead if you have many tenants (hundreds+), need cross-tenant queries, or are starting a greenfield project. Row-level is simpler, uses fewer database resources, and scales more linearly. See the Arkency comparison for a thorough analysis.
This gem is a maintained fork of the original Apartment gem. Maintained by CampusESP since 2024. Same require 'apartment'; v4 introduces a pool-per-tenant architecture that replaces the thread-local switching of v3. Tenant context is fiber-safe via CurrentAttributes, and connection pools are managed per tenant rather than swapping search paths on a shared connection. For why v4 chose this model over the alternatives (including fully-qualified table names), see docs/designs/v4-connection-model-rationale.md. See the upgrade guide for migration steps from v3.
.ruby-version is the single source of truth for the local Ruby version (the
same file ruby/setup-ruby reads in CI). Both mise and
rbenv honor it — use whichever you prefer:
# mise (recommended)
brew install mise # then add `eval "$(mise activate zsh)"` to ~/.zshrc
mise trust && mise install # one-time trust per clone, then install the pinned Ruby
# rbenv (also works, unchanged)
rbenv install "$(cat .ruby-version)"The committed mise.toml carries settings only (never a version): it tells mise
to honor .ruby-version without any per-developer global config. mise trust
is required once per clone; bin/dev/setup-worktree handles it for new worktrees.
# Gemfile
gem 'ros-apartment', require: 'apartment'bundle install
bundle exec rails generate apartment:installThe generated initializer at config/initializers/apartment.rb configures Apartment:
Apartment.configure do |config|
config.tenant_strategy = :schema # :schema (PostgreSQL) or :database_name (MySQL/SQLite)
config.tenants_provider = -> { Customer.pluck(:subdomain) }
config.default_tenant = 'public' # auto-defaults for :schema; required for :database_name
endTenant context is block-scoped. Always use Apartment::Tenant.switch with a block in application code; it guarantees cleanup on exceptions.
Apartment::Tenant.create('acme')
Apartment::Tenant.switch('acme') do
User.create!(name: 'Alice') # in the 'acme' schema
end
Apartment::Tenant.drop('acme')switch! exists for console/REPL use but is discouraged in application code.
Global models that live outside tenant schemas use pin_tenant:
…ruby config.elevator = :subdomain config.elevator_options = {}
…ruby Apartment.configure do |config| config.ddl_role = :db_manager config.tenant_privilege_policy = Apartment::Privileges.standard(grant_to: 'app_user') end
…ruby Apartment.configure do |config| config.configure_postgres do |pg| pg.persistent_schemas = ['shared_extensions'] end end
PostgreSQL extensions (hstore, uuid-ossp, etc.) should be installed in a persistent schema so they're accessible from all tenant schemas:
```ruby
# lib/tasks/db_enhancements.rake
namespace :db do
task extensions: :environment do
ActiveRecord::Base.connection.execute('CREATE SCHEMA IF NOT EXISTS shared_extensions;')
ActiveRecord::Base.connection.execute('CREATE EXTENSION IF NOT EXISTS HSTORE SCHEMA shared_extensions;')
ActiveRecord::Base.connection.execute('CREATE EXTENSION IF NOT EXISTS "uuid-ossp" SCHEMA shared_extensions;')
end
end
Rake::Task['db:create'].enhance { Rake::Task['db:extensions'].invoke }
Rake::Task['db:test:purge'].enhance { Rake::Task['db:extensions'].invoke }Ensure your database.yml includes the persistent schema:
schema_search_path: "public,shared_extensions"Additional PostgreSQL options (set inside the configure_postgres block):
include_schemas_in_dump: non-public schemas to include in schema dumps, e.g., %w[ext shared] (default: []).
Apartment.configure do |config|
config.configure_mysql do |my|
# MySQL-specific options
end
endElevators are Rack middleware that detect the tenant from the incoming request and call Apartment::Tenant.switch for the duration of that request.
Available elevators:
acme.example.com -> 'acme'acme.com -> 'acme'{ 'acme.com' => 'acme_tenant' }Configuration via config.elevator:
Apartment.configure do |config|
config.elevator = :subdomain
endThe Railtie inserts the elevator after ActionDispatch::Callbacks automatically. In the full middleware stack this places it just before cookies, sessions, and authentication. In API mode (where cookies/sessions are absent), Callbacks is still present so the elevator works without changes.
If you need different positioning, skip config.elevator and insert manually:
# config/application.rb
config.middleware.insert_before 'Warden::Manager', Apartment::Elevators::Subdomainclass MyElevator [!WARNING]
> With the PostgreSQL `:schema` strategy, **PgBouncer in `transaction` pooling mode can
> silently serve one tenant another tenant's data.** No error is raised — queries return the
> wrong tenant's rows. It is safe only on **PostgreSQL 18+** with
> `track_extra_parameters = IntervalStyle,search_path`; on PostgreSQL 17 and older,
> transaction mode cannot be made safe and you must use `session` mode.
Tenant isolation under `:schema` rests on `search_path`, which is session-scoped state.
Transaction-mode pooling hands a different backend to each transaction, so a `search_path`
set by one client is not guaranteed to be the one in effect for the next query. This affects
v3 and v4 alike; v4 reduces the number of `SET search_path` statements to one per connection
but does not eliminate them, and one is enough.
**Which pooler to use:** PgBouncer on **PostgreSQL 18+** with
`track_extra_parameters = IntervalStyle,search_path` is the only setup that safely multiplexes
a schema-per-tenant app — and it needs no changes to Apartment or your application. **RDS Proxy
is safe but reduces no connections**: a Rails app pins on it *with or without Apartment* (three
unconditional `SET`s in `configure_connection`, plus the extended query protocol even at
`prepared_statements: false` — [rails/rails#40207](https://github.com/rails/rails/issues/40207)),
and AWS offers no session-pinning filters for PostgreSQL. Keep RDS Proxy if you use it for
failover or IAM; don't adopt it to cut connections.
Database-per-tenant (`:database_name`) is not affected.
**Read [Connection Poolers](docs/connection-poolers.md) before putting a pooler in front of a
schema-per-tenant app**, and verify your configuration rather than assuming it: the failure
is silent, so a working app proves nothing.
### `connects_to` with Separate Databases
If a model (or its abstract base class) uses `connects_to` to point at a completely different database (not just different roles on the same DB), Apartment's `connection_pool` patch will attempt to create a tenant pool for it.
Workaround: add `include Apartment::Model` and `pin_tenant` on the abstract class or model that declares `connects_to` to a separate database.
The common pattern of `ApplicationRecord` using `connects_to` with multiple roles (writing/reading) on the same database works correctly; Apartment keys pools by `tenant:role` and respects Rails' role routing.
## ActionController::Live Streaming
Apartment v4 handles tenant propagation across `ActionController::Live`'s spawned streaming thread automatically, under both `:thread` and `:fiber` isolation. Including `ActionController::Live` in your controller is sufficient — no additional configuration:
```ruby
class StreamingController < ApplicationController
include ActionController::Live
def show
response.headers['Content-Type'] = 'text/event-stream'
# Apartment::Tenant.current returns the request's tenant here,
# even though we're now executing on the OS thread Rails spawned
# for streaming.
response.stream.write("data: #{{ tenant: Apartment::Tenant.current }.to_json}\n\n")
ensure
response.stream.close
end
endHow it works: Apartment prepends ActionController::Live#process with a patch that backports rails/rails#56902 to released Rails versions — it points Thread.current.active_support_execution_state at the request fiber's hash for the duration of the request, so Rails' own share_with carries all CurrentAttributes (apartment's tenant plus any app-defined ones) into the spawned streaming thread. User-spawned threads or fibers inside a Live action (Thread.new, Async { }, raw Fiber.new) escape the patch and need explicit Apartment::Tenant.switch wrapping. See the upgrading guide and docs/designs/rails-boundary-tenancy.md.
Use block-scoped switching in jobs:
class TenantJob < ApplicationJob
def perform(tenant, data)
Apartment::Tenant.switch(tenant) do
# process job
end
end
endFor automatic tenant propagation:
A job that forgets to switch runs in the default tenant — for Rails.cache and
other Tenant.current-derived resources that silently contaminate another
tenant's keyspace. Guard routed work with Apartment::Tenant.require_tenant!
(raises unless a real, non-default tenant is active) and pinned/global work with
require_default_tenant!. See Tenant-Aware Caching for the
routed-vs-pinned model and the two-store recipe.
v4 keys a connection pool per `"tenant:r
No open issues yet, or sync has not completed.