Solving A Race Condition When Using find_or_create_by

1.6k views Asked by At

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?

1

There are 1 answers

0
brookz On