Sub topic 8
Timeouts and retrying safely
This chapter assumes you know Dart classes, Future, async and await, Flutter’s widget lifecycle, and the http package. You also need to know how to inspect an HTTP status code.
A network request can fail even when your code is correct. The server may be slow, the device may lose connectivity, or a gateway may return a temporary error. A timeout stops your app from waiting forever. A retry gives a temporary failure another chance.
Set a timeout for every attempt
A timeout is a limit on how long an asynchronous operation may take. The http package does not automatically choose a timeout for your request. Use Future.timeout:
final response = await client
.get(uri)
.timeout(const Duration(seconds: 10));This throws TimeoutException when no response arrives before the limit. The timeout applies to this attempt only. If you retry three times, the total operation can take longer than ten seconds.
A retry policy should also have a maximum number of attempts. Three total attempts is a reasonable starting point for a read request.
Retry only temporary failures
Do not retry every error. A 401 Unauthorized response will not become valid because you send it again. A 404 Not Found response usually needs a different URL.
These failures are commonly temporary:
| Failure | Usually retry? | Reason |
|---|---|---|
| Timeout or connection failure | Yes | The network may recover |
| 408, 429, 500, 502, 503, 504 | Yes | The server or gateway may recover |
| 400, 401, 403, 404 | No | The request usually needs correction |
The HTTP method also matters. Repeating a GET is normally safe because it reads data. Repeating a POST can create duplicate resources. Retry a POST only when the API documents idempotency or supports an idempotency key, such as Idempotency-Key: order-123.
Use backoff and jitter
Sending retries immediately can overload a recovering server. Exponential backoff increases the delay after each failed attempt. Jitter adds a small random amount so many clients do not retry at exactly the same time.
import 'dart:async';
import 'dart:math';
import 'package:http/http.dart' as http;
class RetryPolicy {
const RetryPolicy({
this.maxAttempts = 3,
this.attemptTimeout = const Duration(seconds: 5),
this.initialDelay = const Duration(milliseconds: 300),
});
final int maxAttempts;
final Duration attemptTimeout;
final Duration initialDelay;
bool shouldRetryStatus(int statusCode) =>
statusCode == 408 ||
statusCode == 429 ||
statusCode == 500 ||
statusCode == 502 ||
statusCode == 503 ||
statusCode == 504;
Duration delayFor(int retryNumber, Random random) {
final exponential =
initialDelay.inMilliseconds * pow(2, retryNumber - 1).toInt();
final jitterLimit = max(1, exponential ~/ 2);
return Duration(
milliseconds: exponential + random.nextInt(jitterLimit),
);
}
}
Future<http.Response> getWithRetry({
required http.Client client,
required Uri uri,
RetryPolicy policy = const RetryPolicy(),
}) async {
final random = Random();
Object? lastError;
for (var attempt = 1; attempt <= policy.maxAttempts; attempt++) {
try {
final response = await client
.get(uri, headers: {'Accept': 'application/json'})
.timeout(policy.attemptTimeout);
if (!policy.shouldRetryStatus(response.statusCode) ||
attempt == policy.maxAttempts) {
return response;
}
} on TimeoutException catch (error) {
lastError = error;
} on http.ClientException catch (error) {
lastError = error;
}
if (attempt < policy.maxAttempts) {
await Future<void>.delayed(policy.delayFor(attempt, random));
}
}
throw lastError ?? StateError('Request failed without a response');
}maxAttempts includes the first request. The code retries timeouts, connection failures, and selected server statuses. In production, inspect a Retry-After response header for 429 and 503, and prefer that server-provided delay when it is valid.
Understand the request flow
Exercise
Why should a client avoid automatically retrying every POST request?
Show answer
Repeating a POST may create the same resource more than once unless the server provides an idempotency guarantee or an idempotency key.