Testing Cancellation with Go's synctest Bubble: 5 Seconds in 0.00
A pool test that waits out a 5-second deadline takes 5 real seconds every run, and a slow suite pays that cost on every change. Go's synctest package runs the same test on a fake clock: the deadline fires at exactly 5 seconds of virtual time, the test reports 0.00 seconds, and the result is the same on every run. This guide builds that test around an errgroup pool, runs it on two Go toolchains, and spells out the limits of the bubble, because the bubble only helps when the code under test actually listens to the context.
Written November 7, 2026 · Tested with Go 1.25 · 14 min read
- The problem with a real deadline
- The pool under test
- The test inside the bubble
- How the bubble moves time
The problem with a real deadline
A worker pool that cancels slow work on a deadline is easy to write and awkward to test. The honest test sets a 5-second deadline, starts a slow worker, and waits. That test takes 5 real seconds, every time it runs. A suite with a dozen such tests takes a minute of waiting for a minute of nothing, and a developer who runs the suite ten times a day waits ten minutes for the same answer. The usual workaround is worse: shorten the deadline in the test to 50 milliseconds and hope the production value behaves the same way. It usually does, until the one time the timing differs and the test flakes on a busy machine.
The synctest package, in the standard library since Go 1.25, removes the wait. Its Test function runs a test inside a bubble with a fake clock. Time in the bubble moves only when every goroutine in the bubble is blocked, and it jumps straight to the next moment that wakes one up. A 5-second deadline fires after 5 seconds of virtual time and no real time at all. The test below runs in 0.00 seconds and asserts the exact virtual elapsed time, so a change in timing fails the test instead of passing quietly.
The pool under test
The pool is the same errgroup pool shape as the companion guide on the race detector, with one difference: each worker waits for a simulated latency instead of doing work. The function takes a context, a list of URLs, and a latency per URL, and runs at most two workers at once:
func FetchWithTimeout(ctx context.Context, urls []string, latencies []time.Duration) error {
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(2)
for i, u := range urls {
_ = u
lat := latencies[i]
g.Go(func() error {
select {
case <-time.After(lat):
return nil
case <-ctx.Done():
return ctx.Err()
}
})
}
return g.Wait()
}
Two details in this code carry the whole test. First, each worker selects on ctx.Done() alongside its timer, so a canceled context wakes the worker at once. A worker that slept with a plain time.Sleep and never looked at the context would keep sleeping until its own latency elapsed, and the deadline would change nothing. Cancellation is a signal, not an interruption. The pool has to listen for it. Second, the group comes from WithContext, so the first worker error cancels the derived context, and Wait returns that first error. The errgroup documentation states both rules: the derived context is canceled the first time a function passed to Go returns a non-nil error or the first time Wait returns, whichever comes first, and Wait returns the first non-nil error from the group.
The limit of 2 matters for reading the test below. Three workers are queued but only two start. The third starts only after one of the first two returns, and by then the context is already done, so it returns at once. The test still measures exactly 5 seconds of virtual time, because the third worker adds no waiting of its own.
The test inside the bubble
The test wraps the pool call in synctest.Test, sets a 5-second timeout on the test context, gives all three workers a 10-second latency, and asserts two things: the error is context.DeadlineExceeded, and the elapsed time is exactly 5 seconds:
func TestPoolCancelDeterministic(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
start := time.Now()
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
defer cancel()
urls := []string{"slow", "slow", "slow"}
lat := []time.Duration{10 * time.Second, 10 * time.Second, 10 * time.Second}
err := FetchWithTimeout(ctx, urls, lat)
elapsed := time.Since(start)
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("want DeadlineExceeded, got %v", err)
}
if elapsed != 5*time.Second {
t.Fatalf("want exactly 5s virtual elapsed, got %v", elapsed)
}
t.Logf("deadline fired at exactly %v virtual time", elapsed)
})
}
=== RUN TestPoolCancelDeterministic
pool_test.go:58: deadline fired at exactly 5s virtual time
--- PASS: TestPoolCancelDeterministic (0.00s)
PASS
ok syncpool 0.003s
The (0.00s) is the test's own reported duration, and the package line shows 0.003 to 0.004 seconds of real time for the whole package run. The 5 seconds exist only on the bubble clock. Nothing in the run waited 5 real seconds, and the log line is byte-identical across all 4 runs. A test that depends on real timing cannot promise that. This one can, because the clock only moves when the test says so.
How the bubble moves time
The synctest documentation describes the bubble in plain terms. Test runs a function in an isolated bubble, and any goroutine started inside the bubble belongs to it. Inside the bubble the time package uses a fake clock, each bubble has its own clock, and the clock starts at midnight UTC on 2000-01-01. Time advances only when every goroutine in the bubble is durably blocked, and then it jumps to the next time that wakes at least one goroutine.
Durably blocked has a precise meaning: a goroutine is durably blocked when it is blocked and can only be unblocked by another goroutine in the same bubble. The documentation lists the operations that count: a blocking send or receive on a channel created inside the bubble, a blocking select where every case is a channel created inside the bubble, sync.Cond.Wait, sync.WaitGroup.Wait when Add was called inside the bubble, and time.Sleep. Operations outside that list may block a goroutine but are not durably blocking, because something outside the bubble could unblock them. Locking a mutex, blocking on a network socket, and system calls are named explicitly as not durably blocking.
That list explains the trace of the test above. The three workers block in their select statements, one case on a timer created inside the bubble and one on the context's Done channel. The test goroutine blocks in Wait, which waits for the workers. Every goroutine is durably blocked, so the clock jumps to 5 seconds, the earliest pending wake-up, which is the context deadline. The deadline closes the Done channel, all three workers return ctx.Err(), Wait returns DeadlineExceeded, and the test measures exactly 5 seconds. The 10-second timers never fire. They are still pending when the test ends, and that is fine, because the test does not wait for them.
Two more rules from the documentation shape how tests are written. When every goroutine is durably blocked and there is no future wake-up time, Test panics with a deadlock instead of hanging. And Test waits for all goroutines in the bubble to exit before it returns, so a leaked worker fails the test rather than running on into the next one.
What the bubble does not fake
The fake clock covers the time package inside the bubble. It does not cover anything else, and the gaps decide whether a test belongs in a bubble at all.
First, time outside the bubble is real. A goroutine started before the test, a background task from another test, or a timer created outside the bubble all run on the real clock. The documentation warns against interacting with goroutines not started from within the test, and it states that operating on a bubbled channel, timer, or ticker from outside the bubble panics. The test must be self-contained: everything it touches starts inside the bubble.
Second, a real network read does not block durably. A worker that reads from a real network socket blocks on that socket read, which the documentation lists as not durably blocking, so the bubble never goes idle, the clock never advances, and the deadline never fires. The documentation's own HTTP example makes the point by building the test on an in-process fake connection instead of a loopback socket, with a comment that a real network read prevents a bubble from becoming idle. A pool test that fetches over a real network does not belong in a bubble. The fetch has to be faked, the way the latency here is faked with time.After.
Third, a mutex does not block durably either. A worker stuck waiting for a lock holds the bubble open the same way a network read does, and the clock stops. A pool that guards shared state with a mutex, as the fixed pool in the companion guide does, is fine inside a bubble as long as no worker actually waits on the lock while the clock needs to move. A contended lock in the middle of a timed test is a deadlock risk, not a timing risk.
Fourth, the bubble cannot make code listen. The deadline fires on schedule whether or not the workers notice. If a worker ignores the context and sleeps out its full latency, the test still passes its clock to 10 seconds and the assertion on exactly 5 seconds fails, which is the correct outcome: the test catches the missing ctx.Done() case instead of hiding it. The bubble tests the cancellation wiring, not the passage of time.
The race-detector sanity check
The same module carries the race-detector pair from the companion guide: a racy pool and a mutex-guarded fixed pool, each run over 50 fetch tasks with a limit of 8. The tests are short, and they run under -race on Go 1.27.3:
func TestRacyPool(t *testing.T) {
urls := make([]string, 50)
for i := range urls {
urls[i] = "u"
}
_, total, err := FetchAllRacy(context.Background(), urls, 8, fakeFetch)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
t.Logf("racy total (unreliable): %d", total)
}
func TestFixedPool(t *testing.T) {
urls := make([]string, 50)
for i := range urls {
urls[i] = "u"
}
results, total, err := FetchAllFixed(context.Background(), urls, 8, fakeFetch)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(results) != 50 || total != 50 {
t.Fatalf("fixed pool wrong: %d results, total %d", len(results), total)
}
}
The racy test fails under -race with 5 WARNING: DATA RACE blocks and exit code 1. The first block points at the shared slice write in the racy pool:
WARNING: DATA RACE
Read at 0x00c0001261b0 by goroutine 14:
syncpool.FetchAllRacy.func1()
/home/user/synctest-probe-2026-11-06/pool.go:27 +0xba
golang.org/x/sync/errgroup.(*Group).Go.func1()
/home/user/go/pkg/mod/golang.org/x/sync@v0.17.0/errgroup/errgroup.go:93 +0x86
Previous write at 0x00c0001261b0 by goroutine 9:
syncpool.FetchAllRacy.func1()
/home/user/synctest-probe-2026-11-06/pool.go:27 +0x135
golang.org/x/sync/errgroup.(*Group).Go.func1()
/home/user/go/pkg/mod/golang.org/x/sync@v0.17.0/errgroup/errgroup.go:93 +0x86
Line 27 of pool.go is the unsynchronized results = append(results, n) line, and the stack runs through errgroup.go:93, the line inside Group.Go where the worker function runs. The tail of the same run shows why the total cannot be trusted:
pool_test.go:23: racy total (unreliable): 50
testing.go:1867: race detected during execution of test
--- FAIL: TestRacyPool (0.00s)
FAIL
FAIL syncpool 0.014s
FAIL
The total is the unstable part. Two runs of the same racy test, minutes apart, logged 46 and then 50. An earlier run on the same module logged 49. The race count is stable at 5 blocks; the total swings. A test that asserted on the total would pass on the days it lands on 50 and fail on the days it does not. The detector fails the run every time, which is why its verdict is the signal and the total is not.
The fixed test passes clean under -race with exit code 0:
=== RUN TestFixedPool
--- PASS: TestFixedPool (0.00s)
PASS
ok syncpool 1.020s
The fixed pool is the same code with every shared write under one mutex. The companion guide covers that pool in full, including the failing control and the fix. The point of repeating the pair here is narrower: the bubble test proves the cancellation timing, and the race run proves the pool it tests is not also racy. A deterministic test of a racy pool would still be a racy pool.
Version floor
The synctest package needs Go 1.25. It first appeared in Go 1.24 behind the GOEXPERIMENT=synctest flag, with a slightly different API, and the Go 1.25 release notes state that the experiment graduated to general availability in 1.25. The old API is still present when the experiment flag is set, but the release notes say it will be removed in Go 1.26. None of the runs in this guide set any experiment flag. The module declares go 1.25, and the test passed on Go 1.26.4 and Go 1.27.3 with a plain go test. Go 1.24 is the only version where the flag matters, and it is not a version this guide recommends: the API there differs, and the flag is gone in 1.26.
The floor for the rest of the stack is the same as the companion guide: golang.org/x/sync v0.17.0 for the errgroup package, which is not in the standard library.
Frequently asked questions
Does the bubble make my test faster, or only more deterministic?
Both, for tests that wait on time. The clock jumps instead of ticking, so a 5-second deadline costs no real waiting, and the jump lands on the exact scheduled time, so the elapsed time is exact rather than approximate. A test that waits on a real network read gains nothing, because the clock never moves while the read blocks.
Can I use synctest with a real HTTP server?
No. A real server means real sockets, and a goroutine blocked on a socket is not durably blocked, so the bubble never goes idle. The documentation's HTTP example uses an in-process fake connection for exactly this reason. Fake the network, keep the timing real to the bubble.
Why assert elapsed time exactly instead of checking it is at least 5 seconds?
An exact assertion catches two failures a lower bound misses: a worker that ignores the context and runs to its full 10-second latency, and a deadline set to the wrong value. The bubble makes the exact value reproducible, so the stronger assertion costs nothing and checks more.
Does passing under synctest prove the pool cancels correctly in production?
It proves the cancellation wiring: the context fires at the deadline, the workers listen, and Wait returns the deadline error. It does not prove the production fetch listens, because the test fetch is a fake timer. The production fetch needs its own check that it watches the context, and the race run above needs a realistic workload too, since the detector only reports races that happen while it runs.
What happens if the bubble deadlocks?
Test panics and the test fails. A deadlock here means some goroutine is blocked on something that is not durably blocking, such as a mutex or a network read, while the clock has nowhere to go. The panic names the deadlock instead of letting the test hang until the test timeout.
Related guides on this site
- Fix Go "panic: runtime error: slice bounds out of range" — A High Bound Past Capacity, a Low Bound Past the High Bound, a Full Slice Expression Past Capacity, a String Past Its Length, and a Negative Bound
- Fix Go "panic: sync: negative WaitGroup counter" — Extra Done Calls, Add(-1) Past Zero, and the Add-Before-Go Rule
- Fix Go "panic: runtime error: makeslice: len out of range" — Negative Length, Length Past Capacity, and Sizes That Overflow
- Fix Go "panic: interface conversion" — A String Asserted to Int, a Nil Interface, a Type That Does Not Implement the Target Interface, and a Typed Nil
Source
- Go Packages, testing/synctest — the bubble:
Testruns a function in isolation, thetimepackage uses a fake clock starting at midnight UTC 2000-01-01, time advances only when every goroutine is durably blocked, the durably-blocking list (channel operations, select,Cond.Wait,WaitGroup.Wait,time.Sleep) and the not-durably-blocking list (mutex locks, network reads, system calls), deadlock panics, isolation rules for channels, timers, tickers andWaitGroup, and theContext.WithTimeoutexample. - Go 1.25 Release Notes — the
testing/synctestpackage graduated to general availability in Go 1.25 after first appearing in Go 1.24 underGOEXPERIMENT=synctestwith a slightly different API; the old API is still present with the flag set but will be removed in Go 1.26. - Go Packages, golang.org/x/sync/errgroup —
WithContextcancels the derived context on the first error or the firstWaitreturn,Goblocks until the goroutine fits under the limit,SetLimitwith negative meaning no limit and zero preventing adds, andWaitreturning the first non-nil error. - Go errgroup Worker Pool: The Race the Compiler Won't Catch — the companion guide on this site: the racy pool, the mutex fix, the
SetLimitceiling, and the cancellation and deadlock probes this guide builds on.
Keep Exploring
The full Go hub \u2014 slices and maps, concurrency, and the standard library.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.