Skip to content

Commit 806eb7a

Browse files
committed
randomize socket.io reconnect delays +/-50%
To prevent a "thundering herd" of clients all reconnecting on the same schedule after a server-side outage, randomize each reconnect attempt's delay by +/-50%
1 parent bf781c7 commit 806eb7a

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

AndroidAsync/src/com/koushikdutta/async/http/socketio/SocketIOConnection.java

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -217,14 +217,23 @@ private void delayReconnect() {
217217
public void run() {
218218
reconnect(null);
219219
}
220-
}, reconnectDelay);
220+
}, nextReconnectDelay(reconnectDelay));
221221

222222
reconnectDelay = reconnectDelay * 2;
223223
if (request.config.reconnectDelayMax > 0L) {
224224
reconnectDelay = Math.min(reconnectDelay, request.config.reconnectDelayMax);
225225
}
226226
}
227227

228+
private long nextReconnectDelay(long targetDelay) {
229+
if (targetDelay < 2L || targetDelay > (Long.MAX_VALUE >> 1) ||
230+
!request.config.randomizeReconnectDelay)
231+
{
232+
return targetDelay;
233+
}
234+
return (targetDelay >> 1) + (long) (targetDelay * Math.random());
235+
}
236+
228237
private void reportDisconnect(final Exception ex) {
229238
if (ex != null) {
230239
request.loge("socket.io disconnected", ex);

AndroidAsync/src/com/koushikdutta/async/http/socketio/SocketIORequest.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,14 @@ public SocketIORequest(String uri, String endpoint, String query, Config config)
4040
}
4141

4242
public static class Config {
43+
boolean randomizeReconnectDelay = false;
44+
public void setRandomizeReconnectDelay(boolean randomizeReconnectDelay) {
45+
this.randomizeReconnectDelay = randomizeReconnectDelay;
46+
}
47+
public boolean isRandomizeReconnectDelay() {
48+
return randomizeReconnectDelay;
49+
}
50+
4351
long reconnectDelay = 1000L;
4452
public void setReconnectDelay(long reconnectDelay) {
4553
if (reconnectDelay < 0L) {

0 commit comments

Comments
 (0)