Cancellation and timeouts

suggest change

Every call that waits on something outside your process (an HTTP request, a database query, a child process, a socket) can hang. Without a timeout, one slow dependency ties up a PHP-FPM worker or blocks a CLI job forever.

PHP has no general cancellation mechanism like Go's context.Context or .NET's CancellationToken. You put together a few separate tools:

Tool What it limits Where it works
max_execution_time / set_time_limit() the whole script, as a fatal error everywhere
cURL CURLOPT_*TIMEOUT* options one HTTP request cURL
default_socket_timeout, stream_set_timeout(), context timeout stream connect and reads streams
driver options and server settings DB connect and query time PDO, mysqli
proc_open() + stream_select() + proc_terminate() child processes Unix
pcntl_alarm() + signal handler any code, as an exception CLI on Unix
deadline and cancellation token objects your own loops and call chains everywhere
TimeoutCancellation, Timer\timeout() async operations Amp, ReactPHP

Script time limit: max_execution_time

max_execution_time (php.ini) and set_time_limit() stop the script with a fatal error once the limit is reached. The default is 30 seconds for web requests and 0 (no limit) for the CLI.

<?php
set_time_limit(2);

register_shutdown_function(function (): void {
    $error = error_get_last();
    if ($error !== null && str_contains($error['message'], 'Maximum execution time')) {
        // Fatal errors cannot be caught, but shutdown functions still run.
        error_log('Request killed by time limit');
    }
});

$i = 0;
while (true) {
    $i++;
}

Output:

PHP Fatal error:  Maximum execution time of 2 seconds exceeded in /app/limit.php on line 14
Stack trace:
#0 {main}
Request killed by time limit

Things to know:

Treat it as a last line of defense against runaway loops, not as a way to bound waiting. For that, set timeouts on the I/O itself.

In PHP-FPM, request_terminate_timeout (in the pool config) is a wall-clock limit. When it is reached FPM kills the worker process outright, without running shutdown functions. The web server has its own limit too (for example nginx fastcgi_read_timeout). Keep these a little higher than the timeouts you set in code, so your code gets a chance to fail cleanly first.

HTTP requests with cURL

cURL has a separate timeout for establishing the connection and for the whole transfer:

<?php
$ch = curl_init('https://httpbin.org/delay/5');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CONNECTTIMEOUT => 3,   // DNS + TCP + TLS handshake
    CURLOPT_TIMEOUT        => 2,   // whole request, including the connect phase
]);

$body = curl_exec($ch);
if ($body === false) {
    if (curl_errno($ch) === CURLE_OPERATION_TIMEDOUT) {
        echo "Timeout: ", curl_error($ch), "\n";
    } else {
        echo "Error: ", curl_error($ch), "\n";
    }
}

Output:

Timeout: Operation timed out after 2001 milliseconds with 0 bytes received

Useful options:

Option Meaning
CURLOPT_CONNECTTIMEOUT / _MS max time to connect; the default is 300 seconds
CURLOPT_TIMEOUT / _MS max time for the whole request; the default is 0, no limit
CURLOPT_LOW_SPEED_LIMIT + CURLOPT_LOW_SPEED_TIME abort if slower than N bytes/s for M seconds; good for large downloads where a total timeout is hard to choose
CURLOPT_NOSIGNAL set to true when using millisecond timeouts below 1 second with a libcurl built without an async DNS resolver

The defaults mean that a plain curl_exec() can wait for minutes. Always set both timeouts.

Cancelling a transfer from a callback

cURL calls a progress function during the transfer. Returning a non-zero value aborts it. You can use that to cancel a download on any condition you like, for example a size limit or a cancellation flag:

<?php
$maxBytes = 1_000_000;

$ch = curl_init('https://proof.ovh.net/files/100Mb.dat');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER   => true,
    CURLOPT_CONNECTTIMEOUT   => 5,
    CURLOPT_NOPROGRESS       => false, // required, or the callback is never called
    CURLOPT_XFERINFOFUNCTION => function ($ch, int $dlTotal, int $dlNow, int $ulTotal, int $ulNow) use ($maxBytes): int {
        return $dlNow > $maxBytes ? 1 : 0; // non-zero = abort
    },
]);

if (curl_exec($ch) === false && curl_errno($ch) === CURLE_ABORTED_BY_CALLBACK) {
    echo "Cancelled: ", curl_error($ch), "\n";
}

Output:

