Skip to content

Send mails in after_create_commit hook - #292

Merged
lmrodriguezr merged 1 commit into
mainfrom
send-mails-in-after-commit-hook
Jun 29, 2026
Merged

lmrodriguezr merged 1 commit into
mainfrom
send-mails-in-after-commit-hook

Conversation

@vangberg

Copy link
Copy Markdown
Contributor

#262

The AsyncAdapter will run jobs immediately. When a mail is sent via perform_later in an after_create hook, the job could run before the record exists in the database, since after_create hooks are executed before the transaction is completed:

  1. Contact.create opens a new transaction.
  2. after_create is run with the transaction still open.
  3. If the job runs before the transaction is committed, the Contact record does not exist yet.

By changing to an after_create_commit hook, we ensure that the Contact actually exists. Same goes for Notification.

I can reproduce this consistently in the production console:

original = Contact.find(30)

Contact.transaction do
  c = original.dup
  c.subject = "ASYNC BAD #{Time.now}"
  c.message = original.message.body.to_html
  c.save!

  puts "created #{c.id}; holding transaction open"
  sleep 1
end

This never sends an email. If I manually switch out the hooks and run the above block again, it reliably sends emails:

  Contact.skip_callback(:create, :after, :send_message)
  Contact.set_callback(:commit, :after, :send_message, on: :create)

@vangberg
vangberg requested a review from lmrodriguezr June 29, 2026 09:45
AsyncAdapter will run jobs immediately. When a mail is sent via
`perform_later` in an `after_create` hook, the job could run
before the record exists in the database, since `after_create`
hooks are executed *before* the transaction is completed.
@vangberg
vangberg force-pushed the send-mails-in-after-commit-hook branch from 3367889 to cc5cd47 Compare June 29, 2026 09:50
@lmrodriguezr

Copy link
Copy Markdown
Member

Excellent! That makes perfect sense, thanks!

@lmrodriguezr
lmrodriguezr merged commit af7dc47 into main Jun 29, 2026
3 checks passed
@lmrodriguezr
lmrodriguezr deleted the send-mails-in-after-commit-hook branch June 29, 2026 12:06
@vangberg vangberg mentioned this pull request Jun 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants