Skip to content

2023092815074242 Golang GC

Phases of GC:

  • Mark Setup. Can create STW(stop the world) latencies
  • Marking. Creates latencies that slow down the throughput of the application
  • Mark Termination. Can create STW latencies

Mark setup

  1. Turning on write barrier. Application's goroutines and GC work concurrently. Write barrier needs to allow Go to maintain data integrity on the heap during a collection. In order to turn the Write Barrier on, every application goroutine running must be stopped.

Marking

  1. The collector does is take 25% of the available CPU capacity for itself.
  2. The collector uses Goroutines to do the collection work. One thread will be dedicated to collection work.
  3. The collector marks values in heap memory they are still in-use. This work starts by inspecting the stacks of all existing goroutines to find root pointers to heap memory. Application can continue work concurrently during this process.
  4. If the collector determines that it needs to slow down allocations , it will recruit the application goroutins to assist with the marking work. This is called a Mark Assist.

Mark termination

  • When write barrier is turned off, various clean up tasks are performed
  • All the Goroutines are stopped while the Mark Termination phase completes. This activity is usually within 60 to 90 microseconds on average

Sweeping

It is another activity that happens after collection is finished. Sweeping is when the memory associated with values in heap memory that were not marked as in-use are reclaimed. It occurs when goroutines attempt to allocate new values in heap memory. The latency of Sweeping is added to the cost of performing an allocation in heap memory and is not tied to any latencies associated with garbage collection.

GC Percentage

This value represents a ratio of how much new heap memory can be allocated before the next collection has to start.  By default it is 100%. Value calculated based on the last collection memory used. For example 2 MB, it means that next collection will started when new 2 MB is allocated.

GC Trace

Example using:

GODEBUG=gctrace=1 ./app

References

  1. https://www.ardanlabs.com/blog/2018/12/garbage-collection-in-go-part1-semantics.html