Cancelled: Callback aborted

With curl_multi_* you can run several requests at once and stop waiting for all of them at a common deadline; see Using multi curl to make multiple POST requests.

Streams and sockets

Functions that use streams (file_get_contents('http://...'), fopen(), fsockopen(), stream_socket_client()) have their own timeout settings.

The timeout option of the http context is a read timeout in seconds (a float is allowed). It also defaults to the default_socket_timeout ini setting, which is 60 seconds:

<?php
$context = stream_context_create([
    'http' => ['timeout' => 2.5],
]);

$body = @file_get_contents('https://httpbin.org/delay/5', false, $context);
if ($body === false) {
    echo "Failed: ", error_get_last()['message'] ?? 'unknown error', "\n";
}

This is not a limit on the whole request: a server that sends one byte every 2 seconds never triggers it. If you need a hard limit on the total time, use cURL.

For raw sockets, pass a connect timeout to stream_socket_client() and set a read timeout with stream_set_timeout(). A read that times out does not fail; it returns what it has so far (often an empty string), and stream_get_meta_data() reports timed_out:

<?php
$fp = stream_socket_client('tcp://example.com:80', $errno, $errstr, 3.0); // connect timeout
if ($fp === false) {
    throw new RuntimeException("Connect failed: $errstr ($errno)");
}

stream_set_timeout($fp, 2); // read timeout: 2 seconds (an optional 3rd arg adds microseconds)

fwrite($fp, "GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n");

$response = '';
while (!feof($fp)) {
    $chunk = fread($fp, 8192);
    if (stream_get_meta_data($fp)['timed_out']) {
        fclose($fp);
        throw new RuntimeException('Read timed out');
    }
    $response .= $chunk;
}
fclose($fp);

echo strlen($response), " bytes\n";

Database queries

There are two different timeouts: how long to wait for a connection, and how long a query may run. The second has to be enforced by the database server, because only the server can stop a running query.

<?php
// MySQL / MariaDB
$pdo = new PDO('mysql:host=db;dbname=app', 'user', 'secret', [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_TIMEOUT => 3, // connect timeout in seconds
]);

// Limit SELECT statements to 1000 ms (MySQL 5.7.8+)
$pdo->exec('SET SESSION max_execution_time = 1000');

try {
    $pdo->query('SELECT customer_id, SUM(total) FROM orders GROUP BY customer_id')->fetchAll();
} catch (PDOException $e) {
    echo $e->getMessage(), "\n";
}

A query that runs too long fails with MySQL error 3024 (Query execution was interrupted, maximum statement execution time exceeded). Don't test this with SELECT SLEEP(5): the server just ends the sleep early and the query returns 1 without an error. For a single query you can use an optimizer hint: SELECT /*+ MAX_EXECUTION_TIME(1000) */ .... On MariaDB the equivalent is SET SESSION max_statement_time = 1 (in seconds).

PostgreSQL has statement_timeout, which applies to every statement:

