7
votes

Observers and Callbacks on Rails models operate on the same thread and block the request until they return.

For example, if I have a Photo model and I queue a resizing job in the after_create callback or observer, the request doesn't finish until an entry is made in the queue (which can sometimes be slow if I am using Amazon SQS for queuing).

Same holds true for Callbacks on Rails controllers. If I have to run maintenance like cache management or store analytics the request doesn't finish until the callback ends.

Is there a Rails way to run the code inside a callback (Model or Controller) or observer in a different thread so the request isn't stalled?

1

1 Answers

3
votes

A couple of the popular ways to run code in the background out of the request/response cycle is currently delayed_job and resque

delayed_job uses your database to queue up background processing jobs, and resque uses Redis.

I've used both and they both work great, read the documentation to see which might suit your case best.

This doesn't automatically make your observers and callbacks run in the background but it makes it pretty easy to do that, and more. This technique is very widespread and production battletested in the Rails community.