Challenge 4 - Production runtime
- Go course
- Expert
- Lesson 34/34
- 8 min
Write a service with GOMAXPROCS and memory limit set.
Challenge: a production-ready runtime
You will prepare a service's main function together with its runtime settings:
- Set the memory limit to 90% of the container limit (
debug.SetMemoryLimit). - Set GOMAXPROCS from the CPU quota.
- Log the version, GOMAXPROCS and memory limit at startup.
- Shut down gracefully on
SIGTERM.
limit := int64(float64(konteynerBayt) * 0.9)
debug.SetMemoryLimit(limit)Make the settings testable
If you separate reading the environment and computing into a pure function, main stays thin and the logic becomes testable:
type Ayar struct {
Procs int
MemLimit int64
}
func hesapla(cpuKota float64, bellek int64) Ayar {
p := int(cpuKota)
if p < 1 { p = 1 }
return Ayar{Procs: p, MemLimit: int64(float64(bellek) * 0.9)}
}Practice Settings computation
Write the Ayar type and the hesapla function above. Print the results of hesapla(0.5, 1000) and hesapla(4, 1000) with %+v on separate lines.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
type Ayar struct {
Procs int
MemLimit int64
}
func hesapla(cpuKota float64, bellek int64) Ayar {
p := int(cpuKota)
if p < 1 {
p = 1
}
return Ayar{Procs: p, MemLimit: int64(float64(bellek) * 0.9)}
}
func main() {
fmt.Printf("%+v\n", hesapla(0.5, 1000))
fmt.Printf("%+v\n", hesapla(4, 1000))
}Expected output
{Procs:1 MemLimit:900}
{Procs:4 MemLimit:900}
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why set the memory limit to 90% of the container limit instead of all of it?
- So GC runs less often
- Because Go doesn't accept 100%
- It makes no difference
- To leave room for stacks and non-Go memory and avoid OOM Correct answer
Explanation: GOMEMLIMIT is a soft limit and can't fully track some memory such as cgo or mmap; leaving headroom keeps the kernel from killing the process.
2 Apply the limit
a := hesapla(2, 512<<20)
runtime.GOMAXPROCS(a.Procs)
debug.____(a.MemLimit)
a := hesapla(2, 512<<20)
runtime.GOMAXPROCS(a.Procs)
debug.SetMemoryLimit(a.MemLimit)
Explanation: SetMemoryLimit gives the computed soft limit to the runtime.
3 Setting and reason
| Term | Meaning |
|---|---|
GOMAXPROCS = kota |
Avoids CPU throttling |
GOMEMLIMIT = %90 |
Avoids OOM |
Startup log |
Easier diagnosis |
Handling SIGTERM |
Graceful shutdown |