Skip to content

Commit 2321afa

Browse files
authored
Add exponential reconnection backoff, solves #140 (#248)
1 parent 11e9e81 commit 2321afa

File tree

1 file changed

+14
-9
lines changed

1 file changed

+14
-9
lines changed

src/connection.js

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,8 @@ module.exports = class Connection extends EventEmitter {
4747
options = this.options;
4848

4949
this.auto_reconnect = options.auto_reconnect || false;
50-
this.auto_reconnect_wait = options.auto_reconnect_wait || 4000;
5150
this.auto_reconnect_max_retries = options.auto_reconnect_max_retries || 3;
51+
this.auto_reconnect_max_wait = options.auto_reconnect_max_wait || 300000;
5252

5353
if (this.transport) {
5454
this.clearTimers();
@@ -131,27 +131,32 @@ module.exports = class Connection extends EventEmitter {
131131
}
132132

133133
if (should_reconnect) {
134+
const reconnect_wait = that.calculateExponentialBackoff();
135+
134136
that.reconnect_attempts++;
135137
that.emit('reconnecting', {
136138
attempt: that.reconnect_attempts,
137139
max_retries: that.auto_reconnect_max_retries,
138-
wait: that.auto_reconnect_wait
140+
wait: reconnect_wait
139141
});
142+
143+
that.debugOut('Scheduling reconnect. Attempt: ' + that.reconnect_attempts + '/' + that.auto_reconnect_max_retries + ' Wait: ' + reconnect_wait + 'ms');
144+
that.setTimeout(() => that.connect(), reconnect_wait);
140145
} else {
141146
that.transport.removeAllListeners();
142147
that.emit('close', !!err);
143148
that.reconnect_attempts = 0;
144149
}
145-
146-
if (should_reconnect) {
147-
that.debugOut('Scheduling reconnect');
148-
that.setTimeout(function() {
149-
that.connect();
150-
}, that.auto_reconnect_wait);
151-
}
152150
}
153151
}
154152

153+
calculateExponentialBackoff() {
154+
const jitter = 1000 + Math.floor(Math.random() * 5000);
155+
const attempts = Math.min(this.reconnect_attempts, 30);
156+
const time = 1000 * Math.pow(2, attempts);
157+
return Math.min(time, this.auto_reconnect_max_wait) + jitter;
158+
}
159+
155160
addReadBuffer(line) {
156161
this.read_buffer.push(line);
157162
this.processReadBuffer();

0 commit comments

Comments
 (0)