Tutorial

Reducing Garbage Collection Pauses in Services

Diagnose stop the world pauses, cut allocation pressure at the source, and tune the collector so latency budgets survive real traffic instead of benchmarks.

On this page

  1. Introduction
  2. What Actually Causes a Pause
  3. Measuring Pauses Before Changing Anything
  4. Reducing Allocation Pressure
  5. Avoiding Pathological Allocation Patterns
  6. Tuning the Collector
  7. Sizing the Heap and the Container
  8. Pauses in Other Runtimes
  9. Load Testing with Realistic Traffic
  10. Verifying the Improvement
  11. Sources

Introduction

A garbage collected runtime frees the programmer from manual memory management at the cost of occasional pauses that can blow a latency budget. Most pauses are not caused by the collector being badly tuned but by the program allocating far more than it needs, forcing the collector to work harder and more often. The leverage is therefore in reducing allocation pressure first and tuning the collector second. This article covers how to measure pauses, how to find the allocation that causes them, and how to configure the runtime without hurting throughput.

What Actually Causes a Pause

A pause happens when the collector must stop application threads to safely reclaim memory, compact a region or scan roots. The length of the pause depends on how much live data must be traversed and how aggressive the collector is. A program with a large live heap and a short deadline forces frequent short pauses or rare long ones. Understanding which of these you have determines whether the fix is fewer allocations, a larger heap, or a different collector.

package main

import (
	"runtime"
	"runtime/debug"
	"time"
)

func tuneMemory() {
	// Cap heap growth: a larger GOGC means fewer collections and more memory.
	debug.SetGCPercent(200)
	// Read the container memory limit and leave headroom for non heap memory.
	const limitBytes = 512 << 20
	debug.SetMemoryLimit(limitBytes)

	// Export a continuously sampled heap metric for pause correlation.
	go func() {
		var m runtime.MemStats
		t := time.NewTicker(5 * time.Second)
		for range t.C {
			runtime.ReadMemStats(&m)
			observe("go_heap_bytes", float64(m.HeapAlloc))
			observe("go_pause_last_ns", float64(m.PauseNs[(m.NumGC+255)%256]))
		}
	}()
}

Measuring Pauses Before Changing Anything

Collect runtime metrics for pause duration, pause frequency, allocation rate and heap size before tuning, otherwise you are guessing. A pause of ten milliseconds once an hour and one of one millisecond every second feel similar in an average but differ enormously for tail latency. Track percentiles of pause duration and correlate them with request latency spikes to confirm that collection is the cause at all, because a slow database usually wins the blame unfairly.

// Reuse buffers instead of allocating per request.
var bufPool = sync.Pool{New: func() any { return make([]byte, 0, 32*1024) }}

func render(w io.Writer, tmpl *Template, data any) error {
	buf := bufPool.Get().([]byte)
	defer func() { bufPool.Put(buf[:0]) }() // reset length, keep capacity

	buf = tmpl.AppendTo(buf, data)
	_, err := w.Write(buf)
	return err
}

// Preallocate when the final size is known to avoid repeated growth.
func merge(a, b []int) []int {
	out := make([]int, 0, len(a)+len(b))
	out = append(out, a...)
	out = append(out, b...)
	return out
}

Reducing Allocation Pressure

The most effective change is usually to allocate less. Reuse buffers instead of creating a new slice or byte array per request, pool objects whose construction is expensive, and avoid converting between representations unnecessarily. Preallocate slices when the size is known to avoid repeated growth and copying. In languages with escape analysis, keeping values on the stack rather than the heap by avoiding unnecessary pointers removes allocation entirely. These changes reduce both pause frequency and pause duration.

Avoiding Pathological Allocation Patterns

Some patterns are especially costly: building a large slice by appending in a loop without capacity, allocating inside a hot inner loop, or creating many short lived objects that survive just long enough to be promoted to a long lived generation. Concatenating strings in a loop is a classic offender. Profiling by allocation shows the call sites responsible, often just a few lines that dominate the total, which makes the fix small and high impact.

Tuning the Collector

Once allocation is reasonable, adjust the collector to the latency goal. In Go, raising GOGC trades memory for fewer collections, and a soft memory limit lets the runtime pace collection against available memory. In the JVM, a low latency collector aims for short pauses while a throughput collector maximizes raw speed. Choose based on whether your service is latency sensitive or batch oriented, and set a memory limit so the runtime adapts to the container rather than the host.

Sizing the Heap and the Container

A heap that is too small collects constantly and a heap that is too large delays collection until a long pause. Size the heap from the live set plus headroom rather than from total memory, and set the container limit consistently with the runtime limit so the process is not killed by the kernel before the collector acts. Running in a container while the runtime sizes itself from the host is a common and confusing source of pauses and out of memory kills.

Pauses in Other Runtimes

Not every pause comes from the garbage collector. A runtime with a global interpreter lock pauses other threads during long operations; an event loop blocks entirely during synchronous work; a stop the world safe point can be delayed by a thread that ignores it. Identify the actual source with a profiler and thread dumps rather than assuming the collector, because the remedy for a blocked event loop is not a collector flag.

Load Testing with Realistic Traffic

Benchmarks that stream a few requests miss the allocation patterns that real concurrency produces. Load test with realistic request mix, payload sizes and concurrency, and measure pause percentiles under that load rather than in isolation. Watch for pauses that grow with concurrency, which indicates contention or allocation scaling with request count. Reproduce production heap and memory limits in the test so tuning transfers.

Verifying the Improvement

After any change, re-measure the same pause percentiles under the same load and confirm the tail latency improved without a throughput regression. Watch the allocation rate and heap size to ensure the change reduced pressure rather than merely moving it. Set a regression test that fails when pause p99 exceeds a budget, because runtime upgrades and dependency changes can reintroduce pressure silently. Tune against a metric you can assert, not a feeling.

Sources

Sources: Go runtime metrics, Go GC guide, Java garbage collection tuning.

FAQ

Should I always increase the heap to reduce pauses?
No. A larger heap reduces how often collection runs but can lengthen each pause. Size from the live set plus headroom, and prefer cutting allocation pressure, which reduces both frequency and duration.
How do I know GC is the cause of my latency spikes?
Correlate pause metrics with request latency percentiles. If spikes do not line up with pauses, the cause is elsewhere, commonly a blocking call or lock contention.

Related Examples