Skip to content

Basic Tenancy with Apartment, Sidekiq and MySQL

J. Scott Johnson edited this page Sep 1, 2017 · 3 revisions

Given that much of Apartment's documentation is very tied to Postgres and the specific use of the schemas feature of Postgres, this wiki page covers the specific use case of a multitenant Rails app using Apartment, Sidekiq and MySQL.

Please note that this is pre-release documentation based on the Flexible Switching fork of the Apartment gem which has not yet been merged into the main branch.

Understanding Limitations

The one real limitation to understand is that there are connection issues at the lowest level of ActiveRecord that can cause issues with Apartment. These connection issues are addressed in Rails 5.1 at the ActiveRecord level and then enabled by turning on the use_schemas option in the apartment.rb initializer. While this sounds like the Postgres schemas feature, it is not. Setting this option configures Apartment to issue standard SQL use statements prior to queries. This prevents the thread safety issues associated with connection switching at the lowest levels of ActiveRecord. The one limitation with this is that it prevents switching to entirely different database servers for a given tenant.

This approach also restores the ability to use a threaded web server such as Puma since the thread safety issues are no longer a concern.

Gems

The two gems that you need are:

  • apartment - this provides basic tenancy for a Rails application including subdomain style functionality such as foo.domain.com where foo is the name of the database
  • apartment-sidekiq - this enhances sidekiq to pass in the current tenant with the sidekiq job

Step 1: Add Apartment and Apartment-Sidekiq to Your Gemfile

gem 'apartment', :git => "https://github.com/mikecmpbll/apartment.git", :branch => flexible-switching"
gem 'apartment-sidekiq'

Step 2: Generate the Initializer

Use the following command to generate the initializer

bundle exec rails generate apartment:install

Step 3: Edit the Initializer and Turn on use_schemas like this:

config.use_schemas = true

Step 4: Migrations

Note: This needs to be done.