Menu

Why Rails `dependent: :destroy` Gets Painfully Slow, with a Simple Example
πŸ“°

Why Rails `dependent: :destroy` Gets Painfully Slow, with a Simple Example

DEV Community: railsΒ·KaziuΒ·about 6 hours ago
#iLc1PVlN
#devtorails#devto#dev#destroy#delete
Reading 0:00
15s threshold

Kaziu

Posted on Nov 16

Edited on Nov 16

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

Enter fullscreen mode

Exit fullscreen mode

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 😱

Enter fullscreen mode

Exit fullscreen mode

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,…

Continue reading β€” create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.