0

Just for context, what I have is a relatively high throughput websocket implementation. Messages are sent through an open websocket from server to server. However, when a connection is lost we need to queue messages until the connection is regained. At this point we don't care much for persistence, in that if the server were to crash we don't need to have a backup of the messages. We also don't care much for the order of the messages.

So what I have so far is similar to the following:

function sendPayload( payload ) {
  var self = this;
  if ( self._state !== states.connected ) {
    // Queue until connected
    setImmediate( sendPayload.bind( self, payload ) );
  }
  else {
    self._wsClient.send( payload );
  }
}

The above has caused some odd looks from peers so I wanted to run it by you all. I was hoping to avoid managing an actual queue (populating an array etc.) and figured this was a quick and easy way to keep messages on hold until the connection is established, and quickly send them once it has.

Some have suggested that using setTimeout(fn, 0) might be better but didn't really provide much detail as to why. In this sense I don't think there would be much relevant difference between them, given my requirements.

Is one of the above a better approach than the other, or should I be doing this entirely differently?

Mitch
  • 291
  • 2
  • 17
  • Related: http://stackoverflow.com/questions/24117267/nodejs-settimeoutfn-0-vs-setimmediatefn – T.J. Crowder Dec 09 '16 at 12:24
  • 2
    The odd look you'd get from me (in a very mild way :-) ) would be that this is very nearly a busy-wait, making the server work far harder than necessary. `setImmediate` schedules the callback *very* proactively. (Also, that code doesn't need `self`.) So you'll be pegging the CPU while waiting for the connection to reestablish, which seems unnecessary and mildly counter-productive. `setTimeout` would be a bit slower, and so probably peg less, but queuing up the calls (e.g, in an array) and then firing them off when you *know* the connection has been reestablished seems better. – T.J. Crowder Dec 09 '16 at 12:28
  • So would a better approach be to store an array and instead of setImmediate as I have above, I push the payload onto the array. Then when I get a connected event I then just flush the array? That might be a pretty simple alternative that is less busy as you say. – Mitch Dec 09 '16 at 13:42
  • 1
    I think unless there's some other design constraint, that's what I'd do, yeah. And flushing the array is *really* simple: `theArray.forEach(this.sendPayload, this); theArray = [];` :-) – T.J. Crowder Dec 09 '16 at 13:46

0 Answers0