rails-on-services / apartment

Database multi-tenancy for Rack (and Rails) applications
376 stars 153 forks source link

Tenant DB Connection is not stable in seperate tenant DB use case #153

Open inspiredstuffs opened 3 years ago

inspiredstuffs commented 3 years ago

Steps to reproduce/Problem statement

I use Puma which is multi-threaded server hosted on Heroku.

While processing a request, the connection to the tenant DB is lost and it defaults to the main app database specified in the database.yml

NOTE: Apartment::Tenant.current intermittently switches between the Tenant DB and the Main App DB during a request lifecycle. Could this be as a result of insufficient Tenant DB connection pools. I noticed a bit of improvement when i increased the Tenant DB pool config.

I have also noticed that the connection can be lost when a call is made asynchronously to a web process that is currently connected to a tenant DB.

System configuration

pirminis commented 3 years ago

@inspiredstuffs did you find what's the problem? I have similar issue when current returns different database (scheme) name (mysql) during execution of sidekiq worker. It switches once, during random line of ruby code.

samuelpzbp commented 3 years ago

@pirminis I got a bit of stability by wrapping all lines of code with ActiveRecord queries, required throughout the request lifecycle with the switch block.

Apartment::Tenant.switch('TENANT') do // Your activerecord queries end

It can be resource consuming, but it brought some stability to the application.