Search code examples
ruby-on-railsthread-safetythin

Is this async Rails action safe?


I'm trying to make a rails action asynchronous and non-blocking. I'm using rails 3.2 and the thin web server. Is the following code safe?

class AnalyticsController < ApplicationController
  # [...]

  # called by an XHR request, displaying a spinner in the main page while loading
  def load
    Thread.new do
      @answer = Analytic.build_stuff_with_blocking_io # can take up to 60sec
      request.env['async.callback'].call [200, {}, render_to_string(partial: '/analytics/dashboard', layout: false)]
    end
    throw :async
  end

end

Solution

  • Here is an example how to do an async Rails action:

    class ApplicationController < ActionController::Base
      def async
        EM.defer do
          sleep 5 # Some work that take a long time.
          request.env['async.callback'].call response
        end
    
        throw :async
      end
    end
    

    Make sure you have config.allow_concurrency = true in you enviroment. And that you are using a server capable of async responses, like Thin.

    If you are using Thin:

    bundle exec thin --threaded start