influitive / apartment

Database multi-tenancy for Rack (and Rails) applications
2.66k stars 463 forks source link

Concurrent tenants with threads using Postgres without schemas #180

Open epotocko opened 9 years ago

epotocko commented 9 years ago

I am experiencing issues with tenants not being switched in sidekiq for the entire duration of the job when there are multiple jobs running concurrently. I am using Postgres without schemas. I was able to put together this script to reproduce the problem (I can run it via the rails console or a rake task). I haven't tested this code with Postgres with schemas or Mysql so it could be broken there too.

def get_thread(tenant)
  Thread.new { 
    Apartment::Tenant.process(tenant) do
      (0..5).each do |i|
        sleep 1
        puts "#{tenant} = #{Apartment::Tenant.current_tenant}"
      end
    end
  }
end

Apartment::Tenant.switch('base')
t1 = get_thread('db1')
sleep(1)
t2 = get_thread('db2')

t1.join
t2.join

Output is: db1 = db2 db2 = db2 db1 = db2 db2 = db2 db1 = db2 db2 = db2 db1 = db2 db2 = db2 db1 = db2 db2 = db2 db1 = db2 db2 = base

bradrobertson commented 9 years ago

Apartment just uses rails connection handling if you're not using postgres schemas. I'm going to be looking at another threading issue shortly, I'll see if this aligns with your findings at all