Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion docs/performance.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
24 changes: 24 additions & 0 deletions internal/memory/memory.go
Original file line number Diff line number Diff line change
@@ -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
}
36 changes: 36 additions & 0 deletions internal/memory/memory_test.go
Original file line number Diff line number Diff line change
@@ -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())
}
13 changes: 7 additions & 6 deletions phpmainthread.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
}

Expand Down
13 changes: 13 additions & 0 deletions phpmainthread_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"net/http/httptest"
"path/filepath"
"runtime"
"runtime/debug"
"sync"
"sync/atomic"
"testing"
Expand Down Expand Up @@ -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")
Expand Down
Loading