The Problem Isn't GC Pauses—It's What Triggers Them
Most Go engineers know the GC runs concurrently and that STW pauses are short. Fewer understand why the write barrier exists, what it costs at the instruction level, and how specific allocation patterns force the runtime into assist mode—burning goroutine CPU on GC work during the critical path of a request.
This matters most in latency-sensitive microservices handling sustained throughput: gRPC handlers, Redis pipelines, MongoDB cursor processing, or inference request fan-out in AI backends. At those workloads, GC-induced assist latency is not theoretical.
Tri-Color Invariant Recap (For Mechanics, Not Basics)
Go's GC uses a concurrent tri-color mark-sweep. Objects are white (unmarked), grey (queued for scanning), or black (scanned). The invariant the runtime must maintain during concurrent marking:
A black object must not point to a white object.
If a mutator goroutine writes a pointer from a black object to a white object after the GC has already scanned the black object, the GC will never see that white object again and will collect it while it is still live. That is a dangling pointer.
The write barrier is the mechanism that prevents this. Every pointer write that could violate the invariant must inform the GC.
Go's Hybrid Write Barrier (Since Go 1.17)
Go does not use a simple Dijkstra or Yuasa barrier in isolation. It uses a hybrid combining both:
- Dijkstra insertion barrier: shade the new pointer target grey on write.
- Yuasa deletion barrier: shade the old pointer target grey on overwrite.
The combined form ensures both the object being pointed away from and the object being pointed to are grey before the write completes. This eliminates the need for a STW re-scan of stacks at the end of the mark phase (which was required pre-1.17 when only the Dijkstra barrier was used on the heap).
The barrier applies to heap pointer writes only. Stack writes do not go through the barrier during mark—instead, stacks are rescanned at mark termination if they were active during marking. This is a deliberate tradeoff: stack writes are far more frequent, so adding a per-write barrier to them would dominate CPU cost.
What the Barrier Looks Like at the Call Site
type Node struct { next *Node val int } func link(a, b *Node) { a.next = b // heap pointer write → barrier fires } Compiled with -gcflags=-S, the assignment to a.next emits a call to runtime.gcWriteBarrier (or the inlined fast path that tests writeBarrier.enabled). The fast path is a single load + branch. When the barrier is off (outside GC cycles), cost is roughly one additional load and a not-taken branch. When the barrier is on, the write goes through a buffer that the GC drains.
The Write Barrier Buffer and Drain Cost
Each P (logical processor) has a write barrier buffer of 256 pointer slots. When a goroutine fills its P's buffer, it must flush it—this is synchronous work on the goroutine. The flush calls runtime.wbBufFlush, which greys the buffered pointers by marking them in the GC work queue.
The consequence: under heavy pointer mutation, goroutines pay flush cost proportional to pointer write rate, not allocation rate alone. A service that updates linked structures (request chains, middleware wrappers, tree nodes representing JSON/BSON documents from MongoDB) can fill buffers faster than one that simply allocates flat structs.
Allocation Pressure and GC Assist
The GC triggers when the heap grows to a size determined by GOGC (default 100, meaning 100% growth since last GC). At that point, concurrent marking begins. The GC needs to complete marking before the heap doubles again.
If goroutines allocate faster than the concurrent mark phase can keep up, the runtime puts goroutines into GC assist: each allocation above a threshold requires the goroutine to do proportional GC marking work before its allocation is fulfilled.
assist_work = allocation_size * (scan_work_remaining / remaining_heap_budget) This is where the latency cliff appears. A request handler that allocates a 50 KB BSON document from a MongoDB cursor, then deserializes it into several Go structs, may cross the assist threshold mid-request and spend 200–500 µs marking heap objects before it can continue. That time appears as handler latency, not GC pause.
Measuring Assist in Production
import "runtime/metrics" func readGCAssistTime() time.Duration { s := []metrics.Sample{{Name: "/gc/scan/globals:bytes"}} // wrong metric // correct: s = []metrics.Sample{{Name: "/gc/pauses:seconds"}} metrics.Read(s) // For assist specifically: s2 := []metrics.Sample{{Name: "/sched/latencies:seconds"}} metrics.Read(s2) // /gc/scan/heap:bytes and /memory/classes/heap/released:bytes // give allocation and release pressure signals return 0 } More practically, expose runtime.ReadMemStats via a metrics endpoint and track GCCPUFraction. Values above 0.05 (5% of available CPU) under sustained load indicate assist is contributing non-trivially to latency. Correlate with p99 handler latency spikes.
Structural Patterns That Amplify Barrier Cost
1. Pointer-Heavy Struct Trees
Deserializing deeply nested JSON or BSON into map[string]interface{} or recursive struct trees generates one heap allocation per node and one pointer write per edge. Both allocation pressure and write barrier flushes scale with document depth.
Mitigation: use flat, index-addressed representations or pre-allocated arenas where the GC sees a single large allocation with no internal pointer updates after initialization.
2. Interface Boxing in Hot Paths
type Handler interface{ Handle(ctx context.Context, r *Request) error } // Every middleware wrap allocates an interface value on heap: var h Handler = &loggingMiddleware{next: base} Each interface value holding a pointer is two words: type pointer + data pointer. If the interface is stored in a heap struct, the write of the data pointer goes through the barrier. Wrapping handlers in chains during request setup (common in middleware-heavy frameworks) writes multiple interface pointers per request.
3. sync.Pool and GC Interaction
sync.Pool releases its contents at each GC cycle. For services with high allocation rates, this means pool-cached objects are frequently invalidated, forcing re-allocation and defeating the pool's purpose during GC-heavy windows. Pool is most effective when allocation rate is moderate and GC cycles are infrequent relative to request rate.
Escape Analysis as a Barrier Avoidance Tool
Only heap pointers trigger the barrier. If a pointer write stays on the stack, it is barrier-free. This is why escape analysis matters for GC cost, not just for reducing allocations.
func process(data []byte) Result { var r Result // r is on stack if Result is small and doesn't escape r.Hash = hash(data) // no barrier: stack write return r // copied out, no heap pointer } Versus:
func process(data []byte) *Result { r := &Result{} // escapes to heap r.Hash = hash(data) // barrier fires if GC is running return r } Check escape decisions with go build -gcflags='-m=2'. The key signal is escapes to heap versus does not escape. In hot paths—middleware, codec layers, Redis command builders—each heap escape that you can eliminate removes one potential barrier invocation.
Write Barrier Cost Under GOMAXPROCS Scaling
The write barrier buffer is per-P. As GOMAXPROCS increases, total buffer flush capacity increases linearly—but so does concurrent mutation rate. The GC work queue (the grey set) is shared and protected by its own lock. Under high parallelism, grey set contention becomes measurable. This is rarely the first bottleneck but matters on 32+ core instances running CPU-saturated backend services.
Decision Framework
Before tuning GC-related behavior, establish which mechanism is actually costing you:
| Signal | Likely Cause | Lever |
|---|---|---|
| STW pauses > 1 ms | Large heap, slow mark termination | Reduce heap size (lower GOGC, use GOMEMLIMIT) |
| p99 latency spikes at GC cycle boundary | GC assist from allocation pressure | Reduce allocation rate in hot path; use sync.Pool correctly |
Elevated GCCPUFraction with normal latency | Acceptable background GC work | No action needed |
| Latency degrades under pointer-heavy workloads | Write barrier buffer flushes | Flatten data structures; eliminate mid-request pointer chains |
Use GOMEMLIMIT (introduced Go 1.19) as the primary control in containerized services. Setting it to 90% of container memory limit prevents the heap from growing to a size where assist becomes severe, without requiring manual GOGC tuning.
import "runtime/debug" func init() { debug.SetMemoryLimit(450 << 20) // 450 MB on a 512 MB container } Combined with escape analysis discipline and flat data structures in codec and middleware layers, this eliminates the majority of GC-induced tail latency in throughput-sensitive Go microservices without sacrificing correctness or requiring off-heap memory management.

