编程 PHP 8.6 的 Io\Poll:900 连接下吞吐 3.88 倍,stream_select 在 1028 连接处失败

2026-11-21 20:01:24

PHP 8.6 的 Io\Poll:900 连接下吞吐 3.88 倍,stream_select 在 1028 连接处失败

PHP 8.6 将加入新的 Polling API(RFC),它是 PHP Foundation “Stream Improvement” 项目的一部分。Tideways 的 Tim Düsterhus 用一个 RFC 862 echo server 做了对比:客户端发什么,服务器就回什么。测试结果很直接:900 条已建立连接时,Polling API 实现的吞吐是旧实现的 3.88 倍,p99 延迟只有旧实现的 34%;stream_select() 在约 1000 条连接时失败,Polling API 在测试中处理了 5000 条空闲连接,性能保持稳定。

示例代码在 tideways/blog-php-86-polling-api-example。下面的数字来自同一套 echo 逻辑、同一个 Node.js 客户端,只更换了轮询 API。这是 PHP 核心 API 层的变化,不是某个框架或托管服务的卖点。

旧 API:stream_select() 的问题

PHP 8.6 之前,轮询连接用 stream_select()。它是一个五参数函数,基本直接映射到 POSIX 的 select(2)。问题有三类:

  • API 不保存状态,操作系统每次都要从连接列表开头检查一遍,才能找出有数据的少数连接。
  • POSIX 默认把 stream_select()(以及底层 select(2))检查的最高文件描述符限制在 1024。
  • 可以把 stream_select() 迁移到 poll(2) 来绕开文件描述符上限,但调用之间不保存状态带来的性能问题仍然存在。

不保存状态的另一个直接后果是:PHP 应用必须自己做全部清理和映射工作,包括决定每次要检查哪些连接,以及把 stream_select() 保留的数组条目映射回应用状态。这里很容易出现难以诊断的细微错误。

PHP 8.5 实测:连接数一上来,等待时间压过工作时间

echo server 会分别测量 stream_select() 调用耗时,以及处理就绪连接耗时。Node.js 客户端从 0 到 5000 逐步打开空闲连接,不做读写;然后用 8 条新连接反复发请求,测量 echo 回复到达的时间。

主事件循环剥离到最小形态,$connections 是一个自定义类,负责连接清理和映射,约 100 行代码。

$timeoutSeconds = 0;
$timeoutMicroseconds = 200_000;

$listener = new Listener(9501);
$connections = new ConnectionSet($listener);

for (;;) {
    $read = $connections->readSet();
    $write = $connections->writeSet();
    $except = null;

    $count = stream_select($read, $write, $except, $timeoutSeconds, $timeoutMicroseconds);

    if ($count === false) {
        fwrite(STDERR, "stream_select() failed\n");
        exit(1);
    }

    foreach ($read as $id => $stream) {
        if ($id === ConnectionSet::SERVER_ID) {
            for (;;) {
                $accepted = $listener->accept();
                if ($accepted === null) {
                    break;
                }
                $connections->add($accepted);
            }
        } else {
            $conn = $connections->get($id);
            if ($conn->readAndEcho()) {
                $connections->syncInterest($id);
            } else {
                $connections->remove($id);
            }
        }
    }

    foreach ($write as $id => $stream) {
        $conn = $connections->getMaybe($id);
        if ($conn === null) {
            // Already closed while handling its read event.
            continue;
        }
        if ($conn->flush()) {
            $connections->syncInterest($id);
        } else {
            $connections->remove($id);
        }
    }
}

/**
 * ConnectionSet is a class we needed to implement ourselves.
 * It performs the housekeeping to map the connections back
 * to the class keeping the application state.
 */
final class ConnectionSet
{
    // 100 lines of code
}

PHP 8.5 服务器的输出:

listening on :9501
select85 conns=  8 94.3 MiB/s 165738 calls/s wait=  1.6 us/call work=  4.3 us/call
select85 conns=264 38.2 MiB/s 11909 calls/s wait= 59.7 us/call work= 24.0 us/call
select85 conns=520 25.1 MiB/s 8336 calls/s wait= 91.9 us/call work= 27.7 us/call
select85 conns=900 24.6 MiB/s 6630 calls/s wait= 118.0 us/call work= 32.4 us/call
select85 conns=908 21.6 MiB/s 5640 calls/s wait= 142.7 us/call work= 34.0 us/call
PHP Warning: stream_select(): You MUST recompile PHP with a larger value of FD_SETSIZE.
It is set to 1024, but you have descriptors numbered at least as high as 1033.
 --enable-fd-setsize=2048 is recommended, but you may want to set it
