Speed Up Rails Deletes: Avoid Slow Callbacks
Summary
Pixel shares a practical guide to the performance costs of Rails dependent: :destroy when child callbacks run for every record. It shows how deleting heavy children with delete_all, then destroying the parent, avoids repeated callbacks and touches, while a background job handles one bulk Elasticsearch reindex.
DEV Community
Why Rails dependent: :destroy Gets Painfully Slow, with a Simple Example
What happens dependent: :destroy (so-called cascade delete) is handy: delete the parent record, and its child records go with it. But if the children have callbacks, those callbacks fire on every single delete. class Author < ApplicationRecord
has_many :books, dependent: :destroy
end
class Book < ApplicationRecord
belongs_to :author, touch: true # deleting it updates the parent's updated_at (a "touch")
after_destroy :reindex_search # reindexes Elasticsearch on every single delete (synchronous, heavy)
end
When you call author.destroy… destroy 1 Author
└─ if there are 1000 books, destroy them one by one (cascade)
└─ each time, touch the parent, and after_destroy runs
an Elasticsearch update — 1000 times, one after another 😱
You won't notice while the data is small, and then it suddenly times out with production-sized data. Fix: delete only the heavy children first, "without callbacks" delete_all fires no callbacks (no cascade, no touch) and deletes everything with a single SQL statement. ActiveRecord::Base.transaction do
Book.where(author_id: author.id).delete_all # ① quietly wipe out the heavy children
author.destroy # ② no children left, so nothing cascades
end
Don't drop the Elasticsearch update — do it once, later, asynchronously and in bulk
ReindexJob.perform_later(author.id) # ③ outside the transaction
Three key points What to do Why Delete the heavy children first with delete_all Doesn't fire callbacks (cascade / touch) (destroy_all does) Delete the parent afterward No children left to cascade, so no heavy work runs Do the heavy work (ES reindex) in a background job, in bulk Replace "synchronous, one at a time" with "asynchronous, once for all" Glossary cascade … deleting the parent also deletes its children in a chain. That's what dependent: :destroy does touch … updating only the related record's updated_at as a "this was updated" mark, without changing its contents destroy = loads records one by one and runs callbacks (safe but slow) delete = runs SQL directly and skips callbacks (fast, but you're on your own)

Powered by Readybot.io