Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can Rails observers and callbacks be handled asynchronously (in a different thread)?

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?

like image 472
Sid Avatar asked Feb 22 '11 18:02

Sid


People also ask

Are rails callbacks Asynchronous?

Guideline #2: Asynchronous by defaultWhenever we add a callback, that is code that will execute before we can respond to a request. If a class defines 20 callbacks, that's 20 blocks of code that must execute before we can respond to the user. Generally, this will make requests take longer.

What is difference between observer and callback in rails?

One really important distinction to keep in mind, which is related to Milan Novota's answer, is that callbacks on an ActiveRecord have the ability to cancel the action being called and all subsequent callbacks, where as observers do not. Observers may only observe, they may not intervene.

How does Callback work in Rails?

Callbacks are methods that get called at certain moments of an object's life cycle. With callbacks it is possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.

What is difference between callbacks and filters in rails?

around_action Around filters may have logic before and after the action being run. You can use around filters for exception handling, setup and teardown, and a myriad of other cases. Callbacks: Callbacks allow you to trigger logic before or after an alteration of an object's state in model.


1 Answers

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.

like image 112
ctcherry Avatar answered Sep 28 '22 00:09

ctcherry