I need to make realtime updates for all subscribers. After creating new record i need to publish it for all subscribers.
I found a solution using postgre listen/notify
def index response.headers['Content-Type'] = 'text/event-stream' sse = SSE.new(response.stream) begin Comment.on_change do |data| sse.write(data) end rescue IOError # Client Disconnected ensure sse.close end render nothing: true end
[...] after_create :notify_comment_added [...] private def notify_comment_added Comment.connection.execute "NOTIFY comments, 'data'" end
class << self def on_change Comment.connection.execute "LISTEN comments" loop do Comment.connection.raw_connection.wait_for_notify do |event, pid, comment| yield comment end end ensure Comment.connection.execute "UNLISTEN comments" end end
Every listeners occupies a connection to db, and after some clients its reach maximum and i got ActiveRecord timeout
it works only with config.cache_classes = true and config.eager_load = true otherwise servers froze on 1-2nd execution of controller. And its a big pain to restart server after every small change.
Does rails have any another solutions to perform this task?