Articles / Go

  • go
  • concurrency
  • time-after
  • timers
  • select
  • debugging

The Timer Leak Hiding in Every select Loop

On older Go versions, time.After inside a select loop is a slow leak, and it looks completely innocent. The pattern turns up in almost every Go codebase that reads from a channel with a timeout: a heartbeat loop, a connection reader, a worker waiting for the next job.

func consume(ch <-chan Message, timeout time.Duration) {
	for {
		select {
		case msg := <-ch:
			handle(msg)
		case <-time.After(timeout):
			log.Println("timed out waiting for message")
			return
		}
	}
}

It reads cleanly, compiles and passes review. But every time ch wins the race, the time.After(timeout) call from that iteration is thrown away half-finished, and nothing ever reads from its channel again.

In Go's own vocabulary, that channel is never "drained": nobody performs the receive that would flush its value and let the timer be forgotten cleanly. The timer just sits there, running down its clock in the background for up to timeout, then fires into a channel nobody is listening on.

One abandoned timer is harmless. The trouble is that consume calls time.After again on the next iteration, and the one after that, for as long as messages keep arriving faster than the timeout.

Undrained timers pin memory until they fire

Each timer you create is registered with the Go runtime in a heap of pending timers, so the scheduler knows when to wake up and fire it without scanning every timer in the program. (There has been one heap per logical processor since Go 1.14 made the timer implementation more scalable.) Stopping a timer, or letting it fire, is what removes it from that heap.

Before Go 1.23, a Timer that was neither stopped nor allowed to fire stayed in that heap indefinitely. Because the runtime's own timer heap held a live reference to it, the garbage collector could not reclaim the Timer value, however thoroughly your code had forgotten it existed.

The object was reachable from the runtime, just not from anything you could see. The standard library documentation used to say so outright: the underlying timer "will not be recovered by the garbage collector until the timer fires."

So in the consume example, if messages arrive every millisecond and the timeout is 30 seconds, you get a steady state of roughly 30,000 live-but-pointless timers in the runtime's heap at any given moment. Each one only disappears when its own 30 seconds run out.

It won't crash anything, and it is bounded. It is still real heap memory and real timer-heap churn, and none of it has anything to do with the work the loop is doing.

On a busy service with several such loops, it shows up as steadily elevated memory and GC time that nobody can explain from the business logic, because the business logic looks fine.

The old fix: one timer, reused, drained by hand

Before Go 1.23 the accepted answer was to stop creating a new timer every iteration and reuse a single one instead, resetting it each time round the loop. That needs the drain dance.

Timer.Stop returning false means the timer had already fired (or was already stopped). On the old buffered timer channel, a fired-but-unread value could still be sitting in the channel's one-element buffer, waiting to be collected on the next receive:

func consume(ch <-chan Message, timeout time.Duration) {
	t := time.NewTimer(timeout)
	defer t.Stop()

	for {
		if !t.Stop() {
			select {
			case <-t.C:
			default:
			}
		}
		t.Reset(timeout)

		select {
		case msg := <-ch:
			handle(msg)
		case <-t.C:
			log.Println("timed out waiting for message")
			return
		}
	}
}

This works, but it is fiddly enough that people got it wrong constantly:

  • reset without stopping first
  • drain unconditionally and occasionally block forever on an empty channel
  • stop and drain in the wrong order relative to Reset

The pattern was correct; the ergonomics were bad. That's exactly how something ends up copy-pasted wrong from Stack Overflow answers with hundreds of upvotes.

Go 1.23 fixed the actual problem, not just the symptom

Go 1.23 changed time.Timer and time.Ticker in two ways at once, and it helps to be precise about which change fixes which half of this mess:

  1. Unreferenced timers are collectable. Timers and tickers no longer referenced by your program become eligible for garbage collection immediately, whether or not Stop was ever called.
  2. The channel is unbuffered. The channel a Timer delivers on became genuinely unbuffered, capacity zero, instead of the old one-element buffer. That guarantees a Reset or Stop call can no longer race against a stale value left over from before it.

The first change kills the leak in the naive consume loop. An abandoned time.After timer becomes an ordinary unreachable Go value the moment the losing select case is taken, and the GC treats it like any other garbage.

The second change makes the manual stop-and-drain dance unnecessary, because there is no buffer left for a stale tick to hide in. The time.After documentation was updated to match and now says, plainly, "there is no reason to prefer NewTimer when After will do."

Hang on: your go.mod decides, not your compiler

Check this before you rely on any of it: both behaviours are gated on the go line in your module's go.mod naming 1.23 or later. The Go toolchain version you happen to have installed isn't enough on its own.

Build an older module (go 1.21 in go.mod, say) with a Go 1.23 compiler and you silently get the old buffered-channel, GC-blocking behaviour, because the runtime checks what the module declared it targets. There is also a GODEBUG=asynctimerchan=1 setting if you ever need to force the old behaviour back for compatibility testing.

Is time.After in a loop fine now? Correct yes, free no

For correctness, yes: on a module targeting Go 1.23 or later, the naive version at the top of this article is fine. There's no leak and no stale-value race, and the standard library's own advice now points towards it.

For efficiency, it depends how hot the loop is. Each call to time.After still allocates a Timer and inserts it into the runtime's timer heap, which has a real (if small) cost. The GC fix stops that cost accumulating; you still pay it on every call.

In a loop processing messages every few microseconds, reusing a single timer with Reset is still measurably cheaper than allocating a fresh one on every pass. Skipping the reuse just no longer risks the runaway memory growth it used to.

If the loop's timeout is really a context.Context deadline rather than a fixed duration, the context already owns and stops its own internal timer when cancelled, so adding time.After alongside it is redundant either way.

If you maintain anything that still supports Go versions or go.mod lines earlier than 1.23, though, this leak is live in your codebase right now. The fix there is still the manual reuse-and-drain pattern above rather than the one-liner.