Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I avoid reconnecting to the database with every REST-request send by a client-application?

Tags:

rest

database

php

I am currently writing a simple RESTful web-application (with PHP), but I am not sure how to efficiently handle database access. The problem is that creating a connection to my MySQL database is quite time consuming.

My first idea was to create a Singleton as a Database Management object, which only connects to the database when the connection hasn't been setup already.
However, my connection object is always null because I guess with every request made by the client, the php script files are reloaded on the server. Hence, with every request that needs to access the database, the connection has to be initialised.

Is there a design pattern or technique that I could use to avoid this problem?

like image 903
user2035039 Avatar asked Jan 20 '26 07:01

user2035039


1 Answers

From Persistent Database Connections:

Persistent connections are good if the overhead to create a link to your SQL server is high. Whether or not this overhead is really high depends on many factors. Like, what kind of database it is, whether or not it sits on the same computer on which your web server sits, how loaded the machine the SQL server sits on is and so forth. The bottom line is that if that connection overhead is high, persistent connections help you considerably. They cause the child process to simply connect only once for its entire lifespan, instead of every time it processes a page that requires connecting to the SQL server. This means that for every child that opened a persistent connection will have its own open persistent connection to the server. For example, if you had 20 different child processes that ran a script that made a persistent connection to your SQL server, you'd have 20 different connections to the SQL server, one from each child.

Here's the mysql_pconnect documentation page.

like image 74
Alex Filipovici Avatar answered Jan 23 '26 07:01

Alex Filipovici