Search code examples
rubytransactionsruby-on-rails-5delayed-job

Implications of Wrapping Delayed Job in Transaction for Rails App


Can anyone explain what would happen in the code below if the delayed_job that's scheduled in two weeks fails?

My understand is that this entire transaction would sit in memory until the transaction runs successfully or exhausts the permitted number of attempts (i.e. transaction doesn't merely guarantee that the job itself is created). Am I correct? If anyone could also elaborate on implications of this structure (i.e. memory leakage, race conditions, performance, etc.) and potential improvements that would be greatly appreciated!

...

def process
  old_user.transaction(requires_new: true) do
    begin
      update_user_attributes

      TransferUserDataJob.new(old_user, new_user).delay(run_at: 14.days.from_now, queue: 'transfer_user_data_queue').perform       

      raise ActiveRecord::Rollback if user.status.nil?
    rescue Exception => e
      raise ActiveRecord::Rollback
    end
end

...

Solution

  • No, the transaction will NOT wait two weeks. This is precisely the reason why background jobs exist: do the expensive/heavy stuff later, so that frontend can respond as quickly as possible. If your user transfer process needs to happen in the same transaction, either move everything to the worker, or do everything on the spot, without delaying.

    That is, transaction doesn't merely guarantee that the job itself is created?

    This is exactly what happens in your code.