3

I've made a application which use the Live method in Rails 4. However when I use it every refresh keeps taking one more connection until it reached the maximum of connections to the DB and then just hangs and loads forever.

What can I do to ensure that the connection is brought down when a user refreshes the site or decides to leave it?

This is my setup:

  def events
    response.headers["Content-Type"] = "text/event-stream"
    redis = Redis.new
    redis.psubscribe("participants.*") do |on|
      on.pmessage do |pattern, event, data|
        response.stream.write("event: #{event}\n")
        response.stream.write("data: #{data}\n\n")
      end
    end
  rescue IOError
    logger.info "Stream closed"
  ensure
    redis.quit
    response.stream.close
  end

I use Nginx, with Rainbows! on Ubuntu 10.04. Ruby 2.0.0-p195 Postgresql Rails 4

Philip
  • 6,827
  • 13
  • 75
  • 104

1 Answers1

0

So if you were doing that logic in a thread you created yourself, my answer would be, wrap everything in:

def events
  ActiveRecord::Base.connection_pool.with_connection do
    response.headers[etc
    #..
  end
end

Now, you are not making your own thread. Based on your symptoms, I suspect that may solve your problem anyway, it would be interesting to see.

However, it probably shouldn't be necessary since ActionController::Live is an official supported part of Rails, and the documentation and examples do not say you should have to do the with_connection thing. I am not familiar with ActionController::Live myself; it sounds like it might possibly be a bug. You might want to file with Rails issue tracker, after creating an as-small-as-possible application that demonstrates the problem.

I suspect there is more going on in your app than you are showing us -- the method you showed us doesn't use ActiveRecord at all, so there's no reason it would be taking any database connections at all. Or wait, by 'database connections' do you actually mean Redis? If so then ignore this entire answer, as I was assuming ActiveRecord. I have no experience with Redis either, but if by 'database connections' you mean Redis, then it's a Redis issue, and you might want to try filing an issue on the Redis issue tracker. Or, definitely, at least tagging this question "redis" so someone that knows redis might see it.

jrochkind
  • 22,799
  • 12
  • 59
  • 74