Running PHP as an event-driven network server

Why PHP's execution model, not the language, kept it from holding connections open, and what a select-based event loop must handle: partial writes, idle expiry and a response that never ends.

April 20074 min readRuntimeOpen sourceWebchat 2

Heavy horizontal umber and dull violet ridges fill the lower canvas under a bare stained band and thin cold white with orange flecks.

In 2006, letting people join IRC from nothing but a browser meant building without WebSocket, Node.js, or server push. Because a browser could neither open a TCP socket to an IRC server nor accept unsolicited events from a web server, a browser IRC client needed a backend process holding two persistent connections per user: an open HTTP response to push events down to the page, and a TCP connection to the IRC server, routing messages between them.

PHP’s conventional execution model, a short-lived, shared-nothing process per request under Apache, tears down memory and open descriptors as soon as a response finishes. For ordinary request-response pages that lifecycle is an asset, not least because leaked state rarely lives long enough to matter, though it leaves no way to hold either a streaming HTTP response or an IRC socket open across requests. Getting around that at the time meant switching to a Java application server, embedding a Flash or Java applet in the page, or falling back to HTTP polling with its latency and request overhead.

The constraint, however, was PHP’s execution model rather than the language itself. PHP exposes POSIX select through socket_select and supports non-blocking sockets. Running PHP outside Apache as one persistent process around a select loop turns it into a single-threaded, event-driven network server, years before Node.js made that architecture common in scripting languages. To serve browser IRC on that model, I wrote an event-loop daemon library of about 700 lines of PHP and built a chat server on top of it: one long-running process acting as both the HTTP server and the IRC client for every connected user, with a design target of thousands of browser connections and thousands of IRC connections in a single process.

Multiplexing sockets around select

Because socket_select mutates its descriptor sets in place, each pass of the loop rebuilds the read, write, and exception sets from the active sockets and waits for up to two seconds. When descriptors become ready, the loop accepts new connections on listening sockets, appends incoming bytes from readable sockets to each connection’s read buffer before invoking its read handler, and flushes queued output on writable sockets. Applications stay decoupled from the socket machinery by subclassing base server and client classes and filling in the event hooks.

Without a process or thread per connection, the daemon itself has to handle partial writes and non-blocking execution. Writes on non-blocking sockets go out only as far as the kernel send buffer allows, leaving any partial-write remainder queued for the next writable event, so a slow reader costs buffer space rather than a blocked process. The companion constraint is the one every single-threaded event loop shares: one blocking callback stalls every connection in the process, so protocol parsing and message routing have to remain non-blocking and brief.

Idle expiry runs on the same loop rather than a watchdog thread or external sweeper. Roughly every two seconds, bounded by the socket_select timeout when the server is quiet, the loop invokes a timer hook on every active connection. When a dropped browser session or half-open TCP connection can leave both an HTTP response and a backend IRC socket lingering, pruning idle connections on that interval keeps descriptor counts and memory bounded across long uptimes.

Streaming IRC over an open HTTP response

Because the chat server speaks HTTP directly, there is no Apache in front of it; the same PHP process serves the page’s HTML and JavaScript alongside the live chat endpoints. Running a standalone HTTP daemon gives up the deployment simplicity of dropping scripts onto ordinary PHP hosting, a trade-off that later led me to turn down this exact architecture for a PHP OpenSocial server, yet here it removes any IPC boundary between HTTP handling and the live IRC sockets.

To push IRC events down to the browser, the server uses Comet streaming, the long-lived HTTP push technique of the mid-2000s. When a user connects, the page opens a hidden iframe on a /get URL carrying the nickname and target IRC server. The daemon answers with HTTP headers that omit Content-Length so the browser treats the document as still loading, leaves the response open, establishes the user’s TCP connection to the IRC server, and returns a session key pairing the two sockets.

Each incoming IRC event is appended to that open HTTP response as an inline <script> tag, such as chat.onMessage('alice', '#php', 'hello');, which the browser parses and executes as the bytes arrive. In Internet Explorer, streaming chunks into a standard iframe triggers the browser’s navigation click sound on every write, so the page places the iframe inside an ActiveX htmlfile document, a known Comet workaround of the period, to suppress it. Outbound chat messages travel the other way as ordinary Ajax requests carrying the session key, which the daemon resolves in memory to write onto the user’s paired IRC socket.

Chris Chabot, April 2007