Search code examples
ruby-on-railsruby-on-rails-4backgroundworkerbackground-processresque

Rails Background Job for Creating Records?


Currently on Rails 4 with Resque.

My question is, would it make sense to use a background job for creating a record? Something like...

def create 
  @article = Article.new(articles_params)
  if @article.valid?
      background_job_here
  else
      render 'new'
  end
end

The only other documentation I can find on this matter says that it does not make sense to do this, however, does not explain why.

Reading Heroku documentation, they suggest that any request taking more than 500 ms be moved off into the background. Creating an article on my site is no exception as it can take upwards of 1,000 ms. If not a background job, how should I architect this? Thx!


Solution

  • In my humble opinion, I would not use a background job for anything that the user is expecting a response for. I think that this would disturb the request/response cycle. For instance, in your case, the user is expecting a response to a request for creating his article. However, it is perfectly fine to create a record in a background job as long as it is not mandatory for the response. For example, I do have background jobs for creating other records that are not being requested by the user, but are used for analytics on user action. Now, it is definitely a problem that it takes 500ms to 1000ms for creating an article. It is a performance problem that a background job is not really addressing anyway. I do not know what the specifics of your app are, but you may want to look into caching your database (with redis for instance).