PHP set_time_limit() and PHP-FPM request_terminate_timeout: coordination for graceful termination
0 reputation · 07 Aug 2024, 22:21 UTC
0 reputation · 07 Aug 2024, 22:21 UTC
The goal is to allow a long‑running PHP script to clean up resources when either the internal execution limit or the FPM hard timeout is reached, without relying on external process management.
While set_time_limit() can reset or extend the CPU‑time limit tracked by PHP, the FPM setting request_terminate_timeout forces a worker kill after a wall‑clock interval, bypassing PHP’s signal handling. The interaction between these two limits is not explicitly defined in the documentation, leaving uncertainty about which timeout takes precedence and whether any cleanup code can execute after an FPM‑initiated termination.
30275 reputation · 08 Aug 2024, 05:42 UTC
The FPM hard timeout (request_terminate_timeout) always takes precedence over PHP’s internal execution limit (set_time_limit() or max_execution_time). When the FPM limit is exceeded, the worker is terminated by SIGTERM then SIGKILL, and PHP gets no chance to run shutdown functions. Only when PHP’s limit is reached first does a fatal error occur, allowing register_shutdown_function(), destructors, or fastcgi_finish_request() to execute.
request_terminate_timeout is a wall‑clock limit enforced by the PHP‑FPM process manager; exceeding it sends SIGTERM then SIGKILL to the worker.set_time_limit() only changes PHP’s internal soft limit; it cannot affect or disable the FPM hard limit.request_terminate_timeout; it can only be adjusted in the pool configuration (e.g., www.conf) and reloaded via FPM.request_terminate_timeout (look in /etc/php/*/fpm/pool.d/www.conf or the equivalent).set_time_limit() or max_execution_time. For example, if you need up to 40 seconds of PHP work, set request_terminate_timeout 50.set_time_limit() (or rely on max_execution_time) to define the soft limit you want; this will trigger a fatal error and allow cleanup via register_shutdown_function().sudo systemctl reload php8.2-fpm or the appropriate service). No PHP‑only method exists.To confirm whether the FPM limit is the active constraint, please provide the current value of request_terminate_timeout from your pool configuration. If it is lower than the PHP limit you are setting, the FPM timeout will preempt cleanup; otherwise PHP’s limit will govern.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.