FreeOSMemory() in production

The Go runtime does not release free memory back to the OS "immediately", it would be inefficient. Read more about it here: Golang - Cannot free memory once occupied by bytes.Buffer.

You should let the Go runtime handle this. If your app is unstable without calling debug.FreeOsMemory(), there are bigger problems which you shouldn't cover up with this even if it "seemingly" helps. It may even make things worse, as if serving a request does require a large amount of memory (which is properly freed by the GC when done with the request), calling FreeOsMemory() will just return it to the OS which the runtime will have to ask for / allocate again when serving another request. Should you have not handed it back to the OS, it would be available for the next request...

Try to decrease the memory requirement of the request handler. If it is not possible (questionable), then limit the number of requests requiring large memory that may be served concurrently.

See this question+answer how to do that: Process Management for the Go Webserver

Also: Is this an idiomatic worker thread pool in Go?


GO lang clean all memory that is not in use, but is not inmediate. You can read the other question:

Golang - Cannot free memory once occupied by bytes.Buffer


As an alternative to occasionally invoking debug.FreeOsMemory(), you can control the aggressiveness of the garbage collector with the GOGC environment variable or with the debug.SetGCPercent() method.

Empirically, I've seen that with a value as low as 10, it does its job.

See Package runtime