GOMEMLIMIT is a memory limit for the Go runtime (Go 1.19+), allowing more precise GC management.
1import "runtime/debug"23func main() {4 // Setting memory limit5 debug.SetMemoryLimit(1 << 30) // 1GB67 // Disabling automatic GC8 debug.SetGCPercent(-1)910 // Monitoring11 var stats runtime.MemStats12 runtime.ReadMemStats(&stats)13 fmt.Printf("Alloc: %d MB\n", stats.HeapAlloc/1024/1024)14 fmt.Printf("Sys: %d MB\n", stats.Sys/1024/1024)15}1617// Memory ballasting: allocating memory for predictable GC18func setupMemoryBallast(sizeMB int) {19 ballast := make([]byte, sizeMB*1024*1024)20 runtime.KeepAlive(ballast) // Prevent GC from collecting21}2223// Usage24func main() {25 // Allocate 500MB for ballast26 setupMemoryBallast(500)2728 // Now GC will run less frequently29 // Because it "thinks" there's already a lot of memory30}3132// In Docker/Kubernetes33// Set GOMEMLIMIT = 80% of container limit34// GOMEMLIMIT=1717986918 # 80% of 2GB3536// Configuration37func configureForDocker() {38 // Read limit from environment variable39 if memLimit := os.Getenv("GOMEMLIMIT"); memLimit != "" {40 limit, _ := strconv.ParseInt(memLimit, 10, 64)41 debug.SetMemoryLimit(limit)42 }43 debug.SetGCPercent(100)44}
Advantages: