How to Handle WebSocket Reconnection on the Client Side

Web
Use an exponential backoff loop with jitter to safely retry WebSocket connections on the client side until success or a retry limit is reached.

Implement an exponential backoff loop in your WebSocket client that attempts to reconnect when the connection closes or errors out. This pattern waits for a random duration before retrying to prevent thundering herd issues and respects a maximum retry limit.

func connectWithRetry(ctx context.Context, url string, maxRetries int) error {
	var lastErr error
	for i := 0; i < maxRetries; i++ {
		conn, _, err := websocket.DialContext(ctx, url, nil)
		if err == nil {
			// Connection successful; start your message loop here
			return nil
		}
		lastErr = err
		// Exponential backoff with jitter: 2^i seconds + random milliseconds
		backoff := time.Duration(1<<uint(i)) * time.Second
		jitter := time.Duration(rand.Intn(1000)) * time.Millisecond
		select {
		case <-time.After(backoff + jitter):
		case <-ctx.Done():
			return ctx.Err()
		}
	}
	return fmt.Errorf("failed after %d attempts: %w", maxRetries, lastErr)
}