I am benchmarking an app I made which uses repcached (memcached with replication) for storing objects and taking some load off the db.
While benchmarking the index page I run
ab -c 400 -n 5000 http://mysite
When I use just one memcache server with
list($server, $port) = explode(':', $settings->memcached_servers[0]);
$this->link = new Memcache();
$this->link->connect($server, (int) $port);
I get 1000 reqs/sec
When I out more than one server to the pool with
$this->link = new Memcache();
foreach($settings->memcached_servers as $server){
list($server, $port) = explode(':', $server);
$this->link->addServer($server, (int) $port, 0, 10);
}
I only get 300 reqs/sec
The difference is huge
Any idea why?
I really need to have 2 server for redundancy but the performance is also crucial
It it normal to have such a huge difference?
Basically, the index page makes justs 2 calls to the db getting just one row, so the rows are cached while running the test.
But I am surprised to see memcached fall so much behind in the test.
Well it seems that the culprit was the weight parameter of the addServer
Changing it to 1 for the 1st server and 2 for the second did it and performance is now the same
Related
I'm using the code below to create and migrate tables, and while it works, it's very slow. It takes about 10 mins to complete creating about 250 tables and migrating the data. The total file size of the dump is ~1 Mb. Note that this is on localhost, and I'm afraid it'll take 5 times longer when deployed to a server with an unreliable network.
Could this code be optimized to to run within something more like 30 seconds?
function uploadSQL ( $myDbName ) {
$host = "localhost";
$uname = "username";
$pass = "password";
$database = $myDbName;
$conn = new mysqli($host, $uname, $pass, $database);
$filename = 'db.sql';
$op_data = '';
$lines = file($filename);
foreach ($lines as $line)
{
if (substr($line, 0, 2) == '--' || $line == '')
{
continue;
}
$op_data .= $line;
if (substr(trim($line), -1, 1) == ';')
{
$conn->query($op_data);
$op_data = '';
}
}
echo "Table Created Inside " . $database . " Database.......";
}
You can use cron job for automatically complete this process without waiting. Sometime this process failed for PHP execution timeout.
For increase the execution timeout in php you need to change some setting in your php.ini:
max_execution_time = 60
; also, higher if you must - sets the maximum time in seconds
The problem is - this question should not be asked with PHP, it is with the database.
During the import, indexes are rebuilt, foreign keys are checked and so on, and this is where the import actually takes a lot of time depending on your database structure.
Additionally to this, hardware might be at fault (i.e if the database is on HDD, the import will take noticeably more time than on the SSD drive).
I suggest looking into mysqltuner.pl result first, and start optimizing your database from there. Maybe post a question in SO on how to improve the database (as a separate question of course)
disabling SET FOREIGN_KEY_CHECKS=0 before the import and then enabling it with SET FOREIGN_KEY_CHECKS=1 after the import might help a bit, but it won't do all the optimizations you can do.
If all you simply want to do it SCHEDULE the task so you don't have to wait for the database import to finish, you need to implement a queue of tasks (i.e within database table) and handle thee queue via crontab, just as Muyin suggested.
If the dump comes from mysqldump, then don't use PHP at all. Simply do
mysql -h host.name -u ... -p... < dump_file.sql
I am using memcache for caching layer and i connect to it using php memcache client.
So if i need to fetch 2 keys then i can do this in following two ways:
First:
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);
$var1 = $memcache_obj->get('key_one');
$var2 = $memcache_obj->get('key_two');
Second
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);
$var = $memcache_obj->get(Array('key_one', 'key_two'));
So my question is will i get any performance benefit in the second approach or internally php memcache client still make two connection requests to memcache server?
On memcache command level we can get multiple keys in a single command but not sure php client.
I feel the speed of Memcached in my website is slower than Mysql queries. Please see the screenshot of performance of my website I got from New Relic.
I don't know how to optimize memcached in my CentOS server. Please see the configuration and performance screenshots of Memcached. I feel the number of Total Connections is high.
Please see Live Stats below
The following is how I use Memcached in my website
<?php
class dataCache {
function setMemData($key, $var, $flag = false, $expire = 36000) {
global $memcache;
if (!$memcache) {
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die("Could not connect");
}
if ($result = $memcache->set($key, $var, $flag, time() + $expire)) {
return TRUE;
} else {
return FALSE;
}
}
function getMemData($key) {
global $memcache;
if (!$memcache) {
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die("Could not connect");
}
if ($data = $memcache->get($key)) {
return $data;
} else {
return FALSE;
}
}
function delMemData($key) {
global $memcache;
if (!$memcache) {
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die("Could not connect");
}
if ($result = $memcache->delete($key)) {
return TRUE;
} else {
return FALSE;
}
}
}
And at the end of each PHP page, I use the following way to close the connection
if(isset($memcache)){
$memcache->close();
}
Do I need more memories for this server? How to reduce the number of connections? Any suggestions to improve the performance?
--------------EDIT------------------------
As the comments mentioned, the current connections are 9. The total connections are 671731. The number of connections might be not a problem.
Here are a few ways to make this go faster.
Your total connections are actually how many connections have been created to memcached.
First, use the memcached php extension NOT the memcache extension. They are entirely different and the memcache extension is pretty much deprecated to death. Memcached extension uses libmemcached which is incredibly faster and has better features (like binary protocol, better timeouts, udp)
Second, use persistent connections. For your workload these should be entirely sufficient and reduce the cost of constantly reconnecting to memcache.
Third, use multi get/set/delete/etc. If you know you will need 10 memcache keys in your request, ask for all 10 at once. This can give you a big performance increase if you are looping over memcache requests at any point.
Another caveat is that NewRelic is historically BAD at reporting time spent in memcache. It can misreport time spent in php as time spent in memcache due to how the instrument the zend engine.
As for why your memcache and mysql performance are so close, you are most likely running rather simple queries so the time spent on memcache and on mysql are comparable. Memcache is extremely fast but it is also a network hop and that is usually the largest amount of the time spent waiting for memcache. You could try running memcache locally or using APC instead of memcache if you really only have 1 server.
I'm having issue using the SDK for PHP.
If I try to estabilish a connection it takes ages...
Here some code:
$old = microtime (true);
$db = new Couchbase(...);
echo microtime (true)-$old."
";
$old = microtime (true);
$db->get(...);
echo microtime (true)-$old;
The output is this:
2.2835459709167 (couchbase establishing)
0.0011978149414062 (get command)
Why does the connection to couchbase take so long time?
The initial connection does take a while, but there is a flag for using persistent connections with the Couchbase() object. It's the last parameter. Generally, it's a good idea to set it to true.
The project is considering setting it to true by default in a future release.
Check which value you're using for the server host, if you use, for example:
$cb = new Couchbase("couchbase_hostname:8091", "user", "pass", "default" , true);
the issue may be the DNS resolution for "couchbase_hostname", try passing the host IP, you didn't paste the whole script code so I can't tell which value you're passing.
I have an issue, it has only cropped up now. I am on a shared web hosting plan that has a maximum of 10 concurrent database connections. The web app has dozens of queries, some pdo, some mysql_*.
Loading one page in particular peaks at 5-6 concurrent connections meaning it takes a minimum of 2 users loading it at the same time to spit an error on one or both of them.
I know this is inefficient, I'm sure I can cut that down quite a bit, but that's what my idea is at the moment is to move the pdo code into a function and just pass in a query string and an array of variables, then have it return an array (partly to tidy my code).
THE ACTUAL QUESTION:
How can I get this function to continue to retry until it manages to execute, and hold up the script that called it (and any script that might have called that one) until it manages to execute and return it's data? I don't want things executing out of order, I am happy with code being delayed for a second or so during peak times
Since someone will ask for code, here's what I do at the moment. I have this in a file on it's own so I have a central place to change connection parameters. the if statement is merely to remove the need to continuously change the parameters when I switch from my test server to the liver server
$dbtype = "mysql";
$server_addr = $_SERVER['SERVER_ADDR'];
if ($server_addr == '192.168.1.10') {
$dbhost = "localhost";
} else {
$dbhost = "xxxxx.xxxxx.xxxxx.co.nz";
}
$dbname = "mydatabase";
$dbuser = "user";
$dbpass = "supersecretpassword";
I 'include' that file at the top of a function
include 'db_connection_params.php';
$pdo_conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
then run commands like this all on the one connection
$sql = "select * from tbl_sub_cargo_cap where sub_model_sk = ?";
$capq = $pdo_conn->prepare($sql);
$capq->execute(array($sk_to_load));
while ($caprow = $capq->fetch(PDO::FETCH_ASSOC)) {
//stuff
}
You shouldn't need 5-6 concurrent connections for a single page, each page should only really ever use 1 connection. I'd try to re-architect whatever part of your application is causing multiple connections on a single page.
However, you should be able to catch a PDOException when the connection fails (documentation on connection management), and then retry some number of times.
A quick example,
<?php
$retries = 3;
while ($retries > 0)
{
try
{
$dbh = new PDO("mysql:host=localhost;dbname=blahblah", $user, $pass);
// Do query, etc.
$retries = 0;
}
catch (PDOException $e)
{
// Should probably check $e is a connection error, could be a query error!
echo "Something went wrong, retrying...";
$retries--;
usleep(500); // Wait 0.5s between retries.
}
}
10 concurrent connections is A LOT. It can serve 10-15 online users easily.
Heavy efforts needed to exhaust them.
So there is something wrong with your code.
There are 2 main reasons for it:
slow queries take too much time and thus serving one hit uses one mysql connection for too long.
multiple connections opened from every script.
The former one have to be investigated but for the latter one it's simple:
Do not mix myqsl_ and PDO in one script: you are opening 2 connections at a time.
When using PDO, open connection only once and then use it throughout your code.
Reducing the number of connections in one script is the only way to go.
If you have multiple instances of PDO class in your code, you will need to add that timeout handling code you want to every call. So, heavy code rewriting required anyway.
Replace these new instances with global $pdo; instead. It will take the same amount of time but it will be permanent solution, not temporary patch as you want it.
Please be sensible.
PHP automatically closes all the connections st the end of the script, you don't have to care about closing them manually.
Having only one connection throughout one script is a common practice. It is used by ALL the developers around the world. You can use it without any doubts. Just use it.
If you have transaction and want to log something in database you sometimes need 2 connections in one script