Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do avoid race conditions in a Ruby on Rails application?
    text
    copied!<p>I'm developing a Rails application in which each subdomain has a separate database. And I'm doing something like this.</p> <pre><code>#app/controller/application_controller.rb class ApplicationController &lt; ActionController::Base before_filter :select_database private def select_database MyModel.use_database(request.subdomains.first) end end #app/model/my_model.rb class MyModel &lt; ActiveRecord::Base def self.use_database path establish_connection :adapter =&gt; 'sqlite3', :database =&gt; File.join(RAILS_ROOT, "db", "sqlite3", path) end end </code></pre> <p>Now, in <code>production</code> mode, requests come and execute in this order.</p> <ol> <li>Request "A" comes for subdomain <em>a.example.net</em> and <code>MyModel</code> establishes a connection with database "a".</li> <li>Now another request "B" comes for subdomain <em>b.example.net</em> and <code>MyModel</code> establishes a connection with database "b".</li> <li>Now if request "A" tries to do a <code>MyModel.find_*()</code> which database would it access? "a" or "b"?</li> </ol> <p>I believe that this is what we call "thread safety" or "race condition", and if this is so, then how can we avoid it while implementing an application using one database per subdomain?</p> <p>In the above question, my assumption is that executing two requests simultaneously is a normal behaviour for production servers. Or is there some better approach. I don't have much experience of production servers, so please advice.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload