Evgenia Karunus
Evgenia Karunus

Reputation: 11232

How to run two functions concurrently from one route in Sinatra?

I'm trying to understand Ruby concurrency with Sinatra app.
Here it is:

require 'sinatra'

get '/a' do
    sleep 10
    "result_a"
end

get '/b' do
    "result_b"
end

If I run it as ruby app.rb or shotgun app.rb and then go to both /a and then /b - /b will not be loaded until /a executes and loads itself.
When I deploy this app to Heroku though, and go to /a then /b, /b is loaded immediately.
As I understand it, Heroku process is concurrent (or multithreaded?) as opposed to my local processes.

My questions are: how to run my app concurrently on local server? Is it possible to run, eg, two functions concurrently from one route?

Upvotes: 1

Views: 171

Answers (1)

user513951
user513951

Reputation: 13770

Install Unicorn.

gem install unicorn

The official docs aren't great but you can find plenty of tutorials showing you how to configure and start up parallel server processes that will allow you to serve multiple requests concurrently.

It works by forking your process, which means that it's completely thread-safe, but also means that concurrent requests won't share memory state with each other. In fact, they won't share memory at all, so if your app has a truly enormous memory footprint (e.g. some kind of in-memory database) you will need a different solution. Otherwise, Unicorn is a very popular and reliable concurrency tool for Ruby web apps; it may actually be what is allowing Heroku to exhibit the concurrency you're seeing.

Upvotes: 1

Related Questions