Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change ping interval in action cable rails

I'm using ActionCable and receiving pings from server after each 3 seconds interval (mentioned in the ActionCable library). My question is: How can I change the ping interval at the time of subscription?

Any idea?

like image 428
faisal bhatti Avatar asked May 20 '16 09:05

faisal bhatti


2 Answers

Expanding on @BoraMa's answer:

You can override the constant on the backend side like this:

# config/initializers/action_cable.rb
module ActionCable
  module Server
    module Connections
      BEAT_INTERVAL = 5
    end
  end
end

On the client side, you also need to override the value:

// this should be after //= require action_cable
// but before any App.cable.subscriptions.create call
// the value here *must* be 2 times the backend's value
ActionCable.ConnectionMonitor.staleThreshold = 10;

Please note that this approach is generally a really bad idea: messing with internal variables is one of the direct ways to bugs and issues.

In fact, ruby will even warn you:

config/initializers/action_cable.rb:7: warning: already initialized constant ActionCable::Server::Connections::BEAT_INTERVAL

Use this only if you know what you're doing.

like image 95
David Avatar answered Nov 01 '22 15:11

David


Interestingly, as of Rails 5.0.0.rc1 it seems that you can't configure the ping interval. It is defined as a constant in the ActionCable::Server::Connections module.

You could probably redefine this constant in an initializer to make the server send pings in different intervals but this would still not help you in the end because the client code that receives the pings also has a statically defined timeout (set for 6 seconds, i.e. two pings missed from the server). When it reaches the 6 seconds timeout without a ping from the server, it tries to reconnect. And I am unsure how you'd be able to override this constant in the Javascript client code.

Judging from this github issue there is some related debate ongoing about possible ways to improve pings behavior to be more useful, e.g. by taking into account the network latency.

But in essence, the interval is not configurable at the moment and unless you wanted a ping interval smaller than 3 seconds, I can see no easy way to override it in Rails now.

like image 3
Matouš Borák Avatar answered Nov 01 '22 13:11

Matouš Borák