Optimize Deletions: destroy_async for Rails

Purpose:

How it Works:

  1. Association Definition:
    • When you define an association (e.g., has_many, belongs_to), you can specify the dependent behavior for deletion:
      1
      2
      3
      
      class Order < ApplicationRecord
        has_many :order_items, dependent: :destroy_async
      end
      
  2. Parent Record Destruction:
    • When you call destroy on the parent record (e.g., order.destroy), Rails doesn’t directly delete the associated order_items.
  3. Background Job Enqueueing:
    • Instead, Rails enqueues an ActiveRecord::DestroyAssociationAsyncJob in the background job queue (typically managed by Active Job).
  4. Background Job Processing:
    • A separate worker process picks up the job from the queue and executes the following steps:
      • Fetches the associated records for deletion (e.g., order_items belonging to the destroyed order).
      • Iterates through the associated records and calls destroy on each one, triggering their deletion callbacks and database operations.

Benefits:

Considerations:

When to Use destroy_async: