WebSockets

Building a Reliable WebSocket Reconnection Manager in Flutter

By Pawan Kumawat • Published Jan 20, 2026 • 12 min read

1. The Problem with Raw WebSocket Connections

On mobile devices, socket connections drop frequently due to cell tower switches, background app pauses, or temporary tunnel drops. If a raw WebSocket connection closes, incoming events stop immediately without notifying UI screens unless an explicit reconnection loop is active.

2. Exponential Backoff Strategy

Immediately retrying a dropped socket in a tight loop floods the server and drains mobile battery. Instead, we use an exponential backoff timer with jitter: after each failed attempt, the waiting delay doubles (e.g. 1s, 2s, 4s, 8s, up to a maximum cap of 30 seconds).

reconnection_manager.dart
import 'dart:async';
import 'dart:math';
import 'package:web_socket_channel/web_socket_channel.dart';

enum SocketState { disconnected, connecting, connected, error }

class ResilientWebSocketManager {
  final String serverUrl;
  WebSocketChannel? _channel;
  Timer? _reconnectTimer;

  int _attempt = 0;
  final int _maxAttempt = 10;
  final int _baseDelaySeconds = 2;
  final int _maxDelaySeconds = 30;

  final StreamController<SocketState> _stateController = StreamController.broadcast();
  Stream<SocketState> get stateStream => _stateController.stream;

  ResilientWebSocketManager({required this.serverUrl});

  void connect() {
    if (_channel != null) return;

    _stateController.add(SocketState.connecting);
    print("Initiating socket connection... Attempt: $_attempt");

    try {
      _channel = WebSocketChannel.connect(Uri.parse(serverUrl));
      _stateController.add(SocketState.connected);
      _attempt = 0; // Reset attempts on successful connection

      _channel!.stream.listen(
        (data) {
          // Handle incoming socket payloads
        },
        onError: (err) {
          _handleDisconnect();
        },
        onDone: () {
          _handleDisconnect();
        },
      );
    } catch (e) {
      _handleDisconnect();
    }
  }

  void _handleDisconnect() {
    _channel = null;
    _stateController.add(SocketState.disconnected);

    if (_attempt < _maxAttempt) {
      _attempt++;
      // Calculate exponential backoff delay: min(maxDelay, base * 2^(attempt-1))
      final int delay = min(_maxDelaySeconds, _baseDelaySeconds * pow(2, _attempt - 1).toInt());
      print("Socket disconnected. Retrying in $delay seconds...");

      _reconnectTimer?.cancel();
      _reconnectTimer = Timer(Duration(seconds: delay), () {
        connect();
      });
    } else {
      _stateController.add(SocketState.error);
      print("Maximum reconnection attempts reached.");
    }
  }

  void dispose() {
    _reconnectTimer?.cancel();
    _channel?.sink.close();
    _stateController.close();
  }
}

3. Mobile Lifecycle Handling

Combine your socket manager with Flutter's `WidgetsBindingObserver` to disconnect sockets when the app goes into background (`AppLifecycleState.paused`) and resume when foregrounded (`AppLifecycleState.resumed`).

4. Conclusion

An exponential backoff reconnection manager guarantees network resilience across unstable mobile data connections.

← Back to Blog Index