skip to content

In a Rails kanban app, why does destroying a board with thousands of cards through dependent: :destroy time out, and what are your options?

level: seniorimportance: should knowfreq 45%

answer

  1. one transaction, every child loaded
  2. destroy! per card, cascading down
  3. delete_all: one statement, no callbacks
  4. destroy_async enqueues after commit
  5. destroy_association_async_batch_size defaults to nil

basics

~20 s

dependent: :destroy loads every card and destroys each one, with its callbacks and cascades, inside the board's transaction. Use :delete_all for plain rows, :destroy_async to move per-card destroys into jobs enqueued after commit, a database cascade, or archive-then-purge.

solid answer

~40 s

`dependent: :destroy` is a `before_destroy` callback that loads all 8,000 cards and calls `destroy!` on each, running their callbacks and their own cascades, all in one transaction that holds locks and a connection until the last `DELETE`. Options: `:delete_all` issues one `DELETE` but skips callbacks and grandchildren. `:destroy_async` deletes the board, then after commit enqueues `ActiveRecord::DestroyAssociationAsyncJob`, which destroys the cards by id; tune `destroy_association_async_batch_size`, which defaults to `nil` (one job), and remember that cards are orphaned meanwhile, that ids are still loaded in the request, and that it must not be combined with a foreign key constraint. A database `ON DELETE CASCADE` is fastest but runs no callbacks. For huge boards, archive first and purge in batches.

code

ruby · 12 lines
ruby
class Board < ApplicationRecord
  has_many :cards, dependent: :destroy_async
end

# config/application.rb
config.active_record.destroy_association_async_batch_size = 500
config.active_record.queues.destroy = :cleanup

board.destroy
# 1. SELECT cards (ids collected), DELETE board, COMMIT
# 2. after commit: 16 DestroyAssociationAsyncJob jobs of up to 500 card ids
# 3. each job: find_each over its ids, card.destroy (callbacks run)

go deeper

for a junior

Recall that dependent: :destroy loads and destroys each child one by one, which is why it gets slow with many rows.

for a middle

Explain the statements and callbacks each strategy runs, and what delete_all skips compared with destroy.

for a senior

Diagnose the timeout from transaction length and per-row callbacks, then choose between destroy_async with batching, a database cascade, or archive-and-purge, naming each one's failure modes.

for a principal

Set deletion policy by data volume and audit needs: decide which deletes are synchronous, which are eventual, and how the product behaves while cleanup is pending.

## Why the request times out A kanban board that has collected 8,000 cards, each with comments and attachments, is declared like this: ```ruby class Board < ApplicationRecord has_many :cards, dependent: :destroy end ``` `board.destroy` looks like one operation, but `dependent: :destroy` does a great deal inside a single transaction: 1. It **loads every card** into memory: 8,000 Active Record objects. 2. It calls `destroy!` on each one, so each card runs its own callbacks, its own `dependent:` cascades (the comments, then whatever hangs off them) and its own `DELETE`. 3. Only then does the board's own `DELETE` run, and the transaction commits. That is tens of thousands of statements and object allocations, holding row locks and one database connection for the whole time. The request times out, memory spikes, and if any card's `before_destroy` aborts, `ActiveRecord::RecordNotDestroyed` is raised and the work so far is rolled back. One small mercy: cards destroyed this way skip decrementing the board's counter cache, since the board is going away anyway. ## Option 1: delete_all when nothing needs Ruby `dependent: :delete_all` replaces all of that with one `DELETE FROM cards WHERE board_id = ?`. It is fast, but it runs no card callbacks and does not touch the cards' comments or attachments. It is correct only when cards are plain rows, or when the database itself cascades the grandchildren. ## Option 2: destroy_async `dependent: :destroy_async` keeps per-card callbacks but moves them out of the request: - The board is deleted in its own transaction. Before that, Rails still **loads the cards** to collect their ids. - After the transaction **commits**, Rails enqueues `ActiveRecord::DestroyAssociationAsyncJob` with the board's class and id and the card ids. - The job checks that the board is really gone, then walks the ids with `find_each` and calls `destroy` on each card, running its callbacks and cascades. Configuration that matters: | Setting | Default | Effect | |---|---|---| | `config.active_record.destroy_association_async_batch_size` | `nil` | cards per job; `nil` puts every id in one job | | `config.active_record.queues.destroy` | `nil` | queue for these jobs; `nil` uses the default queue | | `config.active_record.destroy_association_async_job` | `ActiveRecord::DestroyAssociationAsyncJob` | the job class | | `ensuring_owner_was:` on the association | none | owner method that must return true for the job to proceed | The caveats are what separates a senior answer: - **Orphans exist for a while.** Between commit and job completion, cards point at a deleted board. Code that reads cards must tolerate a missing board. - **Do not combine it with a database foreign key constraint.** The API docs warn that a constraint acts inside the transaction that deletes the owner: it either rejects the board's delete or cascades the cards itself, and either way the job's callbacks are bypassed. - **It still loads every card id in the request**, so a board with a million cards needs a different design. - **Jobs can fail.** If the board still exists when the job runs, it raises `ActiveRecord::DestroyAssociationAsyncError`; ordinary job failures need retries and monitoring like any job. Running the jobs is the job backend's concern. ## Option 3: let the database cascade A foreign key with `ON DELETE CASCADE` deletes the cards in the same statement, at database speed, with no Ruby callbacks. It is the right tool when cards and their descendants are plain rows. Declaring it is a migration concern; the point here is that it competes with `dependent:` rather than complementing it, so pick one per association. ## Option 4: archive now, purge later For very large or audited data, mark the board archived in the request, hide it everywhere, and purge in your own background job in batches (for example `board.cards.in_batches(of: 500)` with `destroy_all` or `delete_all` per batch). You control the pace, the batch size and what happens to attachments. ## Measuring before choosing Before switching strategies, look at what a destroy actually does: the development log lists every `SELECT` and `DELETE`, and counting them for one realistic board shows whether the cost is in the card loop, in grandchildren, or in callbacks such as attachment purges. The fix differs for each. ## Choosing | Children | Choose | |---|---| | few, with callbacks | `:destroy` | | many, with callbacks or attachments | `:destroy_async`, or archive and purge | | many plain rows | `:delete_all` or a database cascade | | huge or audited | archive and purge in batches |

  • Why must the destroy_async job be enqueued after commit rather than inside the board's transaction?
    If it were enqueued inside, a fast worker could run before the board's delete commits, find the board still present and fail, or the transaction could roll back and leave a job destroying cards of a board that still exists. Rails collects the jobs and enqueues them in an `after_commit` callback.
  • What does ensuring_owner_was: add to dependent: :destroy_async?
    It names an instance method on the owner that the job calls before destroying anything; the cards are destroyed only if the owner is gone or that method returns true. It suits soft deletes, where the board row remains but is flagged as deleted.

  • dependent: :destroy issues one DELETE for all the children.
  • destroy_async enqueues its job before the owner's transaction commits.
  • destroy_async never loads the children during the request.
  • delete_all runs each card's callbacks but in one statement.
  • Combining destroy_async with ON DELETE CASCADE is the recommended setup.