Is a new instance of sinatra started on every request? Is a new instance of sinatra started on every request? ruby ruby

Is a new instance of sinatra started on every request?


A new class is created for every request. However, this is not done by Rack. This is a feature of Sinatra. If you want to dig into the details: The instance is not actually created with Sinatra::Application.new but with Sinatra::Application.prototype.dup, see Sinatra::Base#call for the code.


You should always assume that the entire app could be rebooted under you in-between requests. What if you are running 16 copies of your app - the request from user 'jane' for '/' could com e in on copy #2, then when she visits '/signup' the request will hit #12 (possibly booted for this event) app. So it does not matter what Sinatra does (although it looks like they do something similar), since your app could just appear anywhere, booted today, yesterday or a ms ago.

If you plan on growing - or deplying on Heroku, etc - your app needs to run fine using 'shotgun' - which restarts everything for each request. I guess if your app does something radically different than serve web pages, and hardly ever crashes or gets rebooted, you might get away with 'NO'

So my answer is 'YES' (but not always, and not even sometimes usually).

Nevertheless, it's handy to know how things work, so that you can perhaps only set up some complex calculated asset caching scheme once per app load - which is a performance opt. For example, if each call to your app with the url /calculate_pi?decimals=2000 always results in the same 2000 digit number, you could cache that on each instance.


A quick test shows that the same instance is running whatever the request (at least, by default).

require 'sinatra'flag = falseget '/stuff' do  puts "flag is #{flag ? 'set' : 'unset'}"  flag = trueend

When this code is run and two requests are received, the server will prompt flag is unset and then flag is unset.

EDIT:

That shows the files are not reloaded. By using puts self.object_id, self.class (as pguardiario recommended), we actually see that a new instance of Sinatra::Application is created for each request.