user782220
user782220

Reputation: 11207

Does Rack handle requests serially or concurrently?

Suppose I have a single process Rack application, if multiple requests arrive at the same time can the invocations of call(env) occur concurrently? Or is it guaranteed that call(env) will happen serially and so therefore there is no race condition on @counter? Does it make any difference between using Unicorn or Thin?

require 'json'

class Greeter
  def call(env)
    req = Rack::Request.new(env)
    @counter ||= 0
    @counter = @counter + 1
    puts @counter
    [200, {"Content-Type" => "application/json"}, [{x:"Hello World!"}.to_json]]
  end
end

run Greeter.new

Upvotes: 1

Views: 574

Answers (1)

Stuart M
Stuart M

Reputation: 11588

It depends on your Rack handler (the application server). Unicorn and Thin are both capable of concurrent requests, using multi-process and/or evented models, depending on which one you choose and how you configure it. So its not really a question of whether Rack supports it, since it is the handler (Unicorn, Thin, or others) that are responsible for concurrency. This post has some more details and an overview of several popular Rack app servers:

Is Sinatra multi threaded?

If you're wondering whether an instance variable in the Greeter class could potentially be shared between threads, that should not happen even when using one of the concurrent app servers, since they will each have their own Greeter instance and hence separate instance variables. But you would need to watch out for globals or constants, since those would be shared across all threads so you'd need to take that into account and use a lock/mutex, etc.

Upvotes: 1

Related Questions