PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

New plugin: Connection multiplexing with PHP and MySQL

Note: This article was originally published at Planet PHP on 29 August 2012.
Planet PHP

Here comes the next open source mysqlnd plugin prototype: PECL/mysqlnd_mux. The PHP mysqlnd connection multiplexing plugin shares a connection to MySQL between multiple user connection handles. Connection multiplexing aims to reduce connect time and lowers the total number of concurrenly opened connections. The first is primarily a benefit for the client, the latter is great for the server. Multiplexing may be most desired in environments with many short-lived connections and weak client-side pooling - such as a PHP web application.


PHP mysqlnd connection multiplexing plugin . More about PHP mysqlnd

How mysqlnd plugins work in general

The mysqlnd library is part of PHP as of 5.3. Since PHP 5.4 it is the default C client library for all three PHP MySQL APIs (mysqli, PDO_MySQL, mysql).

Wordpress, Drupal, Symfony, Zend Framework, Oxid, a | mysqli PDO_MySQL mysql mysqlnd PECL/mysqlnd_mux | MySQL

As a backend C library for the existing APIs, mysqlnd and its plugins can be transparent from a user perspective. They operate inside PHP at a layer beneath the users applications.Thus, the mysqlnd multiplexing plugin can be used with all existing PHP MySQL applications. However, there is a glory detail. The plugin needs the latest version of mysqlnd contained in PHP 5.5.

How the multiplexing is implemented

Whenever a user attempts to open a MySQL connection using any of the PHP MySQL extensions (mysql, mysqli, PDO_MySQL), the corresponding functions of the mysqlnd library are called inside PHP. The plugin hooks those calls. Whenever the user opens a connection, the plugin checks for a cached connection to the requested MySQL server. If none is found, a new connection is opened, cached and returned to the caller.

$handle_1 = mysqli_connect("host", ...) PECL/mysqlnd_mux Have cached connection to host?

  1. No
    1. Connect to host
    2. Cache conn_1
    3. Return conn_1

When doing another connect to the same MySQL server as before, no matter what API used, the plugin checks its cache and links the new user handle to the already opened connection. No second connection needs to be established.

$handle_2 = new PDO("mysql:host=host;...", ...) PECL/mysqlnd_mux Have cached connection to host?

  1. Yes
    1. Return conn_1

Compared to a traditional connect there is now only one connection opened to MySQL. Two user connection handles share the same underlying connection. Less work for the server.

conn_1 | A | $handle_1 A $handle_2

An optimization for some

Multiplexing is a performance optimization

Truncated by Planet PHP, read more at the original (another 2794 bytes)