0

I have a sinatra app that is using thin as it's web server. I interact with my database via ActiveRecord.

If in an endpoint, I do this:

get '/test' do
  Model.create(.....)
end

Does the Model.create(.....) block the event loop (thin uses eventmachine internally)? If so, how bad is this and what are the alternatives?

Thanks

0xSina
  • 20,973
  • 34
  • 136
  • 253
  • All actions "block" a thread until they complete. If the eventmachine thread (it only uses one) calls the request method then it will block until the method completes. – user2246674 May 25 '13 at 01:40

2 Answers2

0

My understanding is that thin is threaded by default, unless you disable that. So your request handler can be executed asynchronously using Eventmachine::Defer.

Yes, as the comment by @user2246674 says, if your handler is executed in the reactor thread then it will block everything.

As to the alternatives, I just searched Google for ActiveRecord and Eventmachine and the first hit was this post with some code: http://www.mikeperham.com/2010/03/30/using-activerecord-with-eventmachine/. You might find it useful to take a look at "em-synchrony": https://github.com/igrigorik/em-synchrony that has support for ActiveRecord.

Here is also my own question on a related subject: async requests using sinatra streaming API There I use Sinatra's streaming API to implement asynchronous request processing.

I personally would use direct DB access from my Sinatra app. That is what I always do. ActiveRecord is too heavy for me.

Community
  • 1
  • 1
akonsu
  • 28,824
  • 33
  • 119
  • 194
  • Thanks for the detailed response. What do you mean y direct DB access? Do you mean use the mysql2 gem and pass in raw queries? – 0xSina May 25 '13 at 04:49
  • here is a post about `EM.Defer`: http://stackoverflow.com/questions/10881594/why-sinatra-request-takes-em-thread?rq=1 – akonsu May 25 '13 at 05:00
0

Yes, it does block. If you are on Mysql you can make requests using mysql2 gem, it supports async requests. https://github.com/brianmario/mysql2

Sergii Mostovyi
  • 1,361
  • 1
  • 15
  • 19