<?php
$pdo = new PDO('pgsql:host=db;dbname=app;connect_timeout=3', 'user', 'secret', [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
$pdo->exec("SET statement_timeout = '2s'");

try {
    $pdo->query('SELECT pg_sleep(5)');
} catch (PDOException $e) {
    echo $e->getCode(), "\n";    // 57014
    echo $e->getMessage(), "\n";
}

Output:

57014
SQLSTATE[57014]: Query canceled: 7 ERROR:  canceling statement due to statement timeout

With mysqli, set MYSQLI_OPT_CONNECT_TIMEOUT and MYSQLI_OPT_READ_TIMEOUT with $mysqli->options() before calling real_connect().

Child processes

exec(), shell_exec() and proc_close() wait for the command for as long as it runs. To put a limit on it, start it with proc_open(), read its output with stream_select() until a deadline, and kill it if the deadline passes:

<?php
function runWithTimeout(array $command, float $timeout): string
{
    $process = proc_open($command, [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes);
    if ($process === false) {
        throw new RuntimeException('Cannot start process');
    }

    $open = [1 => $pipes[1], 2 => $pipes[2]];
    $output = [1 => '', 2 => ''];
    foreach ($open as $pipe) {
        stream_set_blocking($pipe, false);
    }

    $deadline = hrtime(true) + (int) ($timeout * 1e9);

    while ($open) {
        $left = ($deadline - hrtime(true)) / 1e9;
        if ($left <= 0) {
            proc_terminate($process); // sends SIGTERM
            foreach ($open as $pipe) {
                fclose($pipe);
            }
            proc_close($process);
            throw new RuntimeException(sprintf('Command timed out after %.1f s', $timeout));
        }

        $read = array_values($open);
        $write = $except = null;
        $seconds = (int) $left;
        if (stream_select($read, $write, $except, $seconds, (int) (($left - $seconds) * 1e6)) === false) {
            break;
        }

        foreach ($read as $pipe) {
            $fd = array_search($pipe, $open, true);
            $output[$fd] .= fread($pipe, 8192);
            if (feof($pipe)) {
                fclose($pipe);
                unset($open[$fd]);
            }
        }
    }

    $exitCode = proc_close($process);
    if ($exitCode !== 0) {
        throw new RuntimeException("Command failed ($exitCode): " . $output[2]);
    }
    return $output[1];
}

echo runWithTimeout(['echo', 'hello'], 1.0);

try {
    runWithTimeout(['sleep', '5'], 1.0);
} catch (RuntimeException $e) {
    echo $e->getMessage(), "\n";
}

Output:

hello
Command timed out after 1.0 s

Passing the command as an array (PHP 7.4+) runs it without a shell, so proc_terminate() signals the command itself rather than a sh process that started it. If the program ignores SIGTERM, follow up with proc_terminate($process, 9) (SIGKILL). stream_select() does not work on process pipes on Windows.

Simpler alternatives: prefix the command with the coreutils timeout program (['timeout', '5', 'convert', ...], exit code 124 on timeout), or use symfony/process, which has $process->setTimeout(5) and throws ProcessTimedOutException. See also Spawning non-blocking processes with proc_open.

Timing out arbitrary code with SIGALRM

In CLI scripts on Unix you can ask the kernel to send SIGALRM after N seconds and throw an exception from the signal handler. Unlike max_execution_time, it counts wall-clock time, and the result is an exception you can catch, so finally blocks run:

<?php
final class TimeoutException extends RuntimeException {}

pcntl_async_signals(true); // run handlers as soon as the signal arrives

function withTimeout(int $seconds, callable $fn): mixed
{
    pcntl_signal(SIGALRM, function () use ($seconds): void {
        throw new TimeoutException("Timed out after {$seconds}s");
    }, false); // false: don't restart interrupted system calls

    pcntl_alarm($seconds);
    try {
        return $fn();
    } finally {
        pcntl_alarm(0);                 // cancel the pending alarm
        pcntl_signal(SIGALRM, SIG_DFL);
    }
}

echo withTimeout(2, fn() => 'fast'), "\n";

try {
    withTimeout(1, function (): void {
        sleep(10);
        echo "never printed\n";
    });
} catch (TimeoutException $e) {
    echo $e->getMessage(), "\n";
}

Output:

fast
Timed out after 1s

Limits of this approach:

Deadlines across several calls

A per-call timeout is not enough when one operation makes several calls. If a request handler must answer within 5 seconds and calls three services, each with a 5 second timeout, it can take 15 seconds.

The fix is to compute a deadline once and pass it down. Each call uses the time that is left:

<?php
final class TimeoutException extends RuntimeException {}

final class Deadline
{
    private function __construct(private readonly int $atNs) {}

    public static function in(float $seconds): self
    {
        // hrtime() is monotonic, unlike microtime(), so clock changes don't affect it
        return new self(hrtime(true) + (int) ($seconds * 1e9));
    }

    public function remaining(): float
    {
        return max(0.0, ($this->atNs - hrtime(true)) / 1e9);
    }

    public function check(): void
    {
        if ($this->remaining() <= 0.0) {
            throw new TimeoutException('Deadline exceeded');
        }
    }
}

function fetch(string $url, Deadline $deadline): string
{
    $deadline->check();
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_NOSIGNAL       => true,
        CURLOPT_TIMEOUT_MS     => max(1, (int) ($deadline->remaining() * 1000)),
    ]);
    $body = curl_exec($ch);
    if ($body === false) {
        throw curl_errno($ch) === CURLE_OPERATION_TIMEDOUT
            ? new TimeoutException("Timed out fetching $url")
            : new RuntimeException(curl_error($ch));
    }
    return $body;
}

$deadline = Deadline::in(3.0);
try {
    $user   = fetch('https://httpbin.org/delay/1', $deadline);
    $orders = fetch('https://httpbin.org/delay/1', $deadline);
    $promos = fetch('https://httpbin.org/delay/2', $deadline); // only ~1 s left
} catch (TimeoutException $e) {
    echo $e->getMessage(), "\n";
}

Output:

Timed out fetching https://httpbin.org/delay/2

The same deadline can drive stream_set_timeout(), a database max_execution_time, or a retry loop that stops retrying when no time is left.

Cooperative cancellation

Long-running loops (batch jobs, queue workers, imports) should check a cancellation flag between units of work, so they can stop at a safe point. A small token object makes this explicit and testable:

<?php
final class CancelledException extends RuntimeException {}

final class CancellationToken
{
    private ?string $reason = null;

    public function cancel(string $reason = 'cancelled'): void
    {
        $this->reason ??= $reason;
    }

    public function isCancelled(): bool
    {
        return $this->reason !== null;
    }

    public function throwIfCancelled(): void
    {
        if ($this->reason !== null) {
            throw new CancelledException($this->reason);
        }
    }
}

function importRows(iterable $rows, CancellationToken $token): int
{
    $count = 0;
    foreach ($rows as $row) {
        $token->throwIfCancelled(); // stop between rows, never in the middle of one
        // ... insert $row in its own transaction ...
        usleep(300_000);
        $count++;
    }
    return $count;
}

$token = new CancellationToken();

pcntl_async_signals(true);
pcntl_signal(SIGINT,  fn() => $token->cancel('interrupted by Ctrl+C'));
pcntl_signal(SIGTERM, fn() => $token->cancel('terminated'));

try {
    $n = importRows(range(1, 100), $token);
    echo "Imported $n rows\n";
} catch (CancelledException $e) {
    echo "Stopped: ", $e->getMessage(), "\n";
}

Pressing Ctrl+C after a second prints:

^CStopped: interrupted by Ctrl+C

The signal handler only sets a flag; the work stops at the next check. This is how you get graceful shutdown in queue workers: docker stop and Kubernetes send SIGTERM, wait a grace period, then send SIGKILL. On Windows, sapi_windows_set_ctrl_handler() can set the same flag for Ctrl+C.

A token like this can also be cancelled from code (for example when another request found the answer first) or combined with a Deadline by checking both in the same place.

Detecting client disconnects

When a browser closes the connection, PHP does not notice until it tries to send output. By default (ignore_user_abort is off) it then stops the script, running shutdown functions but not finally blocks. To handle disconnects yourself:

<?php
ignore_user_abort(true); // keep running after a disconnect; we check it ourselves

foreach ($reportChunks as $chunk) {
    echo render($chunk);
    flush(); // a disconnect is only detected when output is sent

    if (connection_aborted()) {
        cleanUpTemporaryFiles();
        exit;
    }
}

Use ignore_user_abort(true) without the check for work that must finish even if the user leaves, such as completing a payment. For work that should continue after the response has been sent, PHP-FPM has fastcgi_finish_request().

Async code: Amp and ReactPHP

Event-loop libraries have real cancellation built in, because many operations share one process and can be abandoned without blocking anything.

In Amp v3 (built on fibers), most functions accept a Cancellation. TimeoutCancellation cancels after a time, and DeferredCancellation lets you cancel manually:

<?php
require 'vendor/autoload.php';

use Amp\CancelledException;
use Amp\TimeoutCancellation;
use function Amp\async;
use function Amp\delay;

$future = async(function (): string {
    delay(5); // pretend this is a slow request
    return 'done';
});

try {
    echo $future->await(new TimeoutCancellation(1)), "\n";
} catch (CancelledException $e) {
    echo "Gave up: ", $e->getMessage(), "\n";
}

await() stops waiting after 1 second. To stop the work itself, pass the same cancellation into the operation, for example delay(5, cancellation: $cancellation) or $httpClient->request($request, $cancellation).

In ReactPHP, React\Promise\Timer\timeout() from react/promise-timer rejects with a TimeoutException and cancels the underlying promise, which for an HTTP request closes the connection:

<?php
use React\Http\Browser;
use function React\Promise\Timer\timeout;

$browser = new Browser();

timeout($browser->get('https://httpbin.org/delay/5'), 2.0)->then(
    fn($response) => print("Status: {$response->getStatusCode()}\n"),
    fn(Throwable $e) => print("Failed: {$e->getMessage()}\n"),
);

See Using Amp event loop for an introduction to Amp.

Checklist

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents