From 68c388ba6e92ef66e35ae4e358dcf1ecf7d8a273 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Thu, 26 Nov 2026 10:38:54 +0100 Subject: [PATCH 1/4] fix: size max_threads auto from the memory limit of the container, not of the host In a container, sysinfo reports the memory of the host: max_threads auto then allowed hundreds of threads to a container of a few hundred MB. The memory limit of Go caps it now when lower, which Caddy derives from the cgroup of the container, and GOMEMLIMIT sets when the container doesn't expose one. --- docs/performance.md | 4 +++- internal/memory/memory.go | 24 +++++++++++++++++++++++ internal/memory/memory_test.go | 36 ++++++++++++++++++++++++++++++++++ phpmainthread.go | 13 ++++++------ phpmainthread_test.go | 13 ++++++++++++ 5 files changed, 83 insertions(+), 7 deletions(-) create mode 100644 internal/memory/memory.go create mode 100644 internal/memory/memory_test.go diff --git a/docs/performance.md b/docs/performance.md index 57c9d1b72f..f3fdb319aa 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -29,7 +29,9 @@ To change the number of workers, use the `num` option of the `worker` section of While it's always better to know exactly what your traffic will look like, real-life applications tend to be more unpredictable. The `max_threads` [configuration](config.md#caddyfile-config) allows FrankenPHP to automatically spawn additional threads at runtime up to the specified limit. `max_threads` can help you figure out how many threads you need to handle your traffic and can make the server more resilient to latency spikes. -If set to `auto`, the limit will be estimated based on the `memory_limit` in your `php.ini`. If not able to do so, +If set to `auto`, the limit will be estimated based on the `memory_limit` in your `php.ini` and the memory available: +the system's, or the memory limit of the Go runtime when it is lower. In a container, Caddy derives that limit from +the memory limit of the container, and `GOMEMLIMIT` sets it explicitly when the container doesn't expose it. If not able to do so, `auto` will instead default to twice the threads started at boot. Keep in mind that `auto` might strongly underestimate the number of threads needed. `max_threads` is similar to PHP-FPM's [pm.max_children](https://www.php.net/manual/install.fpm.configuration.php#pm.max-children). The main difference is that FrankenPHP uses threads instead of processes and automatically delegates them across different worker scripts and 'classic mode' as needed. diff --git a/internal/memory/memory.go b/internal/memory/memory.go new file mode 100644 index 0000000000..780b6c1bda --- /dev/null +++ b/internal/memory/memory.go @@ -0,0 +1,24 @@ +package memory + +import ( + "math" + "runtime/debug" +) + +// Available returns the memory the process may use, 0 if it cannot be +// determined: the total system memory, or the memory limit of the Go runtime +// when it is lower. In a container, the system memory is that of the host, +// while the limit comes from the container: Caddy derives it from the cgroup, +// GOMEMLIMIT sets it explicitly. +func Available() uint64 { + total := TotalSysMemory() + limit := debug.SetMemoryLimit(-1) + if limit <= 0 || limit == math.MaxInt64 { + return total + } + if total == 0 || uint64(limit) < total { + return uint64(limit) + } + + return total +} diff --git a/internal/memory/memory_test.go b/internal/memory/memory_test.go new file mode 100644 index 0000000000..2885540069 --- /dev/null +++ b/internal/memory/memory_test.go @@ -0,0 +1,36 @@ +package memory + +import ( + "math" + "runtime/debug" + "testing" + + "github.com/stretchr/testify/assert" +) + +func setMemoryLimit(t *testing.T, limit int64) { + previous := debug.SetMemoryLimit(limit) + t.Cleanup(func() { debug.SetMemoryLimit(previous) }) +} + +func TestAvailableIsTheSystemMemoryWithoutLimit(t *testing.T) { + setMemoryLimit(t, math.MaxInt64) + + assert.Equal(t, TotalSysMemory(), Available()) +} + +func TestAvailableIsTheMemoryLimitWhenLower(t *testing.T) { + setMemoryLimit(t, 512<<20) + + assert.Equal(t, uint64(512<<20), Available()) +} + +func TestAvailableIsTheSystemMemoryWhenTheLimitIsHigher(t *testing.T) { + total := TotalSysMemory() + if total == 0 || total > math.MaxInt64/2 { + t.Skip("the system memory is unknown") + } + setMemoryLimit(t, int64(total)*2) + + assert.Equal(t, total, Available()) +} diff --git a/phpmainthread.go b/phpmainthread.go index 40adf13c21..cb7a05f500 100644 --- a/phpmainthread.go +++ b/phpmainthread.go @@ -272,23 +272,24 @@ func go_frankenphp_main_thread_is_ready() { } // max_threads = auto -// setAutomaticMaxThreads estimates the amount of threads based on php.ini and system memory_limit -// If unable to get the system's memory limit, simply double num_threads +// setAutomaticMaxThreads estimates the amount of threads based on the memory_limit of php.ini and the memory +// available: the system's, or the memory limit of Go when lower, which Caddy derives from the cgroup of a container. +// If unable to get either, simply double num_threads func (mainThread *phpMainThread) setAutomaticMaxThreads() { if mainThread.maxThreads >= 0 { return } perThreadMemoryLimit := int64(C.frankenphp_get_current_memory_limit()) - totalSysMemory := memory.TotalSysMemory() - if perThreadMemoryLimit <= 0 || totalSysMemory == 0 { + availableMemory := memory.Available() + if perThreadMemoryLimit <= 0 || availableMemory == 0 { mainThread.maxThreads = mainThread.numThreads * 2 return } - maxAllowedThreads := totalSysMemory / uint64(perThreadMemoryLimit) + maxAllowedThreads := availableMemory / uint64(perThreadMemoryLimit) mainThread.maxThreads = int(maxAllowedThreads) if globalLogger.Enabled(globalCtx, slog.LevelDebug) { - globalLogger.LogAttrs(globalCtx, slog.LevelDebug, "Automatic thread limit", slog.Int("perThreadMemoryLimitMB", int(perThreadMemoryLimit/1024/1024)), slog.Int("maxThreads", mainThread.maxThreads)) + globalLogger.LogAttrs(globalCtx, slog.LevelDebug, "Automatic thread limit", slog.Int("perThreadMemoryLimitMB", int(perThreadMemoryLimit/1024/1024)), slog.Int("availableMemoryMB", int(availableMemory/1024/1024)), slog.Int("maxThreads", mainThread.maxThreads)) } } diff --git a/phpmainthread_test.go b/phpmainthread_test.go index a0682f092f..50c1a433ce 100644 --- a/phpmainthread_test.go +++ b/phpmainthread_test.go @@ -6,6 +6,7 @@ import ( "net/http/httptest" "path/filepath" "runtime" + "runtime/debug" "sync" "sync/atomic" "testing" @@ -388,6 +389,18 @@ func testThreadCalculationError(t *testing.T, o *opt) { assert.Error(t, err, "configuration must error") } +// in a container, the memory of the host is not the memory FrankenPHP may use: +// the memory limit of Go, which Caddy derives from the cgroup, caps it +func TestAutomaticMaxThreadsHonorsTheGoMemoryLimit(t *testing.T) { + previous := debug.SetMemoryLimit(640 << 20) + t.Cleanup(func() { debug.SetMemoryLimit(previous) }) + + assert.NoError(t, Init(WithNumThreads(2), WithMaxThreads(-1), WithPhpIni(map[string]string{"memory_limit": "64M"}))) + defer Shutdown() + + assert.Equal(t, 10, mainThread.maxThreads, "640 MB for threads of 64 MB") +} + func TestContextAndLoggerMustNotBeNil(t *testing.T) { log, ctx := getLogger(0) assert.NotNil(t, log, "logger is defined if all threads are inactive") From 61d79f02e26ad2fe2ee8452938f2adb9188a9582 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Dunglas?= Date: Wed, 2 Dec 2026 14:21:34 +0100 Subject: [PATCH 2/4] fix: set the Go memory limit in php-server Like "caddy run", php-server now derives GOMEMLIMIT from the cgroup or the system memory, which max_threads auto relies on. --- caddy/go.mod | 2 +- caddy/php-server.go | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/caddy/go.mod b/caddy/go.mod index 3d97c3f278..2d33a0f7d0 100644 --- a/caddy/go.mod +++ b/caddy/go.mod @@ -7,6 +7,7 @@ replace github.com/dunglas/frankenphp => ../ retract v1.0.0-rc.1 // Human error require ( + github.com/KimMachineGun/automemlimit v1.0.2 github.com/caddyserver/caddy/v2 v2.11.9 github.com/caddyserver/certmagic v0.25.6 github.com/dunglas/caddy-cbrotli v1.0.1 @@ -32,7 +33,6 @@ require ( github.com/AndreasBriese/bbloom v0.0.0-20190825152654-46b345b51c96 // indirect github.com/BurntSushi/toml v1.6.0 // indirect github.com/DeRuina/timberjack v1.4.10 // indirect - github.com/KimMachineGun/automemlimit v1.0.2 // indirect github.com/Masterminds/goutils v1.1.1 // indirect github.com/Masterminds/semver/v3 v3.5.0 // indirect github.com/Masterminds/sprig/v3 v3.3.0 // indirect diff --git a/caddy/php-server.go b/caddy/php-server.go index bd5fb4da76..24dd56cbbc 100644 --- a/caddy/php-server.go +++ b/caddy/php-server.go @@ -10,6 +10,7 @@ import ( "strings" "time" + "github.com/KimMachineGun/automemlimit/memlimit" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" caddycmd "github.com/caddyserver/caddy/v2/cmd" @@ -19,6 +20,7 @@ import ( "github.com/caddyserver/caddy/v2/modules/caddyhttp/rewrite" "github.com/caddyserver/certmagic" "github.com/dunglas/frankenphp" + "go.uber.org/zap/exp/zapslog" "github.com/spf13/cobra" ) @@ -61,6 +63,7 @@ For more advanced use cases, see https://github.com/php/frankenphp/blob/main/doc // cmdPHPServer is freely inspired from the file-server command of the Caddy server (Apache License 2.0, Matthew Holt and The Caddy Authors) func cmdPHPServer(fs caddycmd.Flags) (int, error) { caddy.TrapSignals() + setMemoryLimit() domain := fs.String("domain") root := fs.String("root") @@ -326,3 +329,12 @@ func cmdPHPServer(fs caddycmd.Flags) (int, error) { select {} } + +// setMemoryLimit mirrors what "caddy run" does, as max_threads auto is sized from this limit. +func setMemoryLimit() { + _, _ = memlimit.Set( + // the stacktrace level is above all levels so that errors don't dump traces, as in Caddy + memlimit.WithLogger(slog.New(zapslog.NewHandler(caddy.Log().Core(), zapslog.WithName("memlimit"), zapslog.AddStacktraceAt(slog.Level(127))))), + memlimit.WithProvider(memlimit.ApplyFallback(memlimit.FromCgroup, memlimit.FromSystem)), + ) +} From bfabdf6f762139942e31806393844934fa39ef33 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Dunglas?= Date: Wed, 2 Dec 2026 14:22:33 +0100 Subject: [PATCH 3/4] fix: keep the max_threads fallback outside Linux Caddy sets the Go memory limit to 90% of the RAM even when FrankenPHP cannot read the system memory, so only an explicit GOMEMLIMIT is honored there. Tests no longer assume the host has more memory than the limit under test. --- docs/performance.md | 7 ++++--- internal/memory/memory.go | 10 ++++------ internal/memory/memory_test.go | 26 ++++++++++++++++++++++---- phpmainthread.go | 4 +--- phpmainthread_test.go | 8 ++++++-- 5 files changed, 37 insertions(+), 18 deletions(-) diff --git a/docs/performance.md b/docs/performance.md index f3fdb319aa..29b9b16ac9 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -29,9 +29,10 @@ To change the number of workers, use the `num` option of the `worker` section of While it's always better to know exactly what your traffic will look like, real-life applications tend to be more unpredictable. The `max_threads` [configuration](config.md#caddyfile-config) allows FrankenPHP to automatically spawn additional threads at runtime up to the specified limit. `max_threads` can help you figure out how many threads you need to handle your traffic and can make the server more resilient to latency spikes. -If set to `auto`, the limit will be estimated based on the `memory_limit` in your `php.ini` and the memory available: -the system's, or the memory limit of the Go runtime when it is lower. In a container, Caddy derives that limit from -the memory limit of the container, and `GOMEMLIMIT` sets it explicitly when the container doesn't expose it. If not able to do so, +If set to `auto`, the limit will be estimated by dividing the memory available by the `memory_limit` in your `php.ini`. +The memory available is the system's, capped by the memory limit of the Go runtime: `frankenphp run` and `frankenphp php-server` +set it to 90% of the memory limit of the container, or of the system memory without one (`AUTOMEMLIMIT` changes this ratio), +and `GOMEMLIMIT` sets it explicitly. If not able to do so, for instance outside of Linux without `GOMEMLIMIT`, `auto` will instead default to twice the threads started at boot. Keep in mind that `auto` might strongly underestimate the number of threads needed. `max_threads` is similar to PHP-FPM's [pm.max_children](https://www.php.net/manual/install.fpm.configuration.php#pm.max-children). The main difference is that FrankenPHP uses threads instead of processes and automatically delegates them across different worker scripts and 'classic mode' as needed. diff --git a/internal/memory/memory.go b/internal/memory/memory.go index 780b6c1bda..b8dc2cce47 100644 --- a/internal/memory/memory.go +++ b/internal/memory/memory.go @@ -2,18 +2,16 @@ package memory import ( "math" + "os" "runtime/debug" ) -// Available returns the memory the process may use, 0 if it cannot be -// determined: the total system memory, or the memory limit of the Go runtime -// when it is lower. In a container, the system memory is that of the host, -// while the limit comes from the container: Caddy derives it from the cgroup, -// GOMEMLIMIT sets it explicitly. +// Available returns the system memory capped by the Go memory limit, which Caddy derives from the container, or 0 if unknown. func Available() uint64 { total := TotalSysMemory() limit := debug.SetMemoryLimit(-1) - if limit <= 0 || limit == math.MaxInt64 { + // without the system memory, only an explicit GOMEMLIMIT is meaningful: Caddy's own is a fraction of the RAM + if limit <= 0 || limit == math.MaxInt64 || (total == 0 && os.Getenv("GOMEMLIMIT") == "") { return total } if total == 0 || uint64(limit) < total { diff --git a/internal/memory/memory_test.go b/internal/memory/memory_test.go index 2885540069..d8283b7f87 100644 --- a/internal/memory/memory_test.go +++ b/internal/memory/memory_test.go @@ -3,24 +3,33 @@ package memory import ( "math" "runtime/debug" + "strconv" "testing" "github.com/stretchr/testify/assert" ) -func setMemoryLimit(t *testing.T, limit int64) { +func setMemoryLimit(t *testing.T, limit int64, explicit bool) { + if explicit { + t.Setenv("GOMEMLIMIT", strconv.FormatInt(limit, 10)) + } else { + t.Setenv("GOMEMLIMIT", "") + } previous := debug.SetMemoryLimit(limit) t.Cleanup(func() { debug.SetMemoryLimit(previous) }) } func TestAvailableIsTheSystemMemoryWithoutLimit(t *testing.T) { - setMemoryLimit(t, math.MaxInt64) + setMemoryLimit(t, math.MaxInt64, false) assert.Equal(t, TotalSysMemory(), Available()) } func TestAvailableIsTheMemoryLimitWhenLower(t *testing.T) { - setMemoryLimit(t, 512<<20) + if total := TotalSysMemory(); total != 0 && total <= 512<<20 { + t.Skip("the system memory is lower than the limit") + } + setMemoryLimit(t, 512<<20, true) assert.Equal(t, uint64(512<<20), Available()) } @@ -30,7 +39,16 @@ func TestAvailableIsTheSystemMemoryWhenTheLimitIsHigher(t *testing.T) { if total == 0 || total > math.MaxInt64/2 { t.Skip("the system memory is unknown") } - setMemoryLimit(t, int64(total)*2) + setMemoryLimit(t, int64(total)*2, true) assert.Equal(t, total, Available()) } + +func TestAvailableIgnoresAnImplicitLimitWithoutTheSystemMemory(t *testing.T) { + if TotalSysMemory() != 0 { + t.Skip("the system memory is known") + } + setMemoryLimit(t, 512<<20, false) + + assert.Zero(t, Available()) +} diff --git a/phpmainthread.go b/phpmainthread.go index cb7a05f500..f11341708c 100644 --- a/phpmainthread.go +++ b/phpmainthread.go @@ -272,9 +272,7 @@ func go_frankenphp_main_thread_is_ready() { } // max_threads = auto -// setAutomaticMaxThreads estimates the amount of threads based on the memory_limit of php.ini and the memory -// available: the system's, or the memory limit of Go when lower, which Caddy derives from the cgroup of a container. -// If unable to get either, simply double num_threads +// setAutomaticMaxThreads divides the available memory by the memory_limit of php.ini, or doubles num_threads if either is unknown func (mainThread *phpMainThread) setAutomaticMaxThreads() { if mainThread.maxThreads >= 0 { return diff --git a/phpmainthread_test.go b/phpmainthread_test.go index 50c1a433ce..e66a084958 100644 --- a/phpmainthread_test.go +++ b/phpmainthread_test.go @@ -12,6 +12,7 @@ import ( "testing" "time" + "github.com/dunglas/frankenphp/internal/memory" "github.com/dunglas/frankenphp/internal/state" "github.com/stretchr/testify/assert" ) @@ -389,9 +390,12 @@ func testThreadCalculationError(t *testing.T, o *opt) { assert.Error(t, err, "configuration must error") } -// in a container, the memory of the host is not the memory FrankenPHP may use: -// the memory limit of Go, which Caddy derives from the cgroup, caps it +// in a container, the memory limit of Go, which Caddy derives from the cgroup, caps the memory of the host func TestAutomaticMaxThreadsHonorsTheGoMemoryLimit(t *testing.T) { + if total := memory.TotalSysMemory(); total != 0 && total < 640<<20 { + t.Skip("the system memory is lower than the limit") + } + t.Setenv("GOMEMLIMIT", "640MiB") previous := debug.SetMemoryLimit(640 << 20) t.Cleanup(func() { debug.SetMemoryLimit(previous) }) From 860023ea08ac49090a2f35d048fda6d15d97b1c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Dunglas?= Date: Wed, 2 Dec 2026 14:22:45 +0100 Subject: [PATCH 4/4] fix: log max_threads auto after the clamp The debug log reported the memory-based estimate even when it was below num_threads, while the effective limit was num_threads. --- phpmainthread.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/phpmainthread.go b/phpmainthread.go index f11341708c..26d5b3ac4c 100644 --- a/phpmainthread.go +++ b/phpmainthread.go @@ -283,8 +283,7 @@ func (mainThread *phpMainThread) setAutomaticMaxThreads() { mainThread.maxThreads = mainThread.numThreads * 2 return } - maxAllowedThreads := availableMemory / uint64(perThreadMemoryLimit) - mainThread.maxThreads = int(maxAllowedThreads) + mainThread.maxThreads = max(int(availableMemory/uint64(perThreadMemoryLimit)), mainThread.numThreads) if globalLogger.Enabled(globalCtx, slog.LevelDebug) { globalLogger.LogAttrs(globalCtx, slog.LevelDebug, "Automatic thread limit", slog.Int("perThreadMemoryLimitMB", int(perThreadMemoryLimit/1024/1024)), slog.Int("availableMemoryMB", int(availableMemory/1024/1024)), slog.Int("maxThreads", mainThread.maxThreads))