title: 2 HTTP requests simultaneously checking if record exists, if not creates it = duplicate records
body: <p>I have this app that, on first launch, calls 2 different API endpoints on my server backend (both with very different purposes). Both 2 methods, however, have a <code>before_filter</code> that authenticates the call using information passed in the <code>HTTP_AUTH</code> header (device identifier + api key). </p>
  
  <p>If it fails to find a row from my devices table with the provided identifier, it automatically creates a new row with that identifier. My problem is, it seems that sometimes the 2 calls are so simultaneous that both requests don't find any record and so they both create a new device row (with results in duplicate rows that have the same device identifier).</p>
  
  <p>My auth method looks like this:</p>
  
  <pre><code>def current_user      
      authenticate_with_http_basic do |udid, secret|
          if secret == APP_SECRET
              @device = Device.find_by_udid(udid)
  
              if !@device
                  @device = Device.new
                  @device.udid = udid
                  @device.created_on = DateTime.now.utc
              end
  
              // set a bunch of properties on @device
              @device.connected_at = DateTime.now.utc
              @device.save
          end
      end
  end 
  </code></pre>