Skip to content

The Go execution tracer — scheduling, GC, and goroutine timelines

Capture a runtime/trace file from a running Go service, open it with go tool trace, and read what the scheduler and GC are doing on the timeline.

pprof tells you where you spent CPU; the execution tracer tells you why a request waited. When tail latency is dominated by scheduler stalls, channel contention, network round trips, or GC pauses — not by pure CPU — you reach for runtime/trace. This article shows how Stack Harbor captures and reads execution traces from real Go services.

How to verify

Capture a five-second trace from a running pprof endpoint, then open it locally:

curl -o trace.out 'http://127.0.0.1:6060/debug/pprof/trace?seconds=5'
file trace.out
go tool trace trace.out

go tool trace boots a local webserver around port 51000 and prints a URL. Open it in a browser; the landing page lists views (View trace, Goroutine analysis, Network blocking profile, Sync blocking profile, Syscall blocking profile, Scheduler latency profile, etc.).

What’s happening

A Go execution trace is a tape of low-level runtime events: every goroutine create/start/end, every channel send/receive, every GC start/mark/sweep, every netpoll wake, every syscall enter/exit. The recording overhead is significant (~10-30% CPU during the trace window), so traces are short and on-demand — not continuous.

The four most useful tracer views in practice:

  • View trace — Chrome trace-event style swimlanes, one row per OS thread (P0..PN). You see each goroutine as a colored bar; the gap between bars on the same row is scheduler downtime.
  • Goroutine analysis — pick a goroutine type (function name) and see its execution time broken into: running, runnable, sync block, GC, network wait, syscall. This is where you discover that 80% of a “slow” handler is actually chan receive waiting on its downstream.
  • Network blocking profile — flame graph rooted at the network round trips that gated execution. Tells you which call site is the latency leader.
  • Scheduler latency profile — distribution of how long goroutines waited from runnable to running. Wide tails here mean GOMAXPROCS is too low or you have too many runnable goroutines.

The tracer does NOT see what is happening inside the kernel (block I/O, page faults) — only the userspace-visible state transitions.

The procedure

  1. Programmatic capture for a custom window. Wrap an interesting operation in trace.Start / trace.Stop:

    import (
        "os"
        "runtime/trace"
    )
    
    func captureTrace(path string, fn func() error) error {
        f, err := os.Create(path)
        if err != nil { return err }
        defer f.Close()
        if err := trace.Start(f); err != nil { return err }
        defer trace.Stop()
        return fn()
    }

    Call it from a debug endpoint or from a benchmark that re-creates the slow case.

  2. Capture from production via pprof. With net/http/pprof already wired (private listener), the trace endpoint is built in:

    curl -o trace.out 'http://127.0.0.1:6060/debug/pprof/trace?seconds=10'

    Keep the window short. Ten seconds is plenty to capture thousands of requests in a busy service.

  3. Open and start reading the timeline.

    go tool trace trace.out
    # browser opens http://127.0.0.1:51000

    Click View trace first. Scroll horizontally. Each row is a logical P (processor). Wide colored bars are goroutines running on that P; thin gaps are scheduler idle. If you see long blank stretches, your throughput is gated by waiting, not by CPU.

  4. Use user regions to label your transactions. The tracer is far more useful when you mark request boundaries:

    import "runtime/trace"
    
    func (h *handler) Serve(w http.ResponseWriter, r *http.Request) {
        ctx, task := trace.NewTask(r.Context(), "billing.charge")
        defer task.End()
        region := trace.StartRegion(ctx, "db.query")
        row := h.db.QueryRowContext(ctx, "SELECT ...")
        region.End()
        // ...
    }

    These show up as named bars and as separate entries in Goroutine analysis. Now you can answer “where in a charge request does time go” with three clicks.

  5. Use Goroutine analysis to find blocking. Click Goroutine analysis, then pick main.(*handler).Serve (or whatever your handler is). The breakdown table shows:

    • Execution time
    • Network wait time
    • Sync block time
    • GC time
    • Scheduler wait time
    • Syscall time

    The biggest column is the bottleneck. A handler that spends 70% in Network wait means it is downstream-bound — fix the downstream, not the handler.

  6. Cross-reference with metrics. A spike in Scheduler wait time correlates with too many runnable goroutines. A spike in GC time correlates with allocation pressure (re-run a heap profile). Tracer + pprof together tell the whole story.

Common pitfalls

  • Tracing has 10-30% CPU overhead. Do not leave it on continuously. Use the pprof ?seconds=N endpoint or a programmatic capture gated by feature flag.
  • Trace files are large. A 10-second trace on a busy service is often 50-200 MB. Compress before downloading: curl ... | gzip > trace.out.gz, then gunzip before go tool trace.
  • go tool trace cannot stream. It loads the whole file into memory. Capturing too long produces a file you cannot open.
  • Tracer vs profiler. A profiler tells you what runs hot; a tracer tells you what waits. If your latency is high but CPU is low, the tracer is the right tool — not pprof.
  • Old Go versions render slowly. Pre-1.21 traces render frame-by-frame instead of with the modern Perfetto frontend. Stay on Go 1.22+ for big traces.

Stack Harbor uses the execution tracer on every Go service latency investigation — it turns “the API is slow” from a guess into a measured number. See how that feeds our managed operations practice when latency budgets need to be defended.