Redis slow with PHP? Think again!

So you have a problem and think that a NoSQL solution should work for you.

Good.

Then you realize you use PHP.

Damn.

As demonstrated in redis’ mailing list, there are tons of PHP clients ( also native extensions ) but they do really suck at performances.

I’ve tried a couple of benchmarks ( not written by me ):

that were basically saying that Redis was able to perform about 11k SET/GET per second.

The almost same thing, done with MySQL

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php

mysql_connect('127.0.0.1', 'root');
mysql_select_db('redis_benchmark');
$query = mysql_query('SELECT * FROM users WHERE id = 1');

for ($i = 0; $i < 100; $i++) {
  $start = microtime(true);
  for ($j = 0; $j < 10000; $j++) {
    $key = sprintf("key:%05d", $j);

    $persone = mysql_fetch_row($query);
  }
  $time = microtime(true)-$start;
  printf("%6d req/sec\n", $j/$time);
}

was identical: 11k GETs per second.

As Salvatore, the lead developer of Redis, stated months ago, the biggest percentage of benchmarks suck and the problem with PHP is PHP itself.

However Kijin highlighted that the main part of the benchmarks made with PHP are single threaded and not-pipelined.

What if we only use the pipeline?

Editing the second gist:

1
2
3
4
5
6
7
8
9
10
11
12
<?php

  $start = microtime(true);
  for ($j = 0; $j < 10000; $j++) {
    $key = sprintf("key:%05d", $j);
    $redis->pipeline();
    /* GET or SET */
    if (rand() % 2 == 0) {
      $redis->set($key, rand());
    } else {
      $redis->get($key);
    }

we see that the transaction rate goes up to > 40k SET/GET per second!

Adding the pipeline to the first gist ( which only does SETs ) make it reach the 90k SETs per second.

Don’t believe?

See it before

and after

So, guys, yes, Redis is fast also with PHP.


In the mood for some more reading?

...or check the archives.