2023-01-17 23:59:04 +03:00
# automemlimit
[![Go Reference ](https://pkg.go.dev/badge/github.com/KimMachineGun/automemlimit.svg )](https://pkg.go.dev/github.com/KimMachineGun/automemlimit)
[![Go Report Card ](https://goreportcard.com/badge/github.com/KimMachineGun/automemlimit )](https://goreportcard.com/report/github.com/KimMachineGun/automemlimit)
[![Test ](https://github.com/KimMachineGun/automemlimit/actions/workflows/test.yml/badge.svg?branch=main )](https://github.com/KimMachineGun/automemlimit/actions/workflows/test.yml)
Automatically set `GOMEMLIMIT` to match Linux [cgroups(7) ](https://man7.org/linux/man-pages/man7/cgroups.7.html ) memory limit.
See more details about `GOMEMLIMIT` [here ](https://tip.golang.org/doc/gc-guide#Memory_limit ).
2024-01-22 12:35:23 +03:00
## Notice
Version `v0.5.0` introduces a fallback to system memory limits as an experimental feature when cgroup limits are unavailable. Activate this by setting `AUTOMEMLIMIT_EXPERIMENT=system` .
You can also use system memory limits via `memlimit.FromSystem` provider directly.
This feature is under evaluation and might become a default or be removed based on user feedback.
If you have any feedback about this feature, please open an issue.
2023-01-17 23:59:04 +03:00
## Installation
```shell
go get github.com/KimMachineGun/automemlimit@latest
```
## Usage
```go
package main
// By default, it sets `GOMEMLIMIT` to 90% of cgroup's memory limit.
2024-04-22 11:59:30 +03:00
// This is equivalent to `memlimit.SetGoMemLimitWithOpts(memlimit.WithLogger(slog.Default()))`
// To disable logging, use `memlimit.SetGoMemLimitWithOpts` directly.
2023-01-17 23:59:04 +03:00
import _ "github.com/KimMachineGun/automemlimit"
```
or
```go
package main
import "github.com/KimMachineGun/automemlimit/memlimit"
func init() {
2023-08-28 09:59:08 +03:00
memlimit.SetGoMemLimitWithOpts(
memlimit.WithRatio(0.9),
memlimit.WithProvider(memlimit.FromCgroup),
2024-04-22 11:59:30 +03:00
memlimit.WithLogger(slog.Default()),
2023-08-28 09:59:08 +03:00
)
2024-01-22 12:35:23 +03:00
memlimit.SetGoMemLimitWithOpts(
memlimit.WithRatio(0.9),
memlimit.WithProvider(
memlimit.ApplyFallback(
memlimit.FromCgroup,
memlimit.FromSystem,
),
),
)
2023-01-17 23:59:04 +03:00
memlimit.SetGoMemLimit(0.9)
memlimit.SetGoMemLimitWithProvider(memlimit.Limit(1024*1024), 0.9)
memlimit.SetGoMemLimitWithProvider(memlimit.FromCgroup, 0.9)
memlimit.SetGoMemLimitWithProvider(memlimit.FromCgroupV1, 0.9)
2023-12-11 13:35:15 +03:00
memlimit.SetGoMemLimitWithProvider(memlimit.FromCgroupHybrid, 0.9)
2023-01-17 23:59:04 +03:00
memlimit.SetGoMemLimitWithProvider(memlimit.FromCgroupV2, 0.9)
}
```