WebSockets: add some jitter to retries.

If the websocket server gets restarted or goes down temporarily, we
don't want everyone to be retrying at exactly the same time even though
we have exponential backoff.
This commit is contained in:
Neil Williams
2014-02-27 11:15:59 -08:00
parent aa2e045b1a
commit 0de32efc29

View File

@@ -10,6 +10,7 @@ r.WebSocket = function (url) {
_.extend(r.WebSocket.prototype, Backbone.Events, {
_backoffTime: 2000,
_maximumRetries: 9,
_retryJitterAmount: 3000,
_connect: function () {
r.debug('websocket: connecting')
@@ -37,7 +38,9 @@ _.extend(r.WebSocket.prototype, Backbone.Events, {
_onClose: function (ev) {
if (this._connectionAttempts < this._maximumRetries) {
var delay = this._backoffTime * Math.pow(2, this._connectionAttempts)
var baseDelay = this._backoffTime * Math.pow(2, this._connectionAttempts),
jitter = (Math.random() * this._retryJitterAmount) - (this._retryJitterAmount / 2),
delay = Math.round(baseDelay + jitter)
r.debug('websocket: connection lost, reconnecting in ' + delay + 'ms')
this.trigger('reconnecting', delay)
setTimeout(_.bind(this._connect, this), delay)