Sub topic 13
Testing timeouts with paused time
Timeout code is hard to test with a real clock. A 30-second timeout makes the test take 30 seconds. A 50 ms timeout against a 40 ms operation makes the test flaky on a busy CI machine. Tokio solves this with a clock you can pause and move forward yourself.
This chapter assumes you have read the earlier chapters on timeout, select!, and cancellation by drop. You should be comfortable with #[tokio::test], tokio::spawn, and JoinHandle.
Why real time makes bad tests
A test for a timeout has to wait for the timeout. That causes three problems:
- Slow tests. Every timeout in the suite adds its full duration to the run.
- Flaky tests. A test that expects "the operation finishes at 100 ms and the deadline is 150 ms" depends on scheduler jitter.
- Untestable long durations. Nobody wants a test that waits for a 5-minute heartbeat.
Paused time removes the real clock from the picture. Tokio's timers read a clock that the test controls, so a 60-second sleep can finish in microseconds of real time.
Enabling the test clock
The pause API is behind the test-util Cargo feature. Enable it only for tests, using a dev-dependency entry.
[dependencies]
tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] }
[dev-dependencies]
tokio = { version = "1", features = ["test-util"] }Cargo merges the features of both entries when it builds tests. Your release build does not include the test utilities.
Starting a test with the clock paused
The simplest form is the start_paused option on the test macro. The runtime begins with the clock frozen.
use std::time::Duration;
use tokio::time::{sleep, timeout};
#[tokio::test(start_paused = true)]
async fn operation_times_out() {
let result = timeout(Duration::from_secs(1), sleep(Duration::from_secs(60))).await;
assert!(result.is_err());
}This test finishes immediately. The 60-second sleep never runs for 60 real seconds. Here is why.
Auto-advance: how the clock moves
While paused, the clock does not move on its own. But Tokio uses one rule to avoid hanging forever: when the runtime has nothing left to do, it jumps the clock forward to the next pending timer. This is called auto-advance.
In the test above, the test task awaits the timeout. The runtime has no other ready work, so it looks for the earliest timer. That timer is the 1-second timeout, so the clock jumps by 1 second and the timeout fires. The 60-second sleep is dropped, and the clock never reaches it.
Two consequences follow from this rule:
- Time only moves when every task is blocked. A task that is busy computing never lets the clock jump.
- Timers fire in deadline order, so the relative order of events in your code is preserved. Only the waiting is removed.
Checking how much time passed
Use tokio::time::Instant, not std::time::Instant. Only the Tokio type reads the paused clock.
use std::time::Duration;
use tokio::time::{sleep, timeout, Instant};
async fn slow_lookup(delay: Duration) -> u32 {
sleep(delay).await;
42
}
pub async fn lookup_with_deadline(delay: Duration) -> Option<u32> {
timeout(Duration::from_secs(2), slow_lookup(delay)).await.ok()
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test(start_paused = true)]
async fn returns_value_before_deadline() {
let result = lookup_with_deadline(Duration::from_secs(1)).await;
assert_eq!(result, Some(42));
}
#[tokio::test(start_paused = true)]
async fn gives_up_at_the_deadline() {
let start = Instant::now();
let result = lookup_with_deadline(Duration::from_secs(30)).await;
let elapsed = start.elapsed();
assert_eq!(result, None);
assert!(elapsed >= Duration::from_secs(2));
assert!(elapsed < Duration::from_secs(3));
}
}The second test checks that the call gave up at the 2-second deadline and not at the 30-second delay. The test asserts a range because timers have millisecond granularity. Avoid asserting exact equality on elapsed time.
Moving the clock by hand with advance
Auto-advance is convenient, but sometimes you want to check state at an exact moment. For that, call tokio::time::pause() and then tokio::time::advance(duration).
use std::time::Duration;
use tokio::task::yield_now;
use tokio::time::{advance, sleep};
#[tokio::test]
async fn advance_controls_the_clock() {
tokio::time::pause();
let handle = tokio::spawn(async {
sleep(Duration::from_secs(10)).await;
"done"
});
// Let the spawned task run far enough to register its sleep.
yield_now().await;
advance(Duration::from_secs(9)).await;
assert!(!handle.is_finished());
advance(Duration::from_secs(1)).await;
assert_eq!(handle.await.unwrap(), "done");
}The yield_now().await line matters. A spawned task does not run until the test task yields. A sleep computes its deadline when the task first polls it. Without the yield, advance(9s) would move the clock first, and the task would then start a fresh 10-second sleep from the new time. The assertions after it would give confusing results.
The advance call itself yields to the runtime after moving the clock. Timers that became due get their tasks woken and polled before advance returns.
Testing that cancellation really dropped the work
Paused time pairs well with the drop-based cleanup from earlier chapters. You can check that a timeout dropped the inner future by watching a drop guard flip a flag.
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc,
};
use std::time::Duration;
use tokio::time::{sleep, timeout};
struct Flag(Arc<AtomicBool>);
impl Drop for Flag {
fn drop(&mut self) {
self.0.store(true, Ordering::SeqCst);
}
}
#[tokio::test(start_paused = true)]
async fn timeout_drops_the_inner_future() {
let dropped = Arc::new(AtomicBool::new(false));
let flag = Flag(dropped.clone());
let work = async move {
let _flag = flag;
sleep(Duration::from_secs(60)).await;
};
let result = timeout(Duration::from_secs(1), work).await;
assert!(result.is_err());
assert!(dropped.load(Ordering::SeqCst));
}The assertion on dropped proves the future was dropped when the timeout fired. The test needs no real waiting and has no timing race.
What paused time cannot do
Paused time controls Tokio's clock and nothing else. Know these limits before you rely on it.
It requires a single-threaded runtime
pause and start_paused work only on the current-thread runtime. #[tokio::test] uses that runtime by default. If you ask for flavor = "multi_thread" and also pause the clock, the runtime panics.
Real I/O counts as idle
If a task waits on a real socket or file, the runtime has no ready tasks, so auto-advance runs. A timeout around real network I/O can then fire immediately, because the clock jumps to the deadline before the data arrives. In paused-time tests, replace real I/O with in-memory pieces such as tokio::io::duplex or channels.
Blocking code is not affected
std::thread::sleep blocks a real thread for real time and does not move the Tokio clock. A blocking call inside an async task also stops the runtime from becoming idle, so no auto-advance happens while it runs. This is the same reason blocking code ignores a timeout, as covered in the previous chapter. Paused time makes the problem less visible, not less real. A test with a paused clock will not catch it, so look for it in review.
Only Tokio's time types see the pause
std::time::Instant::now() and SystemTime::now() read the real clock. Code under test that measures durations with those types will not match your advance calls. Use tokio::time::Instant in code you intend to test this way.
A short checklist
- Enable
test-utilin dev-dependencies. - Use
#[tokio::test(start_paused = true)]for most timeout tests. - Read time with
tokio::time::Instantand assert on ranges. - Use
pauseandadvanceonly when you must inspect state at a specific moment, and callyield_nowfirst so spawned tasks register their timers. - Replace real I/O with in-memory substitutes.
Exercise
A test uses #[tokio::test(start_paused = true)] and wraps a TcpStream::connect to a real local server in timeout(Duration::from_secs(5), ...). The test reports a timeout even though the server answers in a few milliseconds. What is going on, and how would you fix the test?
Show answer
While the task waits for the real socket, the runtime has no ready tasks, so it counts as idle. Auto-advance then jumps the paused clock to the 5-second deadline, and the timeout fires before the connection completes. To fix it, remove real I/O from the test. Use an in-memory transport such as tokio::io::duplex, or a channel-based fake, so the operation completes through tasks and timers that the paused clock controls.
Exercise
In a test with tokio::time::pause(), you spawn a task that sleeps for 10 seconds, then immediately call advance(Duration::from_secs(10)).await and assert that the task finished. The assertion sometimes fails, or the task seems to need 10 more seconds. Why, and what is the minimal change?
Show answer
The spawned task has not run yet when advance moves the clock, so its sleep computes its deadline after the jump, from the new current time. The task then waits another 10 paused seconds. Add tokio::task::yield_now().await after tokio::spawn and before advance, so the task polls once and registers its timer at the original time.