Read more

Why Sidekiq Jobs should never be enqueued in an after_create or after_save callback

Avatar
Tanja
January 19, 2023Software engineer at makandra GmbH

When an object is created / updated, various callbacks are executed in this order Show archive.org snapshot :

before_validation
after_validation
before_save
around_save
before_create
around_create
after_create
after_save
after_commit / after_rollback
Illustration book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
Read more Show archive.org snapshot

Thus, each of these callbacks is executed at a specific time in the life cycle of the object Show archive.org snapshot . This is important because this point in time determines which actions can be executed in the respective callbacks.

after_save vs after_commit

In case of after_save callbacks, changes to the object are not yet persisted in the database. At this point, the transaction is still open and can still be rolled back in case of an error. This is no longer possible with after_commit, since changes are already persisted in the database. (see here Show archive.org snapshot )

Reference to Sidekiq Jobs

Note that you should generally avoid creating Sidekiq Jobs with code that is wrapped within a database transaction. For example, if you have an ActiveRecord after_save callback that creates a Sidekiq Job it will not be cancelled if the implicit database transaction is rolled back!

The after_commit callback is an exception to this. Since all changes are already persisted in the database when after_commit callbacks are executed, there is no possibility that a Sidekiq Job will be created on an unfinished / non-existent record. For this reason, it is ok to create Sidekiq Jobs in after_commit callbacks.

Posted by Tanja to makandra dev (2023-01-19 18:21)