Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solving A Race Condition When Using find_or_create_by

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?

like image 941
Nick Ginanto Avatar asked Oct 20 '25 01:10

Nick Ginanto


1 Answers

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

Fix race condition at the database level

like image 149
brookz Avatar answered Oct 22 '25 04:10

brookz