Stop time.After Memory Leaks in Go Loops Using NewTimer and NewTicker
Avoid accumulating uncollected timers in busy select loops by using time.NewTicker and stopped time.NewTimer instances. After this, polling loops keep memory flat under load.
When a worker goroutine processes 5,000 messages per second and uses time.After(30 * time.Second) inside its for { select { ... } } loop, memory usage climbs steadily even though your message handler frees every message immediately. Why? Because time.After does not reset—it allocates a brand-new time.Timer on every single loop iteration, and Go's runtime timer heap holds onto each timer until its 30-second deadline expires.
At 5,000 messages/second with a 30-second timeout, 150,000 uncollected timers sit live in memory continuously, inflating heap size and forcing the garbage collector to scan dead timer channels on every cycle.
Skip ahead
Want the safe patterns? Jump to periodic loops with time.NewTicker or reusable idle timeouts with time.NewTimer.
Why time.After leaks inside a loop
Look at what happens in this common broken pattern:
// Broken under high throughput: allocates a 30s timer on EVERY message!
for {
select {
case msg := <-msgs:
handle(msg)
case <-time.After(30 * time.Second):
return errors.New("idle timeout")
}
}
Even though case msg := <-msgs: wins in 0.2 milliseconds, the time.After(30 * time.Second) expression already ran before select blocked—creating a timer scheduled 30 seconds in the future. Prior to Go 1.23, that timer could not even be garbage-collected until all 30 seconds elapsed. Even in Go 1.23+, allocating a new timer struct and channel on every hot-loop iteration creates unnecessary GC churn.
1. Periodic intervals: use time.NewTicker with defer Stop()
For periodic work (flushing metrics, polling health checks, refreshing a cache), create one time.NewTicker outside the loop and stop it on exit:
package main
import (
"context"
"fmt"
"time"
)
func poll(ctx context.Context) int {
ticker := time.NewTicker(10 * time.Millisecond)
defer ticker.Stop()
ticks := 0
for {
select {
case <-ctx.Done():
return ticks
case <-ticker.C:
ticks++
}
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 35*time.Millisecond)
defer cancel()
fmt.Printf("ticks=%d\n", poll(ctx))
}
$ go run -race .
ticks=3
2. Per-message idle timeouts: reuse one time.NewTimer
When you actually want an idle timeout that resets after each message arrives, allocate one time.NewTimer before the loop and call timer.Reset(30 * time.Second) on every iteration:
timer := time.NewTimer(30 * time.Second)
defer timer.Stop()
for {
timer.Reset(30 * time.Second)
select {
case msg := <-msgs:
handle(msg)
case <-timer.C:
return errors.New("idle timeout")
case <-ctx.Done():
return ctx.Err()
}
}
Instead of 150,000 timers in memory, the loop keeps exactly one timer alive no matter how fast messages arrive.
time.After vs. time.NewTimer vs. time.NewTicker
| API | Safe inside a hot loop? | Why |
|---|---|---|
time.After(d) |
No | Allocates a fresh timer and channel on every loop iteration |
time.NewTimer(d) + Reset(d) |
Yes | Reuses a single timer for per-message idle deadlines |
time.NewTicker(d) + defer Stop() |
Yes | Fires repeatedly on a fixed schedule without reallocating |
💡 Tip
As of Go 1.23, Timer.Stop() and Timer.Reset() automatically prevent stale values from lingering in timer.C, so you no longer need the old manual channel-drain dance before calling Reset.
Common mistakes
- Calling
time.Tick(d)instead oftime.NewTicker(d):time.Tickgives you no*time.Tickerhandle, so you cannot callStop()when a worker shuts down. - Assuming
time.Afterresets automatically: It never resets; every evaluation creates an independent timer. - Passing
0or negative durations toNewTicker:time.NewTicker(0)panics immediately at runtime.
⚠ Warning
If your ticker.C handler occasionally takes longer than the ticker interval, time.NewTicker drops missed ticks rather than queueing a backlog—do not rely on ticker counts as an exact wall-clock counter.
What happens if you skip this
Busy worker loops calling time.After accumulate tens of thousands of pending timers in the runtime heap, driving up RSS memory and GC pause times whenever message throughput spikes.
Related course: Go Intermediate.
About
Avoid accumulating uncollected timers in busy select loops by using time.NewTicker and stopped time.NewTimer instances. After this, polling loops keep memory flat under load.
- Responsible
- Jay P
- Last Update
- 11/27/2026
- Reading Time
- 4 min
Reviews
Sign in to write a reviewComments
Sign in to commentNo comments yet.