Search code examples
ruby-on-railsrubysidekiq

Sidekiq best practice when try to destroy object in perform method


Is it safe to call AC destroy in side perform method? I have this method and it will loop through devices and send notification, if failed it will destroy that device in rescue.

Is it possible one thread A paused right after this line "devices = Device.where(id: device_ids)" and thread B destroyed the same device object paused by Thread A, when thread A resumes, "devices" would be already destroyed? How to deal with this issue>

def perform(device_ids, message)
  devices = Device.where(id: device_ids)
  devices.each do |device|
    begin
      device.send_notification(message)
    rescue Aws::SNS::Errors::EndpointDisabled
      device.destroy
    end
  end
end

Solution

  • If they both try to destroy the same database record, yes, there can be a race condition. Typically you rescue and ignore the error.