High-Performance Servers with Swoole
Serve thousands of connections with coroutine-based Swoole.
What Swoole Is
Swoole (and its fork OpenSwoole) is a C extension that turns PHP into a high-performance, coroutine-based, event-driven runtime. Instead of PHP-FPM spawning a process per request, a Swoole server boots your app once and keeps it resident in memory, serving requests from a pool of long-lived workers with built-in coroutines. The result: order-of-magnitude throughput gains and native concurrency inside a single request.
The Persistent HTTP Server
The classic example: a full HTTP server in a script. It listens, dispatches each request to a worker, and never re-bootstraps the framework. Note this requires ext-swoole — it does not run on stock PHP CLI.
<?php
$server = new Swoole\Http\Server('0.0.0.0', 9501);
$server->set(['worker_num' => 4]);
$server->on('request', function ($request, $response) {
$response->header('Content-Type', 'application/json');
$response->end(json_encode(['hello' => $request->server['request_uri']]));
});
echo "listening on :9501\n";
$server->start();All lessons in this course
- The PHP Concurrency Model
- PHP 8.1 Fibers
- Event Loops with ReactPHP
- High-Performance Servers with Swoole