GOGC and GOMEMLIMIT
- Go course
- Expert
- Lesson 10/34
- 4 min
Learn the GOGC and GOMEMLIMIT environment variables.
GOGC and GOMEMLIMIT
GOGC (default 100) sets by what percentage the live heap may grow before GC starts: with a 100 MB live heap the next GC starts around 200 MB. A larger GOGC means less GC but more memory; a smaller one the opposite.
GOGC=200 ./app # less frequent GC
GOGC=off ./app # GC disabled (careful!)
GOMEMLIMIT=1GiB ./app # soft memory limitGOMEMLIMIT (Go 1.19) puts a soft upper bound on total memory; near the limit GC runs more often.
A good setting in containers
A common recipe in a container limited to 512 MB: set GOMEMLIMIT to ~90% of the limit. Go then runs GC more often before memory fills up and avoids being OOM-killed. Under very high traffic, GOGC=off + GOMEMLIMIT runs GC only when needed; but if the live heap exceeds the limit GC runs constantly (a death spiral), so it must be monitored carefully.
Practice Change the GC percent
Call eski := debug.SetGCPercent(50) with runtime/debug, restore with debug.SetGCPercent(eski) and print the returned value (50). Also read the current limit with debug.SetMemoryLimit(-1) and print whether it is greater than 0.
Starter code
package main
import (
"fmt"
"runtime/debug"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"fmt"
"runtime/debug"
)
func main() {
eski := debug.SetGCPercent(50)
fmt.Println(debug.SetGCPercent(eski))
fmt.Println(debug.SetMemoryLimit(-1) > 0)
}Expected output
50 true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 With a 50 MB live heap and GOGC=100, roughly when does the next GC start?
- When the heap reaches ~150 MB
- Every 2 minutes
- When the heap reaches ~100 MB Correct answer
- When the heap reaches ~50 MB
Explanation: Target = live heap × (1 + GOGC/100) = 50 × 2 = 100 MB.
2 Set it from code
eski := debug.____(200)
eski := debug.SetGCPercent(200)
Explanation: runtime/debug.SetGCPercent changes GOGC at run time and returns the old value.
3 Setting and effect
| Term | Meaning |
|---|---|
GOGC=50 |
Frequent GC, less memory |
GOGC=400 |
Rare GC, more memory |
GOGC=off |
GC off |
GOMEMLIMIT |
Soft memory limit |