Question

On my website, when an user opens his profile or any other page, (almost all pages use data from mysql), my website makes around 50 connections to mysql in loading the page. This is the case on my development server, running elementary OS.

When I came to know about persistent connections in mysql, I was puzzled. If I am to run this website on a VPS (with low RAM in starting), and considering the overhead produced by a large number of mysql connections, will using persistent connections improve my website's performance?

Currently, I start and end a connection in every function. Is there a better way to connect to mysql?

And, taking into account that if 100 users are using my website simultaneously, what will be the performance if each page makes around 50-60 connections?

Was it helpful?

Solution

You asked so I will answer. You are doing this incorrectly. You should start the processing on each page request (each externally-accessible .php file) by using a common function to establish a single database connection, then you should reuse that connection.

You are getting away with this because you're probably using an automatic connection pool built in to your php database-access library, and because you have not yet scaled up your application.

You won't be able to scale this up very far using this multiconnection strategy because it will perform very badly indeed when you add users.

There are lots of examples of working open-source php-based web app systems you can look at. WordPress is an example. You'll find that most of them start by opening a database connection and storing its handle in a global variable.

You asked:

According to CBroe's comment, I changed my strategy. Actually, I am using multiple database connections, but the functions are same (don't ask why lol). So if I open connections on start, and then pass the handler to the function, will that be an improvement?

Yes, that will be fine. You need to avoid churning connections to get best performance.

If you need connections to more than one different database, you can open them all. But it sounds like you need to hit just one database.

PHP doesn't have significant overhead when passing a handler to a function, so don't worry about that.

OTHER TIPS

As explained wonderfully by Ollie Jones, I opened the connection on start, and my connections dropped from 50-60 per page to 1 per page. Although I don't see any change in performance on my local development server, this will surely we a great improvement when its on a live server. There is no need for me to use persistent connections yet.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top