Back to Concepts Roadmap
⚫ Level 6 — Memory Model
Memory Model

Garbage Collector (Tri-color)

Concurrent tri-color mark-and-sweep GC providing sub-millisecond stop-the-world pauses.

Real-World Analogy (Mental Model)

A team of janitors cleaning an office building while workers are working: they tag active desks with color badges (White, Grey, Black) and recycle unreferenced desks in the background.

Key Concepts & Rules To Remember

  • Runs concurrently with your application goroutines.
  • STW (Stop-The-World) pauses are typically under 1 millisecond.
  • Tuned via `GOGC` environment variable (default 100).
Step-by-Step Code

1. Understanding Garbage Collector (Tri-color)

Concurrent tri-color mark-and-sweep GC providing sub-millisecond stop-the-world pauses. In Go, garbage collector (tri-color) is designed around clarity and high runtime efficiency.

example.goGo 1.24+
// GOGC=100 triggers GC when heap doubles
// GOMEMLIMIT sets hard memory ceiling in modern Go
Battle-Tested Production Case Study

How Cloudflare Reduced Go GC Latency by 90% Using sync.Pool

Cloudflare Architecture
Production Challenge

Allocating millions of temporary 32 KB byte buffers per second triggered frequent Garbage Collector Stop-The-World (STW) mark phases, causing 50ms latency spikes.

Architectural Solution

Replaced ephemeral heap buffer allocations with a global `sync.Pool`. Buffers are checked out upon request arrival and returned to the pool immediately upon completion.

production_pattern.goP99 latency dropped from 50ms to 4ms. GC memory churn dropped by 92%.
var bufferPool = sync.Pool{
    New: func() any {
        b := make([]byte, 32*1024)
        return &b
    },
}

func handleRequest(r io.Reader) {
    bufPtr := bufferPool.Get().(*[]byte)
    defer bufferPool.Put(bufPtr) // Return to pool
    // Process request with *bufPtr...
}

Common Beginner Pitfalls & Mistakes

Mistake: Misusing garbage collector (tri-color) without understanding its memory or concurrency semantics.
✅ Correct Way: Always follow standard Go idioms and verify with tests.
Self Assessment

Knowledge Check

Verify your understanding with these interactive practice questions.

Quizzes

Quick checks for understanding

Multiple-choice with inline explanations—expand to see why.

What is the primary concept behind Garbage Collector (Tri-color)?

Finished this lesson?

Mark it as complete to track your overall Go mastery.