to equal the maximum number of open files supported by your system,
in order to avoid seeing this error again at a later date. in server-select85.php on line 134
stream_select() failed with 1028 connections open
select85 conns=1028 12.6 MiB/s 3307 calls/s wait= 269.8 us/call work= 32.0 us/call

Node.js 客户端连 PHP 8.5 服务器:

127.0.0.1:9501 active=8 size=512B window=5s
 idle req/s p50 ms p99 ms max ms
 0 187762 0.031 0.113 3.801
 256 121190 0.058 0.187 2.648
 512 72233 0.100 0.279 2.302
 900 45840 0.156 0.387 2.706
Only 1028 idle connections could be opened: ECONNREFUSED.

最显眼的是那条 PHP 警告:某个连接被分配到的文件描述符,已经超过 select(2) 在编译时设置的上限。虽然可以重新编译 PHP 来增大 FD_SETSIZE,但这会让运维更麻烦,发行版提供的预编译二进制包也不能直接用了。而且即使把连接数限制在 FD_SETSIZE 以下,单个连接仍可能被分配到超过该值的文件描述符。

服务端和客户端的数字也说明:空闲连接越多,吞吐越低,stream_select() 的等待时间升得尤其快。8 条连接时是 94.3 MiB/s、wait=1.6 us/call;900 条时降到 24.6 MiB/s、wait=118.0 us/call;1028 条时是 12.6 MiB/s、wait=269.8 us/call。等待时间已经明显压过工作时间。

新 Polling API:状态留在 OS,元数据挂在 Handle 上

操作系统提供的可扩展轮询接口,比如 Linux 的 epoll,依赖调用之间保留状态,因此 stream_select() 的 API 与它们根本不兼容;它要求用户手动实现连接清理,开发体验也不好。

新的 Polling API 不只是换了底层机制,还提供了一套可扩展、对开发者更友好的接口,设计时考虑了现代 PHP 特性。比如每个注册的 polling Handle(例如一个网络连接)都可以关联任意元数据,数组或对象都行。连接上有新活动时,返回的 Watcher 实例可以取回这些元数据,应用状态直接可用,不需要容易出错的手动清理。

在 Linux 上,Backend::Auto 会自动选择 epoll。服务器实现和 stream_select() 版本相同,只换了轮询循环;读写 socket 的代码不用改。自定义的 ConnectionSet 不再需要,因为元数据直接存在 Handle 旁边,由 Watcher 返回。整个服务器实现大约少了 90 行代码。

主事件循环剥离到最小形态,不需要自定义清理:

use Io\Poll\Context;
use Io\Poll\Event;
use Io\Poll\Watcher;
use Time\Duration;

// The Backend defaults to Backend::Auto, selecting the best
// available backend. On Linux this will be Backend::Epoll.
$poll = new Context();
$timeout = Duration::fromMilliseconds(200);

// The same listener class as for the `stream_select()` example.
$listener = new Listener(9601);

$poll->add(
    new StreamPollHandle($listener->stream),
    [Event::Read],
    $listener
);

for (;;) {
    $ready = $poll->wait($timeout);

    foreach ($ready as $watcher) {
        $subject = $watcher->getData();

        if ($subject instanceof Listener) {
            for (;;) {
                $accepted = $subject->accept();
                if ($accepted === null) {
                    break;
                }
                $poll->add(
                    new StreamPollHandle($accepted->stream),
                    [Event::Read],
                    $accepted,
                );
            }
        } elseif ($subject instanceof EchoConnection) {
            $alive = true;

            if ($watcher->hasTriggered(Event::Read)) {
                $alive = $subject->readAndEcho();
            }

            if ($alive && $watcher->hasTriggered(Event::Write)) {
                $alive = $subject->flush();
            }

            if (
                $watcher->hasTriggered(Event::Error)
                || $watcher->hasTriggered(Event::HangUp)
            ) {
                $alive = false;
            }

            if ($alive) {
                syncInterest($watcher, $subject);
            } else {
                $watcher->remove();
                $subject->close();
            }
        }
    }
}

