Back to results for “Resilience”
Flutter › Networking with HTTP & Dio

How can you properly implement an effective retry strategy with exponential backoff for a genuinely failed network request, meaningfully improving your app's own overall resilience against genuinely temporary, transient network issues?

Advanced

Answer

An effective retry strategy properly retries a genuinely failed request automatically a specific limited number of times, gradually and progressively increasing the delay between each successive retry attempt, commonly referred to as exponential backoff, rather than either giving up entirely after just one single failed attempt or aggressively retrying immediately and repeatedly without any meaningful delay whatsoever, and this particular approach meaningfully improves overall resilience against genuinely temporary transient issues, such as a brief momentary network blip, while still properly avoiding overwhelming an already genuinely struggling backend server with an excessive flood of rapid repeated retry requests.
Future<Response> fetchWithRetry(String url, {int retries = 3}) async {
  for (int i = 0; i < retries; i++) {
    try {
      return await dio.get(url);
    } catch (e) {
      if (i == retries - 1) rethrow;
      await Future.delayed(Duration(seconds: pow(2, i).toInt()));
    }
  }
  throw Exception('Failed after $retries attempts');
}
Real-world example A file syncing feature automatically retries a genuinely failed upload request up to three separate times with progressively and steadily increasing delay between each attempt, successfully completing that particular upload despite an initial brief momentary network interruption that would have otherwise completely failed the entire operation on the very first attempt alone.

Common follow-ups: What genuinely specific kinds of errors should actually genuinely be retried automatically, versus which ones genuinely should not be retried at all?;How do you actually properly and correctly implement a genuine maximum total retry time limit rather than simply a fixed specific number of attempts?