How to delete the bulk of custom data when the associated user is deleted I'm one of the maintainer of Statuses(Social Microblog), As of now we are storing the status messages and comments to it in custom tables. We are also having hooks which needs to be invoked for the deletion of every status message,

Since this just  a status update, we will have bunch of messages(even 2k+ also possible) associated with one user.

So when the user is deleted, we need to delete all the status messages and comments associated to that user. The problem I could see that I need to perform these deletions in hook_user_delete, so if I have more number of deletions it may give timeout error and also I need to consider performance here.

If I directly loop through the status messages to delete one by one then it will be a hectic process, because when a status message is deleted it needs to invoke several hooks.

I want a guidance on handling this situation.
One approach would be to add a deleted column to your messages table, and mark the messages for deletion when a user is deleted, e.g.

function statuses_user_delete($account) {
  db_update('statuses_message')
    -&gt;fields(array('deleted' =&gt; 1))
    -&gt;condition('uid', $account-&gt;uid)
    -&gt;execute();
}


Forgive the obviously incorrect table name, I'm not familiar with the statuses module.

Then in a cron hook, you could grab x number of the messages marked for deletion, and process them:

function statuses_cron() {
  $max = 50;
  $sql = 'SELECT message_id FROM {statuses_message} WHERE deleted = 1';
  $message_ids = db_query_range($sql, 0, $max)-&gt;fetchCol();

  statuses_delete_message_multiple($message_ids);
}


I'm making some assumptions about how things are set up in your module, but hopefully the principal is obvious enough. You could one step further and implement hook_cron_queue_info(), which will give you a finer grained control over the amount of time your worker can run for. I think some profiling with both methods would probably be appropriate to determine which which is better.

This is along the same lines as the logic the core field module uses to purge deleted data on the cron run, so I think it's safe to assume the principal at least is well tested...it's just whether this method will work for your use case.

I guess the only sticking point here would be the amount of code you need to change in the rest of the module to respect the new deleted column (i.e. not showing deleted messages to users). Again I can't really comment on that as I'm not familiar with the module, but if you take a methodical approach to implementing changes I can't imagine it being that much of a problem.