Add jitter to reconnect intervals.

This prevents all servers from reconnecting at the same time in case of network
interruptions or service restarts.
This commit is contained in:
Joachim Bauch 2025-05-07 11:18:52 +02:00
commit e0e6cb6e9d
No known key found for this signature in database
GPG key ID: 77C1D22D53E15F02
3 changed files with 12 additions and 4 deletions

View file

@ -45,7 +45,7 @@ const (
screenPublisherUserId = 2
initialReconnectInterval = 1 * time.Second
maxReconnectInterval = 32 * time.Second
maxReconnectInterval = 16 * time.Second
)
var (

View file

@ -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) {

View file

@ -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) {