title: Devise losing session when I'm using ActiveRecord::Base.establish_connection
body: <h2>Environment</h2>
  <ul>
  <li>Ruby <strong>2.6</strong></li>
  <li>Rails <strong>6.0</strong></li>
  <li>Devise <strong>4.7.2</strong></li>
  <li>Database <strong>Postgres</strong></li>
  </ul>
  <h2>Current behavior</h2>
  <p>Hi,
  I'm using a custom Middleware to connect to correct database based on subdmain</p>
  <pre class="lang-rb prettyprint-override"><code>module Vtenancy
    class WebTenancyMiddleware
      def initialize(app)
        @app = app
      end
  
      def call(env)
        Rails.logger.info(&quot;env #{env['SERVER_NAME']}&quot;)
  
        if (Vtenancy::Tenant.current = Vtenancy::Tenant.tenant_from_env(env))
            Vtenancy::Tenant.current.establish_connection
            @app.call(env)
         else
          [404, {}, []]
        end
      end
    end
  end
  </code></pre>
  <pre class="lang-rb prettyprint-override"><code>module Vtenancy
    class Tenant &lt; Vtenancy::ApplicationRecord
       def self.current
        if Rails.env.test?
          @current
        else
          RequestStore.store[:tenant]
        end
      end
  
      def self.current=(tenant)
        if Rails.env.test?
          @current = tenant
        else
          RequestStore.store[:tenant] = tenant
        end
      end
     
  
      def establish_connection
        Vtenancy::Tenant.current = self
        ActiveRecord::Base.establish_connection(name.to_sym)
        ActiveRecord::Base.connection.active?
        ActiveRecord::Base.connection.enable_query_cache!
      end
  
    end
  end
  </code></pre>
  <p>I add it before Warden::Manager</p>
  <pre class="lang-rb prettyprint-override"><code>  config.middleware.insert_before Warden::Manager, Vtenancy::WebTenancyMiddleware
  </code></pre>
  <p>But, when I access a page with a lot of requests, some fails with 401. Totally random</p>
  <p>I'm using cookie session on Rails.</p>
  <hr />
  <h1>Edit 1</h1>
  <p>I changed the code a little bit because I read from rails issues (<a href="https://github.com/rails/rails/issues/37158" rel="nofollow noreferrer">https://github.com/rails/rails/issues/37158</a>) that connect to with database will be removed.</p>
  <p>But anyway, using establish_connection have the same problem.</p>
  <hr />
  <h1>Edit 2</h1>
  <p>I set puma threads to one and now it's working.
  It's not the solution I need because It make my application note mult thread</p>