title: Strategies for multithreaded singleton object in Rails
body: <p>I have a compelling use case where notifications happen in realtime at the server level. I would like to push these events out over a websocket using Rails' ActionCable. <strong>How Can I reliably maintain a long-lived singleton object to react to and push server-level events?</strong></p>
  
  <ul>
  <li><p>I prototyped a Rails app using an object instantiated from a file in /app/lib that mixes in the <code>Singleton</code> module. Even with class caching, this was instantiated multiple times and occasionally garbage collected despite open sockets.</p></li>
  <li><p>Marking the event producer's <code>initialize</code> method private and writing a class-level instance method that checks <code>Thread.main[:event_provider]</code> for an instance works 95% in development, but I worry about what I don't know that I don't know about production. Very occasionally I get exceptions like "Expected x_y.rb to define constant XY" exceptions, which make me think there's a problem to this approach.</p></li>
  <li><p>The production server will ultimately serve a very small number of clients in an environment that demands 100% uptime. I can choose a server stack that makes sense.</p></li>
  </ul>
  
  <p>I'm hoping someone with knowledge of Rack and/or ActionCable can comment on reliable ways to serve events to a Rails application from within the server.</p>