Sub topic 8
Timeouts and retrying safely
This chapter assumes you can write async and await code, you have the http package in pubspec.yaml, and you know the ApiException pattern from the error-handling chapter. It covers what a timeout does, which failures are worth retrying, and how to retry without making things worse.
Why a request needs a deadline
Without a deadline, a request can wait for a very long time. A phone that moves between Wi-Fi and mobile data can leave a socket half open. A server under load can accept a connection and never answer. In both cases your FutureBuilder shows a spinner indefinitely.
A timeout turns "wait forever" into a failure that your UI can show. A retry then gives transient failures a second chance. The two work together, and each has traps.
What `Future.timeout` does
The simplest deadline is Future.timeout:
final response = await client
.get(uri)
.timeout(const Duration(seconds: 10));If the future has not completed after 10 seconds, timeout throws a TimeoutException. Be clear about what this does not do:
- It does not cancel the request. The socket stays open and the server may still process it. The response is simply discarded when it arrives.
- It covers the whole call, from connecting to receiving the response body. It cannot tell a slow connection from a slow download.
- You can pass
onTimeoutto return a fallback value instead of throwing. For network code, throwing is usually clearer.
Connection timeouts on `dart:io`
On mobile and desktop you can also set a connection timeout on the underlying HttpClient. It fails fast when the server cannot be reached, without limiting how long a slow response may take.
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:http/io_client.dart';
http.Client buildClient() {
final inner = HttpClient()
..connectionTimeout = const Duration(seconds: 5);
return IOClient(inner);
}IOClient is not available on the web, where the browser controls connections. Keep Future.timeout as the portable deadline and treat the connection timeout as an extra on dart:io platforms. Dio, covered later in this tutorial, offers separate connect, send and receive timeouts on every platform.
Which failures are worth retrying
Retrying a failure that will never succeed wastes battery and traffic, and can hammer a struggling server. Sort failures into two groups.
| Failure | Retry? | Reason |
|---|---|---|
| `TimeoutException` | Yes, if the request is safe to repeat | The network may have been briefly slow |
| `ClientException` (connection lost) | Yes, if safe to repeat | Often transient |
| 408 Request Timeout | Yes | The server gave up waiting for the request |
| 429 Too Many Requests | Yes, after waiting | The server asks you to slow down |
| 500, 502, 503, 504 | Yes | Server or gateway trouble, often temporary |
| 501 Not Implemented | No | The server will never support this |
| 400, 401, 403, 404, 422 | No | The request itself is wrong. Repeating it gives the same answer |
A 401 deserves a special note. Repeating the same request does not help, but refreshing the token and then repeating once can. That is a separate flow, usually handled in an interceptor.
Retrying only what is safe
An operation is idempotent if doing it several times has the same effect as doing it once. This decides whether a retry is safe.
- GET, PUT and DELETE are idempotent by definition in HTTP. Setting a post's title twice leaves the same title.
- POST is not. Retrying a POST that created a resource can create it twice, because a timeout does not tell you whether the first attempt reached the database.
- PATCH depends on the operation. "Set status to done" is safe. "Increment the counter" is not.
If you must retry a POST, ask the server for an idempotency key. The client generates a unique value once per logical operation, sends it in a header such as Idempotency-Key, and reuses the same value on every retry. A server that supports the header recognizes the repeat and returns the original result. Check the API's documentation first. Without server support, the header does nothing.
Backoff and jitter
If every client retries immediately, a briefly overloaded server receives a second wave right when it is weakest. Two techniques soften this:
- Exponential backoff: wait longer after each failure, for example 0.5 s, 1 s, 2 s.
- Jitter: pick a random delay up to that ceiling, so thousands of clients that failed together do not retry together.
Always cap the number of attempts. Three is a reasonable default for an interactive screen, because the user is waiting.
A retrying GET helper
This helper combines the pieces. The random and baseDelay parameters exist so tests can make it deterministic and fast.
import 'dart:async';
import 'dart:math';
import 'package:http/http.dart' as http;
class ApiException implements Exception {
const ApiException(this.message, {this.statusCode});
final String message;
final int? statusCode;
@override
String toString() => 'ApiException($statusCode): $message';
}
bool isRetryableStatus(int status) =>
status == 408 || status == 429 || (status >= 500 && status != 501);
Future<http.Response> getWithRetry(
http.Client client,
Uri uri, {
int maxAttempts = 3,
Duration timeout = const Duration(seconds: 10),
Duration baseDelay = const Duration(milliseconds: 500),
Random? random,
}) async {
final rng = random ?? Random();
for (var attempt = 1; ; attempt++) {
Duration? serverDelay;
try {
final response = await client.get(uri).timeout(timeout);
final status = response.statusCode;
if (status >= 200 && status < 300) {
return response;
}
if (!isRetryableStatus(status) || attempt >= maxAttempts) {
throw ApiException('Request failed', statusCode: status);
}
final seconds = int.tryParse(response.headers['retry-after'] ?? '');
if (seconds != null) {
serverDelay = Duration(seconds: min(seconds, 30));
}
} on TimeoutException {
if (attempt >= maxAttempts) {
throw const ApiException('The request timed out');
}
} on http.ClientException catch (e) {
if (attempt >= maxAttempts) {
throw ApiException('Connection problem: ${e.message}');
}
}
final ceiling = baseDelay * (1 << (attempt - 1));
final jittered =
Duration(milliseconds: rng.nextInt(ceiling.inMilliseconds + 1));
await Future<void>.delayed(serverDelay ?? jittered);
}
}Points worth noticing:
- The
ApiExceptionthrown for a non-retryable status is not caught by theonclauses below it, because it is neither aTimeoutExceptionnor aClientException. It leaves the function immediately. - A
Retry-Afterheader given in seconds takes priority over the computed delay. The value is capped at 30 seconds, so a bad header cannot freeze the screen. The header can also hold an HTTP date, which this helper ignores for simplicity.int.tryParsereturnsnullfor such values, and the jittered delay is used instead. - The delay is computed as
baseDelay * 2^(attempt-1), and the random pick is between zero and that ceiling. This is called full jitter. - Each attempt gets its own timeout, so the worst-case total is roughly
maxAttempts * timeoutplus the waits. With the defaults that can approach 30 seconds. For a screen the user is watching, lower the per-attempt timeout or the attempt count.
Using the package's `RetryClient`
The http package ships RetryClient in package:http/retry.dart, which wraps another client. By default it retries only on 503 and uses a delay that grows by a factor of 1.5. You can customize which responses and errors trigger a retry through its when and whenError callbacks. It is convenient, but it retries every method, including POST. If you use it, give it a when callback that checks response.request?.method, or use it only for read-only clients.
Testing retry logic
Retry code is easy to get wrong and slow to test against a real network. MockClient lets you script the failures. Passing Duration.zero as the base delay removes the waiting.
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
void main() {
test('retries a 503 and then succeeds', () async {
var calls = 0;
final client = MockClient((request) async {
calls++;
return calls < 3 ? http.Response('', 503) : http.Response('ok', 200);
});
final response = await getWithRetry(
client,
Uri.https('example.com', '/'),
baseDelay: Duration.zero,
);
expect(response.body, 'ok');
expect(calls, 3);
});
test('does not retry a 404', () async {
var calls = 0;
final client = MockClient((request) async {
calls++;
return http.Response('', 404);
});
await expectLater(
getWithRetry(client, Uri.https('example.com', '/'),
baseDelay: Duration.zero),
throwsA(isA<ApiException>()),
);
expect(calls, 1);
});
}Common mistakes
- Retrying inside the widget. Keep retry logic in the API layer, so each screen does not invent its own policy.
- Retrying without a limit, or with a fixed short delay. Both turn a brief outage into a flood of requests.
- Retrying every non-200 status. A 404 or 422 will fail the same way every time.
- Retrying POST without an idempotency key, which can create duplicate records.
- Creating a new
Futureinbuild. A retry loop inside aFutureBuilderwhose future is rebuilt on every frame multiplies requests. Create the future once, as shown in theFutureBuilderchapter. - Giving the user no way out. After the final failure, show the error with a "Try again" button that creates a fresh future.
Exercise
Your app calls POST /orders and the request times out after 10 seconds. A teammate suggests wrapping the call in the retry helper with three attempts. Why is that risky, and what would make it safe?
Show answer
A timeout does not show that the server failed. The first request may have created the order, so each retry could create a duplicate. It becomes safe if the client generates one idempotency key per order, sends it in a header such as Idempotency-Key on every attempt, and the server is documented to return the original result when it sees the same key again. Without server support, do not retry the POST. Show an error and let the user decide, or check whether the order exists with a GET first.
Exercise
In getWithRetry, the first attempt returns 429 with the header "Retry-After: 4", and the second attempt succeeds. What delay is used before the second attempt, and what would it be if the header were missing and baseDelay were 500 ms?
Show answer
With the header, the helper waits 4 seconds, because serverDelay takes priority and 4 is below the 30-second cap. Without it, the ceiling for attempt 1 is 500 ms * 2^0 = 500 ms, so the wait is a random value between 0 and 500 ms.