3

I am using

@current_device ||= Device.find_or_create_by!(udid: request.headers["udid"])

and sometimes there is a race condition, where due to network behavior, 2 requests come at the same time, which causes 2 devices to be created with the same udid, even though there is a validation on the udid column for uniqueness.

I tried to engulf this with

begin
    @current_device ||= Device.find_or_create_by!(udid: request.headers["udid"])
rescue ActiveRecord::RecordInvalid => e
            if e.message == 'Validation failed: Udid has already been taken'
                retry #to compensate/handle possible(and very happening) race condition
             else
                Rollbar.error(e)
             end
end

But it doesn't work.

Is there a better way to handle this race condition?

Nick Ginanto
  • 31,090
  • 47
  • 134
  • 244

1 Answers1

3

https://rietta.com/blog/2015/05/04/validates-uniqueness-race-condition-in-ruby-on-rails/

Fix race condition at the database level

brookz
  • 477
  • 5
  • 17