wyncg
wyncg

Reputation: 53

Request to Grape API for rails block other requests

For my rails app I set up an API with gem Grape. I add a test post method that the code sleeps 10 seconds and returns {'status'=>'success'}. Everything works except that the API call seems to block all other requests sent to the server. Any other request will not be executed until this sleep 10 seconds api finishes. Any GET request from front end interface will be delayed. And if I simulate two api calls, it takes the second call 20 seconds (10 seconds for waiting the first one finishes) to finish. Please give advise on this.

The api.rb file looks like this:

module ProjectName
  module MyErrorFormatter
    def self.call message, backtrace, options, env
      { "status" => "Fail", "error_message" => message }.to_json
    end
  end

  class API < Grape::API

    format :json
    default_format :json
    prefix 'api'
    cascade false
    error_formatter :json, MyErrorFormatter
    helpers APIHelpers

    before do 
      authenticate!
    end

    post do
      if params[:action].present?
        p_url = format_url(params)
        redirect "/api/#{params[:action]}?key=#{params[:key]}#{p_url}"
      end
    end

    post 'test' do
      sleep(10)
      {'status'=>'success'}
    end
  end
end

I am using Rails 4.2.0

Upvotes: 4

Views: 904

Answers (1)

khpatel4991
khpatel4991

Reputation: 98

This means that your requests are not handled simultaneously in parallel. threadsafe is enabled in Rails 4 and that might have something to do with this. Threadsafe might be locking your action and so your next request can't get the access. However you can explicitly tell server to handle simultaneous request. Adding this line in all your config/environments files will help.

config.allow_concurrency = true

Also, you'll need a server that can handle concurrency like puma.

More info on this from this here and here.

Upvotes: 2

Related Questions