Hi,
I have a multi-tenant web application. Each tenant’s data is
separated into their own database. In rails, I have some code to
manually change the database connection using
ActiveRecord::Base.establish_connection to create a connection to the
appropriate database.
My question is this: in a single database environment (as I am aware
Rails is designed for), Rails seems to maintain the connection to the
database beyond the lifetime of a request. Looking at mysql, the
connection is placed in sleep mode and obviously reused for the next
action. However, if I am manually establishing connections, this
reuse of connection will obviously not function. Are there any
downsides to using ActiveRecord::Base.establish_connection to
establish a connection on each request to potentially a different
database? Will these connections be gracefully closed once the
request is over? And finally, is there any way to use connection
pooling to keep a list of connections to each database and reuse them,
instead of creating a new one on each request?
Thanks in advance! 
Hello,
If you would find a solution for a connection pool, i would be very
interested in your approach.
As i am currently have struggeling with thesame problem.
Every request with ActiveRecord::Base.establish_connection on every
request has the following performance hit (about 0.01s, too big in my
opinion)
With ActiveRecord::Base.establish_connection on every request
Processing SiteController#show_page (for 127.0.0.1 at 2007-08-24
22:46:25) [GET]
Parameters: {“action”=>“show_page”, “url”=>[“products”, “m-series”],
“controller”=>“site”}
Completed in 0.01111 (90 reqs/sec) | DB: 0.00019 (1%) | 200 OK [http://
localdev.be/products/m-series/]
Without ActiveRecord::Base.establish_connection on every request
Processing SiteController#show_page (for 127.0.0.1 at 2007-08-24
22:42:07) [GET]
Parameters: {“action”=>“show_page”, “url”=>[“products”, “m-series”],
“controller”=>“site”}
Completed in 0.00169 (590 reqs/sec) | DB: 0.00035 (20%) | 200 OK
[http://localdev.be/products/m-series/]
Thanks,
Tiele
Most rails apps that are multi-tenant use a single database. This is
covered
a lot and DHH has commented on how basecamp does it. Might want to
search
the list archives for some proposed solutions. They all involve using
associations to protect data from being exposed to the wrong user.
Of course, that doesn’t answer your question, but I thought I’d bring it
up.