function syncInterest(Watcher $watcher, EchoConnection $conn): void
{
    $wantWrite = $conn->hasPendingOutput();
    $isRegistered = in_array(
        Event::Write,
        $watcher->getWatchedEvents(),
        true,
    );

    if ($wantWrite === $isRegistered) {
        return;
    }

    if ($wantWrite) {
        $watcher->modifyEvents([Event::Read, Event::Write]);
    } else {
        $watcher->modifyEvents([Event::Read]);
    }
}

PHP 8.6 epoll 后端:5000 空闲连接下仍稳定

PHP 8.6 服务器使用 Polling API 的 epoll 后端,输出如下:

listening on :9601
poll86 (Epoll) conns=   8 90.5 MiB/s 183921 calls/s wait= 1.5 us/call work= 3.8 us/call
poll86 (Epoll) conns= 264 89.2 MiB/s 176071 calls/s wait= 1.4 us/call work= 4.2 us/call
poll86 (Epoll) conns= 520 83.6 MiB/s 158779 calls/s wait= 1.5 us/call work= 4.7 us/call
poll86 (Epoll) conns= 908 86.4 MiB/s 167991 calls/s wait= 1.5 us/call work= 4.4 us/call
poll86 (Epoll) conns=2008 88.7 MiB/s 177455 calls/s wait= 1.5 us/call work= 4.1 us/call
poll86 (Epoll) conns=5000 33.2 MiB/s 67404 calls/s wait=10.0 us/call work= 4.8 us/call
poll86 (Epoll) conns=5008 76.0 MiB/s 153213 calls/s wait= 2.5 us/call work= 3.9 us/call

Node.js 客户端连 PHP 8.6 服务器:

127.0.0.1:9601 active=8 size=512B window=5s
 idle req/s p50 ms p99 ms max ms
 0 181275 0.035 0.132 3.588
 256 181559 0.036 0.110 3.533
 512 168620 0.036 0.143 3.957
 900 178061 0.036 0.132 3.804
 2000 177611 0.036 0.128 4.262
 5000 160209 0.043 0.106 2.812

和 PHP 8.5 的 stream_select() 服务器不同,PHP 8.6 使用 Polling API 的服务器能处理客户端配置的 5000 条空闲连接,并在整个测试过程中保持稳定性能。8 条连接时 90.5 MiB/s,900 条时 86.4 MiB/s,2008 条时 88.7 MiB/s;5000 条那行有回落,33.2 MiB/s、wait=10.0 us/call,但连接继续增加到 5008 条时又回到 76.0 MiB/s。客户端侧在 5000 条空闲连接下仍有 160209 req/s,p50 0.043 ms,p99 0.106 ms。

结论:API 层的变化比后端更值得看

新 Polling API 明显达到了可扩展性目标,但更大的价值在用户态 API:只用 PHP 标准库,就能在单屏代码里构建一个生产可用的 event loop。

还有一些实际服务常用功能没有覆盖,比如按计划唤醒 event loop,用 Handle 抽象实现超时来关闭空闲连接。这些内容在 PHP 8.7 additions RFC 中讨论。

谁该用:

  • 用 PHP 写常驻 TCP/Unix socket 服务,连接数会过千,或者需要给每个连接挂应用状态。
  • 已经自己维护 event loop,受够了 stream_select() 的 FD_SETSIZE 限制和手写 ConnectionSet 映射。
  • 想在 PHP 标准库范围内实现一个可读、可维护的轮询循环,而不是引入完整异步框架。

谁不必用:

  • 短生命周期的 FPM/CGI 请求,一次请求只处理少量连接。
  • 连接数长期在个位数,stream_select() 的等待时间还不构成瓶颈。
  • 已经用 ReactPHP、Swoole、AMPHP 等框架,且框架尚未适配 PHP 8.6;等框架封装即可,不必为了一个 CLI 小工具直接迁移。

升级前要确认运行环境是 PHP 8.6。Linux 上默认走 epoll;其他平台由 Backend::Auto 选择可用的最佳后端。旧代码里的 stream_select() 仍然能用,但 1024 文件描述符限制和每次从头扫描的成本不会消失。

复制全文 生成海报 PHP 8.6 Io\Poll epoll 网络编程

推荐文章

程序员茄子在线接单