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

Updated . Posted . Visible to the public.

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

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.

Last edit
Tobias Kraze
Keywords
ruby, rails
License
Source code in this card is licensed under the MIT License.
Posted to makandra dev (2023-01-19 17:21)