Is it better to create new controller instance for each HTTP request in Rack based app or to use the same instance?

StackOverflow https://stackoverflow.com/questions/19171108

  •  30-06-2022
  •  | 
  •  

Frage

I'm creating a very simple Rack based application as I want it to do a very specific task.

The server.rb looks something like this:

Path= File.expand_path("#{File.dirname __FILE__}/../../")

require "bundler/setup"
require "thin"
require "rack"

%w(parser auth controller).each do |file| 
  require "#{Path}/app/server/#{file}.rb"
end


builder = Rack::Builder.app do
  use Auth
  run Parser.new    
end

Rack::Handler::Thin.run(builder, :Port => 8080, :threaded => true)

parser.rb looks like:

class Parser

  def initialize
    @controller = Controller.new
  end

  def call(env)
    req = Rack::Request.new(env).params
    res = Rack::Response.new
    res['Content-Type'] = "text/plain"

    command= req[:command]

    if command =~ /\A(register|r|subscribe|s)\z/i
      @controller.register     
    end


    res.write command
    res.finish 

  end
end

Now my question here, from design prospective, is it better to create one instance of Controller and use it with each request(like Idid with the code above), or to create new controller instance for each request(change @controller.register to Controller.new.register)? which is better to use and why?

Thanks in advance

War es hilfreich?

Lösung

The overhead of creating a new controller per request is likely not that large.

If you store state in the controller (instance variables etcetera) and you reuse it, you could run into concurrency issues such as race conditions or deadlock when under load.

If you take care to ensure that your Controller object stores no state, you can reuse it. If it does any sort of state storage per request, you will need to ensure that the shared resources are property synchronized.

My 2c - create a new controller per request, until you can confirm that you have a performance hit from creating a new controller per request. It's simpler, cleaner, and less prone to strange bugs.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top