Production lit up with thousands of NoMethodError: undefined method 'starts_at' for nil, all from an SMS notifier. The app uses the noticed gem (v2) to send notifications by email, push, and SMS. The notifier looked fine. The booking it referenced had been deleted.

What was happening

The notifier built the SMS body from the booking:

def sms_options(notification)
  super.merge(
    body: "You're booked for #{I18n.l notification.record.starts_at}.",
    to:   notification.recipient.phone_number
  )
end

Deliveries run in background jobs. Between enqueueing the notification and running the SMS job, the user deleted their booking, so notification.record was nil. The job retried over and over, and one deleted booking turned into a wall of errors.

The fix

noticed checks each delivery's if: condition inside the job, when it runs. That's the moment you know whether the record still exists. A base notifier can add the check to every channel:

class ApplicationNotifier < Noticed::Event
  def self.deliver_by(name, options = {})
    super do |config|
      yield config if block_given?

      original_if = config[:if]
      config.if = lambda do
        recipient.present? &&
          (event.record_id.nil? || record.present?) &&
          (original_if.nil? || instance_exec(&original_if))
      end
    end
  end
end

Checking record_id matters. Some notifications never have a record, and those should still go out. If record_id is set but record is nil, the record was deleted, so the delivery is skipped. No error, no retry.

Testing it

To reproduce the bug in a test, perform the jobs twice with the delete in between:

BookingNotifier.with(record: booking).deliver(user)
perform_enqueued_jobs   # EventJob enqueues the delivery jobs
booking.destroy
perform_enqueued_jobs   # delivery jobs run with the record gone

Takeaway

Records can disappear before a background delivery runs, so check for them when the job runs, not when it's enqueued.