Sub topic 9
Setting deadlines with timeout
This chapter assumes you can write async functions and use await, and that you know how try/catch works with awaited Futures. If those feel shaky, review the chapters on async functions and error handling first.
A Future that never completes is a quiet bug. A network request to a dead server, a socket that never answers, or a Completer that nobody completes will leave your code waiting forever. Future.timeout puts an upper limit on that wait.
What timeout does
timeout is a method on Future<T>. It returns a new Future that completes with whichever happens first:
- The original Future completes, with a value or an error. The new Future completes the same way.
- The duration passes. The new Future completes with a
TimeoutException, or with the result of anonTimeoutcallback if you supplied one.
import 'dart:async';
Future<String> slowOperation() =>
Future.delayed(const Duration(seconds: 5), () => 'finished');
Future<void> main() async {
try {
final result = await slowOperation().timeout(const Duration(seconds: 1));
print(result);
} on TimeoutException {
print('timed out');
}
}After about one second this prints timed out. Note the import 'dart:async'. TimeoutException and Completer live in that library, and your code won't compile without the import unless another import re-exports it.
Reading a TimeoutException
TimeoutException has two useful properties: message (a nullable String) and duration (a nullable Duration). When timeout creates the exception, the message is Future not completed and the duration is the one you passed.
import 'dart:async';
Future<void> main() async {
try {
await Completer<void>().future.timeout(const Duration(milliseconds: 200));
} on TimeoutException catch (e) {
print(e);
print(e.duration);
}
}The first line prints TimeoutException after 0:00:00.200000: Future not completed. The second prints 0:00:00.200000. The Completer here is never completed, so the Future would wait forever without the timeout.
Catch TimeoutException with on TimeoutException, not a bare catch. A bare catch would also swallow unrelated errors, such as a FormatException from the operation itself, and you would report them to the user as "timed out".
Supplying a fallback with onTimeout
The optional named parameter onTimeout is a function with no arguments. If the timer wins, timeout calls it and completes the result Future with whatever it returns. No exception is thrown.
Future<String> fetchProfile() =>
Future.delayed(const Duration(seconds: 5), () => 'Ada');
Future<void> main() async {
final name = await fetchProfile().timeout(
const Duration(seconds: 1),
onTimeout: () => 'guest',
);
print(name);
}This prints guest after one second.
The callback can do three things:
- Return a value of the Future's type, or a Future of that type. The type is
FutureOr<T>. - Throw. The result Future then completes with your error, for example a domain-specific
ServiceUnavailableexception that is easier to handle than a genericTimeoutException. - Do a side effect first, such as logging, and then return or throw.
| Situation | Without onTimeout | With onTimeout |
|---|---|---|
| Original Future finishes in time | Value or error passes through | Value or error passes through |
| Deadline passes | `TimeoutException` | Return value of `onTimeout`, or whatever it throws |
| Caller needs to know a timeout happened | Catch `TimeoutException` | Must signal it yourself, for example with a sentinel value |
The last row is a real trade-off. A fallback hides the timeout from the caller. If 'guest' is a legitimate name, you can't tell a timeout from a real answer. When the caller should react differently, for example by showing a retry button, let the exception propagate instead.
Timeout does not cancel the work
This is the most important edge case in the chapter. A Dart Future has no cancel operation. timeout stops you from waiting, but the operation underneath keeps running.
import 'dart:async';
Future<void> work() async {
await Future<void>.delayed(const Duration(seconds: 2));
print('work finished anyway');
}
Future<void> main() async {
try {
await work().timeout(const Duration(milliseconds: 500));
} on TimeoutException {
print('gave up');
}
}The output is:
gave up
work finished anywayThe second line appears about 1.5 seconds after the first. The program does not exit between them, because a pending timer keeps the process alive. In a real application the leftover work could be an HTTP request still downloading, a database write still in progress, or a loop still consuming CPU.
Three consequences follow:
- Side effects still happen. If the operation writes to a database or sends a payment, the timeout does not undo it. Treat a timed-out operation as "outcome unknown", not "failed".
- The late result is discarded. When the original Future finishes after the deadline, the timed-out Future ignores its value. A late error is also ignored, so it does not become an uncaught error in your zone.
- Resources are not released. You must release them yourself.
Cooperative cancellation
If the operation is yours, you can make it stoppable. Pass in a flag that it checks between steps, and set the flag when the timeout fires.
import 'dart:async';
class Cancellation {
bool isCancelled = false;
}
Future<int> countSlowly(Cancellation cancellation) async {
var n = 0;
while (n < 10 && !cancellation.isCancelled) {
await Future<void>.delayed(const Duration(milliseconds: 200));
n++;
}
return n;
}
Future<void> main() async {
final cancellation = Cancellation();
try {
final n = await countSlowly(cancellation)
.timeout(const Duration(seconds: 1));
print('counted to $n');
} on TimeoutException {
cancellation.isCancelled = true;
print('timed out, asked the loop to stop');
}
}After one second the program prints timed out, asked the loop to stop. The loop sees the flag at its next check and exits within about 200 ms, so the process ends promptly instead of counting to ten.
Many libraries offer a stronger form of this. package:http clients can be closed, sockets can be destroyed, and dart:io HttpClient has its own connectionTimeout. Prefer those when they exist, because they release the underlying resource. Use Future.timeout as the outer safety net.
When the clock starts
The timer starts when you call .timeout(...), not when the Future was created. Compare these two:
import 'dart:async';
Future<void> main() async {
final sw = Stopwatch()..start();
final pending = Future.delayed(const Duration(seconds: 2), () => 'done');
await Future<void>.delayed(const Duration(seconds: 1));
try {
await pending.timeout(const Duration(milliseconds: 1500));
print('finished at ${sw.elapsedMilliseconds ~/ 100} tenths of a second');
} on TimeoutException {
print('timed out');
}
}The pending Future is two seconds from completion. One second has already passed when timeout is attached, so only one second remains, which fits inside the 1.5 second budget. The program prints finished at 20 tenths of a second. If you had attached a 1500 ms timeout at creation, it would have timed out.
Keep this in mind when you place the call. Attach timeout at the point where you start the operation, so the deadline means what you think it means.
Timeouts with several Futures
There are two common intentions, and they need different code.
A deadline per operation. Attach timeout to each Future before passing them to Future.wait. Each one can fall back independently:
import 'dart:async';
Future<String> fetch(String name, int ms) =>
Future.delayed(Duration(milliseconds: ms), () => name);
Future<void> main() async {
const limit = Duration(milliseconds: 300);
final results = await Future.wait([
fetch('a', 100).timeout(limit, onTimeout: () => 'a-fallback'),
fetch('b', 800).timeout(limit, onTimeout: () => 'b-fallback'),
]);
print(results);
}The output is [a, b-fallback] after about 300 ms.
One deadline for the whole group. Put the timeout on the Future that Future.wait returns:
import 'dart:async';
Future<String> fetch(String name, int ms) =>
Future.delayed(Duration(milliseconds: ms), () => name);
Future<void> main() async {
try {
final results = await Future.wait([
fetch('a', 100),
fetch('b', 800),
]).timeout(const Duration(milliseconds: 300));
print(results);
} on TimeoutException {
print('the batch took too long');
}
}Here you lose partial results. The a value arrived in time but is unreachable, because Future.wait produces its list only when every Future has completed. If you need partial results, use per-operation timeouts.
For a sequence of awaited steps that must share one budget, a timeout on each step gives each step its own full budget, so the total can be many times the limit. Wrap the whole sequence in an async function and put one timeout on the call to it:
import 'dart:async';
Future<String> checkout() async {
await Future<void>.delayed(const Duration(milliseconds: 400));
await Future<void>.delayed(const Duration(milliseconds: 400));
return 'order placed';
}
Future<void> main() async {
try {
print(await checkout().timeout(const Duration(milliseconds: 600)));
} on TimeoutException {
print('checkout exceeded its overall budget');
}
}Each step is well under 600 ms, but together they need 800 ms, so the overall deadline fires.
Pitfalls specific to timeout
- Returning the Future inside try.
return fetch().timeout(limit);inside atryin anasyncfunction passes the failing Future out without running yourcatch. Writereturn await fetch().timeout(limit);, as covered in the pitfalls chapter. - Choosing a type-unsafe fallback.
onTimeoutmust return something compatible withT. For aFuture<int>you can't return'n/a'. Use a nullable type,Future<int?>, if "no value" is a legitimate result. - Retrying without idempotence. After a timeout, retrying a non-idempotent request such as "create order" can run it twice, because the first attempt may still be in flight.
- Picking one number for every case. Timeouts that are too short cause spurious failures on slow networks. Timeouts that are too long make the app seem frozen. Choose them per operation and make them configurable.
- Forgetting streams.
Streamhas its owntimeout. It limits the gap between events, not the total duration, and by default it adds aTimeoutExceptionto the stream when the gap is exceeded.
Exercise
A function calls await saveOrder(order).timeout(const Duration(seconds: 2)). The call throws a TimeoutException, and the user taps "Retry", which calls it again. What risk does this create, and how would you reduce it?
Show answer
The first saveOrder is not cancelled by the timeout, so it may still complete on the server. The retry could then create a duplicate order. Reduce the risk by making the operation idempotent, for example by sending a client-generated order ID that the server uses to reject duplicates, or by checking whether the order exists before retrying.
Exercise
Write a Dart function Future<int> withFallback(Future<int> future) that returns the future's result, or -1 if it takes longer than 500 ms. Then explain why -1 may be a poor choice and what you could use instead.
Show answer
Implementation: Future<int> withFallback(Future<int> future) => future.timeout(const Duration(milliseconds: 500), onTimeout: () => -1);. The value -1 can be confused with a real result, and the caller can't tell that a timeout happened. A better design returns Future<int?> and uses null for the timeout, or lets the TimeoutException propagate so the caller handles it explicitly.