go 19 lines · 1 tab

Set a soft memory limit with debug.SetMemoryLimit

Leah Thompson Jan 2026
1 tab
package main

import (
  "os"
  "runtime/debug"
  "strconv"
)

func applyMemLimitFromEnv() {
  v := os.Getenv("GOMEMLIMIT_BYTES")
  if v == "" {
    return
  }
  n, err := strconv.ParseInt(v, 10, 64)
  if err != nil || n <= 0 {
    return
  }
  debug.SetMemoryLimit(n)
}
1 file · go Explain with highlit

In containerized environments, the Go runtime can benefit from knowing the memory budget. With Go 1.19+, debug.SetMemoryLimit lets you set a soft limit so the GC reacts more aggressively before the process gets killed by the OOM killer. I treat this as an operational tuning knob, not a magic fix: you still need to size caches and avoid leaks. The snippet below reads a byte value from GOMEMLIMIT_BYTES and applies it at startup. In production, I prefer using the standard GOMEMLIMIT env var when possible, but having an explicit hook can help when environments are inconsistent. The important part is observability: pair this with heap profiles and GC metrics so you understand the tradeoff between CPU and memory. Done carefully, this can improve stability for memory-constrained services.


Related snips

Share this code

Here's the card — post it anywhere.

Set a soft memory limit with debug.SetMemoryLimit — share card
Link copied