Search code examples
ruby-on-railspostgresqlsidekiq

Sidekiq fetches inconsistent data


class A
  ....
  def something
    if condition
      mark_completed
      // here I can see the object progress is completed
      CompletionStatsWorker.perform_async(self.id)
    end
  end

  def mark_completed
    self.update_attributes!(progress: 'completed')  
  end
end

In the worker:

class CompletionStatsWorker
  include Sidekiq::Worker

  def perform(id)
    obj = A.find(id)
    //here I'm getting the progress of the same object as 'progressing'
  end
end

Sidekiq somehow fetches old data even if it is triggered after the successful field updation. I can see that the object updated_at is not same as the actual updated_at value. Please help


Solution

  • it may happens because sidekiq works faster than it commited to DB, you should add CompletionStatsWorker.perform_async(self.id) to after_commit callback or change method to :

      def something
        if condition
          if mark_completed
            // here I can see the object progress is completed
            CompletionStatsWorker.perform_async(self.id)
          end
        end
      end
    

    take a look sidekiq docs