Sidekiq background job enqueued in after_save callback fails to access persisted record

Recently while working on one of our project, there was a requirement of scheduling background job for processing some stuff once record is saved. So I written enqueue logic for job in after_save callback of record. But then job started giving unexpected results.

After long time of debugging I found that job was not able to fetch record from db which was just saved and after some researching on it I got to know that sometimes job scheduled in after_save callback fails to access that record as it tries to process it before transaction actually completes, so if you query database from job to fetch that record you will get record not found exception.

So clean solution for such scenarios is to useafter_commit callback which makes sure that your record is persisted in database and then your background job can access that record.

For more details on this issue of processing background job in after_save callback you can check following articles -

rails-callbacks-workers-and-the-race-you-never-expected-to-lose

sidekiq-issue-can-not-find-modelname-with-id12345

Tushar Titame

I am software enthusiast. I like to work on web frameworks, services and trending things in JS world. As a hobby I love visiting beautiful places and capturing them through eyes...

Read More