Skip to content

Commit

Permalink
Exponential backoff for websocket reconnect
Browse files Browse the repository at this point in the history
  • Loading branch information
Gegy committed Nov 19, 2024
1 parent 83798a0 commit b6ec4e6
Showing 1 changed file with 7 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/main/java/com/lovetropics/lib/backend/BackendProxy.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@

public final class BackendProxy implements BackendConnection {
private static final Logger LOGGER = LogManager.getLogger(BackendProxy.class);
private static final long RECONNECT_INTERVAL_MS = 10 * 1000;
private static final long BASE_RECONNECT_INTERVAL_MS = 10 * 1000;
private static final long MAX_RECONNECT_INTERVAL_MS = 5 * 60 * 1000;
private static final long PING_INTERVAL_MS = 2 * 1000;

private final Supplier<URI> address;
Expand All @@ -22,6 +23,8 @@ public final class BackendProxy implements BackendConnection {
private long lastConnectTime;
private long lastPingTime;

private long reconnectIntervalMs = BASE_RECONNECT_INTERVAL_MS;

public BackendProxy(Supplier<URI> address, BackendConnection.Handler handler) {
this.address = address;
this.receiver = new Handler(handler);
Expand Down Expand Up @@ -51,7 +54,7 @@ private void tickConnected(BackendWebSocketConnection connection, long time) {
}

private void tickDisconnected(long time) {
if (time - this.lastConnectTime > RECONNECT_INTERVAL_MS) {
if (time - this.lastConnectTime > reconnectIntervalMs) {
this.initiateConnection();
}
}
Expand All @@ -78,11 +81,13 @@ private void onConnectionOpen(BackendWebSocketConnection connection) {
LOGGER.info("Successfully opened backend connection to {}", this.address);
this.connection = connection;
this.connecting = false;
this.reconnectIntervalMs = BASE_RECONNECT_INTERVAL_MS;
}

private void onConnectionError(Throwable throwable) {
LOGGER.error("Failed to open backend connection to {}", this.address, throwable);
this.closeConnection();
this.reconnectIntervalMs = Math.min(this.reconnectIntervalMs * 2, MAX_RECONNECT_INTERVAL_MS);
}

private void closeConnection() {
Expand Down

0 comments on commit b6ec4e6

Please sign in to comment.