Yeda AI Tips · #130

Español

Reject AI-Generated Rails Callbacks That Do Slow Work

That after_save callback is why your test suite hits the network. Ask an AI assistant to "sync the record to the CRM after saving" and it will happily hand you an after_save that makes an HTTP call — inside your save, on every save, in every test. It compiles, it passes the happy-path spec, and it plants a slow, flaky dependency in the hottest path of your app. This is one of the easiest AI-generated patterns to reject in review, because the rule is one sentence long.

Why the generated callback is a trap

A callback isn't a hook that runs "after the important part." It is part of the important part:

The one-sentence review rule

Callbacks are for cheap invariants. Network and slow or retryable work goes to background jobs.

Work in the callbackVerdict
Normalize an email, set a default, compute a slugCallback — fine
Update a counter or denormalized columnCallback — fine
HTTP call to any external APIReject — background job
Sending email, push, or webhooksReject — background job
Anything that can fail transiently and should retryReject — background job
Anything slower than ~1 msReject — background job

The compliant version is barely longer than the generated one:

# AI-generated — reject in review
after_save :sync_to_crm
def sync_to_crm
  CrmClient.new.upsert(self)   # network call inside your save
end

# What to ask for instead
after_commit :enqueue_crm_sync, on: [:create, :update]
def enqueue_crm_sync
  CrmSyncJob.perform_later(id)
end

class CrmSyncJob < ApplicationJob
  retry_on Net::OpenTimeout, wait: 3.seconds, attempts: 5
  def perform(record_id)
    CrmClient.new.upsert(Record.find(record_id))
  end
end

Note after_commit, not after_save: it fires only after the transaction actually commits, so you never enqueue a job for a record that rolled back — and by then an exception "won't roll anything back anymore."

What you win

Power-user moves

Resources

Building with AI coding assistants? Yeda AI designs, audits, and ships production LLM systems.

Talk to us · Read the blog