Skip to Content
Skip to content
Go Intermediate: Interfaces, Concurrency, and Services
Intermediate
Courses
Go Intermediate: Interfaces, Concurrency, and Services

Timers, Tickers, and Avoiding time.After Leaks

Replace time.After inside loops with reusable time.NewTimer and stopped time.NewTicker instances. After this, long-running workers stay flat on memory.

Course content

Sign in to save your progress.

Course Home

Calling time.After(30 * time.Second) inside a busy for { select { ... } } worker loop is one of the sneakiest memory leaks in Go. At 5,000 messages per second, your handler processes every message in 0.2 ms—yet memory climbs steadily because time.After allocates a brand-new time.Timer on every single iteration, piling up ~150,000 live timers in the runtime heap.

Replacing time.After in loops with time.NewTicker (for periodic intervals) or a single reused time.NewTimer (for resettable idle timeouts) keeps memory completely flat under load.

Skip ahead

If you already avoid time.After inside hot loops and know when to use time.NewTicker vs. time.NewTimer + Reset, continue to "Testing With Interface Fakes, t.TempDir, and testdata."

Experiment 1: Why time.After leaks in a busy loop

Look closely at what Go evaluates on every pass of this common loop:

// Broken under load: allocates a new 30s timer on EVERY iteration!
for {
	select {
	case msg := <-msgs:
		handle(msg)
	case <-time.After(30 * time.Second):
		return errors.New("idle timeout")
	}
}

Every expression in a select's case clauses is evaluated before select decides which branch is ready. Even if <-msgs is ready immediately, time.After(30 * time.Second) already allocated a fresh timer and channel scheduled 30 seconds in the future. Prior to Go 1.23, that timer stayed pinned in the runtime heap for the full 30 seconds; even in Go 1.23+, allocating thousands of throwaway timers per second adds completely avoidable GC pressure.

Experiment 2: Periodic polling with time.NewTicker and defer Stop()

When a background worker runs on a fixed schedule (flushing metrics, checking health, refreshing a cache), create one time.NewTicker before 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

Experiment 3: Resettable per-message timeouts with one time.NewTimer

When you want "abort if no message arrives for 30 seconds" (resetting the countdown whenever a message arrives), allocate one time.NewTimer outside the loop and call timer.Reset(30 * time.Second) on every pass:

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()
	}
}

As of Go 1.23, Timer.Stop() and Timer.Reset() automatically prevent stale unread ticks from lingering in timer.C—so you no longer need the fragile manual channel-drain dance from older Go tutorials.

Experiment 4: What happens when a ticker handler runs slow

Suppose your ticker fires every 1 second, and one slow iteration takes 3.5 seconds. Does time.NewTicker queue up 3 backlogged ticks and burst them immediately? No—ticker.C has a buffer of 1, so missed ticks are dropped cleanly and the next tick fires at the next regular interval without stampeding your worker.

Common mistakes

  • Using time.Tick(d) instead of time.NewTicker(d): time.Tick returns only the channel—leaving you with no *time.Ticker handle to call Stop() when a worker shuts down.
  • Passing 0 or a negative duration to time.NewTicker: Panics immediately at runtime with non-positive interval for NewTicker.
  • Using time.Sleep inside a cancellation-aware loop: time.Sleep(10 * time.Second) ignores ctx.Done(), stalling graceful shutdown for 10 full seconds. Always select on a timer + ctx.Done().

💡 Tip

time.After is totally fine for a one-shot select outside a loop (for example waiting once on a startup readiness signal). Only avoid it inside loops that execute repeatedly.

What happens if you skip this step

Busy worker loops calling time.After silently bloat heap usage under peak message traffic, and workers sleeping with time.Sleep ignore SIGTERM until Kubernetes hard-kills the container.

A message consumer processes 2,000 events per second and uses case <-time.After(10 * time.Second): inside its for loop. Roughly how many timers does that loop allocate every 10 seconds, and how do you drop that to 1?

About

Replace time.After inside loops with reusable time.NewTimer and stopped time.NewTicker instances. After this, long-running workers stay flat on memory.

Duration
5 min
Last update
11/27/2026
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.