diff --git a/mcu_janus.go b/mcu_janus.go index ea08371..d90fd13 100644 --- a/mcu_janus.go +++ b/mcu_janus.go @@ -45,7 +45,7 @@ const ( screenPublisherUserId = 2 initialReconnectInterval = 1 * time.Second - maxReconnectInterval = 32 * time.Second + maxReconnectInterval = 16 * time.Second ) var ( diff --git a/mcu_proxy.go b/mcu_proxy.go index 04f9fd2..715535d 100644 --- a/mcu_proxy.go +++ b/mcu_proxy.go @@ -29,6 +29,7 @@ import ( "errors" "fmt" "log" + "math/rand/v2" "net" "net/http" "net/url" @@ -749,7 +750,10 @@ func (c *mcuProxyConnection) scheduleReconnect() { } interval := c.reconnectInterval.Load() - c.reconnectTimer.Reset(time.Duration(interval)) + // Prevent all servers from reconnecting at the same time in case of an + // interrupted connection to the proxy or a restart. + jitter := rand.Int64N(interval) - (interval / 2) + c.reconnectTimer.Reset(time.Duration(interval + jitter)) interval = interval * 2 if interval > int64(maxReconnectInterval) { diff --git a/proxy/proxy_remote.go b/proxy/proxy_remote.go index 0e5822f..b16ade2 100644 --- a/proxy/proxy_remote.go +++ b/proxy/proxy_remote.go @@ -28,6 +28,7 @@ import ( "encoding/json" "errors" "log" + "math/rand/v2" "net" "net/http" "net/url" @@ -44,7 +45,7 @@ import ( const ( initialReconnectInterval = 1 * time.Second - maxReconnectInterval = 32 * time.Second + maxReconnectInterval = 16 * time.Second // Time allowed to write a message to the peer. writeWait = 10 * time.Second @@ -170,7 +171,10 @@ func (c *RemoteConnection) scheduleReconnect() { c.close() interval := c.reconnectInterval.Load() - c.reconnectTimer.Reset(time.Duration(interval)) + // Prevent all servers from reconnecting at the same time in case of an + // interrupted connection to the proxy or a restart. + jitter := rand.Int64N(interval) - (interval / 2) + c.reconnectTimer.Reset(time.Duration(interval + jitter)) interval = interval * 2 if interval > int64(maxReconnectInterval) {