Trace goroutine scheduling
Trace goroutine scheduling
A runtime trace records events over time: goroutine execution, blocking, unblocking, scheduling and other runtime activity. Unlike aggregate profiles it helps examine chronology. In a fresh local module run go test -trace=trace.out -count=1, then go tool trace trace.out to inspect the trace with a local browser. Stop the viewer after use; do not expose its local service publicly.
Create the files shown below in a fresh directory, then run go test -count=1 -v ./... there. The separator lines are file labels, not source code. Go 1.23 is used for these local examples.
--- go.mod ---module example.test/lesson
go 1.23
--- lesson_test.go ---package lesson
import ( "bytes" "runtime/trace" "testing")
func TestLesson(t *testing.T) { var b bytes.Buffer if err := trace.Start(&b); err != nil { t.Fatal(err) } done := make(chan struct{}) go func() { close(done) }() <-done trace.Stop() if b.Len() == 0 { t.Fatal("empty trace") }}Trace recording is process-wide. Stop it before reading the buffer; Stop flushes pending trace data. Do not use the CLI -trace flag on this specific example because it already starts tracing. The test only checks capture creation, not the exact event order or latency. Use go tool trace -d=1 trace.out on a Go 1.23 trace file for a local textual diagnostic; the debug format is not a stable API.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestLessonAnnotate a logical operation
--- go.mod ---module example.test/lesson
go 1.23
--- lesson_test.go ---package lesson
import ( "context" "runtime/trace" "testing")
func TestLesson(t *testing.T) { ctx, task := trace.NewTask(context.Background(), "order") defer task.End() done := make(chan struct{}) go func() { defer close(done) trace.WithRegion(ctx, "calculate", func() { trace.Log(ctx, "stage", "ready") }) }() <-done}Run this second example with the CLI -trace flag. Tasks connect related activity through a context; a region marks an interval within one goroutine. Labels describe your operation, not a synchronization mechanism. Avoid secrets in trace labels and logs. Inspect runnable versus blocked periods before attributing delay to a scheduler problem.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestLessonTry it locally
Annotate a worker with region name decode and wait for its done signal. Capture it with go test -trace=trace.out. Use a fresh module with the same go.mod shown above; run go test -count=1 -v ./...
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Concurrency testing 06: Trace goroutine scheduling
Check the lesson objective before moving on.
What can a trace reveal that an aggregate profile cannot directly show?
Do trace regions coordinate goroutines?