Improve PHP Application Performance With Database Connection Pooling
Stateless Design
Statelessness is a fundamental aspect of modern internet applications. The HTTP Protocol is stateless which is used by most web applications. Stateless applications don’t store state internally on the application process or application server.
The stateless approach is always more reliable because the previous requests won’t impact the next request because there don’t share anything between them. And the downside is the performance issue and duplicate operation overhead.
PHP-FPM is a stateless design. For this approach, there are overhead on launch process. Each process always have to fetch context and state to execute the request from database, cache, files on disk.
In my case, I have 700+ IoT devices which send heartbeat requests periodically to our PHP-FPM application for updating their status in database. And usually our PHP-FPM application has 300+ concurrent HTTP requests, so it establishes 300+ concurrent connections to database.
Because there are quite large costs to launch the processes and also the context switch cost on a large number of processes, the memory cost of each process, this approach is not scalable at the situation of high concurrency. As you can see at graph above, the CPU Load while handling 300+ concurrent connections.
Connection Pooling
If we can use the database connection pooling, we can create 10 connections to the database, and reuse these 10 connections by 300 concurrent HTTP requests. In this approach, it is more stable and reliable for a database.
Get Dolly Aswin Harahap’s stories in your inbox
Join Medium for free to get updates from this writer.
The concept of connection pooling has seldom been used by PHP applications because of PHP has a stateless nature. With Swoole, we can reuse the connections by managing a pool of connections in PHP.
The graph above shows MySQL Connections stats after Connection Pooling and Coroutine is implemented. It reuse same connections, so the stats becoming drop.
By reducing MySQL Connections, the CPU load and Memory usage also dropped. Because of each MySQL Connections has it’s own cost like CPU Resource and Memory Resource. So, we should not close them if we still want to use it. As you can see at graphs above, CPU Load and MySQL Memory usage dropped. And it improve the application performance!
The last, thanks to Bruce Dou for your great book! Your explanation for Swoole is very clear and not only about Swoole, you also explain Linux OS kernel knowledges, async I/O, Concurrency and Coroutine there. And it help me a lot to solve performance problem on my PHP Application!
I’m sorry I cannot share the code here due to company privacy. If you have same problem with me and curious about Swoole, Concurency and Coroutine you can drop me a message on my email at dolly.aswin(at)gmail.com








