How to reduce server load and improve WordPress speed with Memcached

In my last article about Varnish in a Docker container, I’ve explained how to easily activate server-side caching and what advantages you can get with this mechanism. Today, I will show you how you can reduce server load and drastically improve your WordPress website speed with Memcached.

Memcached – a distributed memory caching system

Memcached caches data and objects directly into the memory (RAM) and reduces the amount of times an external source has to be read (e.g. the database or API-calls). This especially helps dynamic systems like WordPress or Joomla! by noticeably improving the processing time!

Before we start, keep in mind that Memcached does not have built-in security measures for shared hosting environments! This tutorial should only be used on a dedicated server.

Installing Memcached

On my server, I run Plesk Onyx with CentOS 7.x. This tutorial also applies to other systems, just remember to use the system-specific commands (e.g. apt-get instead of yum). To install Memcached, first access your server via SSH and use the command line:

yum install memcached

After the installation process, we start it with:

service memcached start

Next we have to install PECL Memcached for the corresponding PHP version. WordPress is fully compatible with PHP 7, so let’s activate Memcached for the latest PHP 7.1 version. Start by installing all the necessary packages to add our custom PHP module in Plesk.

yum install make plesk-php71-devel gcc glibc-devel libmemcached-devel zlib-devel

Build the module with these instructions. You don’t have to specify the libmemcached directory manually, simply hit Enter if prompted.

/opt/plesk/php/7.1/bin/pecl install memcached

In the next step, we have to add a line to the corresponding configuration file to register the module in PHP. You can use the command line without having to open the ini file with an editor.

echo "extension=memcached.so" > /opt/plesk/php/7.1/etc/php.d/memcached.ini

And finally, re-read the PHP handlers so that you see the module in the PHP overview in the Plesk GUI.

plesk bin php_handler --reread

You can check the phpinfo()-page now to find out if the memcached module was loaded properly.

Memcached php configuration
Memcached – phpinfo() output

Or directly via the command line:

/opt/plesk/php/7.1/bin/php -i | grep "memcached support"
Memcached php command line check
Memcached – PHP command line check

Secure and monitor your Memcached integration

Memcached is using port 11211 per default. For security reasons, we can bind port 11211 only to localhost.

Add the following line to the end of file /etc/sysconfig/memcached and restart Memcached service.

OPTIONS="-l 127.0.0.1"

To monitor and get some stats from Memcached, you can use the following commands:

echo "stats settings" | nc localhost 11211
/usr/bin/memcached-tool localhost:11211

Activate Memcached in WordPress

Once Memcached is installed on the server, it is easy to activate it in WordPress. First, we need to activate the Memcached backend with a special script that auto-detects whether to use Memcached as the caching mechanism.

Download the script from https://github.com/bonny/memcachy and move all files to the /wp-content/  folder.

If you didn’t change the default port (11211) of Memcached, then you are ready to use it directly. If you’ve changed it, then you will have to add the following code to the wp-config.php (placed in the root of your WordPress instance).

$memcached_servers = array( array( '127.0.0.1', 11211 ) );

Okay, once the backend is activated, we will install a cache plugin to store and serve rendered pages via Memcached. Install the plugin Batcache (https://wordpress.org/plugins/batcache/) using the installation instruction.

  1. Download and unzip the package
  2. Upload the files advanced-cache.php to the /wp-content/ folder
  3. Open wp-config.php and add the following line
    1. define(‘WP_CACHE’, true);
    2. Important: Be sure that Memcached is enabled properly for the selected PHP version before adding this line else an error will be thrown!
  4. Upload the file batcache.php to the /wp-content/plugins/ folder

That’s pretty much it! You can open the advanced-cache.php file and adjust the settings for your needs. The file batcache.php is a small plugin that regenerates the cache on posts and pages. Don’t forget to activate the plugin in the backend on the plugin page!

Verify that Memcached works properly in WordPress

Now, let’s verify that you did everything correctly. The easiest way to see whether the rendered page was sent from cache is to add an additional header field to the response.

To achieve it, you have to modify the advanced-cache.php file. Open the file and search for

var $headers = array();

Change this line to

var $headers = array('memcached' => 'activated');

Open the Developer Tools in your browser (F12 in Chrome), select the Network tab and reload your website several times (just to be sure the page is loaded from the cache) and check the response headers. If you see the memcached header field, then everything is fine!

Memcached for WordPress - Nginx response headers
Memcached – Response Headers Check

Attention, if you are logged in into WordPress, then cache is never used and the system always sends the uncached version of the loaded page. So, what can you do to verify the functionality while being logged in? You can either log out first or open a new tab in your browser in Incognito / Private Window mode and use the Developer Tools there.

Instead of the examining the headers, you can also check the source code of the loaded page. If you can find similar lines, then the page was loaded from the cache:

<!—
    generated 207 seconds ago
    generated in 0.450 seconds
    served from batcache in 0.007 seconds
    expires in 93 seconds
-->

Let’s do some stress tests with Blitz.io!

We can test the load performance by stress testing, which will load the website with many concurrent users per second for a certain time span. Without any security and overload protection, your server should start to respond slower until the requests cannot be handled anymore. With Memcached activated, your server should be able to serve intensive requests longer without throwing errors.

Let’s run some load and performance tests with Blitz.io.

Note: For this stress test I took the same small server that I used for the tests with Varnish (only 1 CPU and 500MB Memory)!

Result WITHOUT Memcached:

Wordpress Without Memcached
Stress test – WordPress without Memcached

It is the same result like in the Varnish stress test. As you can see, I had to abort the stress test because the server couldn’t handle the requests less than 5 seconds and less than 50 concurrent users into the test. After just 15 seconds, the server collapsed completely and no requests could be managed anymore!

Result WITH Memcached:

Memcached WordPress
Stress test – WordPress with Memcached

As you can see, the Memcached cache allows us to keep the server stable even under heavy load. The small test server handled over 400 concurrent users and responded all requests over 50 seconds without any errors. After 50 seconds and almost 450 concurrent users, the server finally overloaded and stopped accepting further requests. With a more powerful server, the numbers would be much higher.

Therefore, it’s a great idea to use Memcached to keep your website reactive, even when it suffers a simple attack. For real DDoS attacks (Distributed Denial of Service attack) you’d be better off with CloudFlare ServerShield to protect your server.

Summary: Memcached for WordPress works perfectly

Memcached can greatly improve the performance of your WordPress website and reduce the CPU-load of your server. It’s easy to set up a working environment and it works out-of-the-box.

Thank you for reading my article, let me know your comments!

Have fun improving the speed of your WordPress website and stay Plesky!

17 Comments

  1. For security reasons, I would strongly recommend to add line

    OPTIONS=”-l 127.0.0.1″

    at the end of file /etc/sysconfig/memcached and restart memcached service. It will bind port 11211 only to localhost.

    Also following commands would useful for memcached monitoring and stats:

    # echo “stats settings” | nc localhost 11211
    # /usr/bin/memcached-tool localhost:11211

  2. What about WP toolkit it is better to use it to install plugins.

  3. How can one configure memcache for php 5?

  4. So using memcached and batcache in conjunction with Varnish is feasable, I assume? I guess memcached takes care of caching objects and Varnish caches the .html files, so there is no interference between the two caching solutions?

    What about using Memcached/Batcache, Varnish and the plugin WP Supercache together? I assume that
    – Memcached/Batcache caches obejcts
    – WP Supercache caches the output of the PHP queries into .html files
    – and finally varnish caches these .html files

    So this would work too I guess, but is it recommended to chain so many caching solutions behind each other?

  5. Hello. Thank you for this article. Is it possible to install memcached this way for different versions of PHP ?

  6. Sorry, I meant several version of PHP on the same server 🙂

  7. it doesn’t work with Ubuntu 16 64bit

    root@my-server-name:~# apt-get install make plesk-php71-devel gcc glibc-devel libmemcached-devel zlib-devel
    Reading package lists… Done
    Building dependency tree
    Reading state information… Done
    E: Unable to locate package plesk-php71-devel
    E: Unable to locate package glibc-devel
    E: Unable to locate package libmemcached-devel
    E: Unable to locate package zlib-devel

    OS ‪Ubuntu 16.04.2 LTS‬
    Product Plesk Onyx
    Version 17.5.3 Update #12, last updated on July 4, 2017 01:32 PM
    The system is up-to-date. Checked on July 9, 2017 01:28 AM.

  8. /opt/plesk/php/7.1/bin/pecl install memcached
    pecl/memcached can optionally use PHP extension “igbinary” (version >= 2.0)
    pecl/memcached can optionally use PHP extension “msgpack” (version >= 2.0)
    downloading memcached-3.0.3.tgz …
    Starting to download memcached-3.0.3.tgz (77,310 bytes)
    ………………done: 77,310 bytes
    15 source files, building
    running: phpize
    sh: 1: phpize: not found
    ERROR: `phpize’ failed

  9. Sound good but doesn’t work. Everything as Viktor wrote but header doesn’t show any memcached usage. PHP 7.1.17, Plesk Onyx 17.5. Tried with Apache, only Nginx mit php-fpm etc. nothing works.

  10. Hello;

    Your last post you never replied to comments or solve any of the issues raised, so why should i follow this? also what about using redis?

  11. Hello, Nice article everything work fine .
    But i have a little bit question .
    How i can save the configuration file sysconfig/memcached ?
    I don’t have good knowledge with linux command im using centos 7 thanks for all .

  12. For some reason I dont see Memcached in my header with var $headers = array(‘memcached’ => ‘activated’);

    This does work /usr/bin/memcached-tool localhost:11211 so it should be working right?

  13. Not working with SSL enabled wordpress…. no Memcached in my header…

  14. Is this guide still valid today?

  15. Hi,
    thanks for very useful how-to.
    In my installation with Plesk Obsidian 18.0.36 and CentOs v7.9 the setup of memcached is ok and memcached work ok, but in WordPress not work.
    Memcached is regularly up on default port (11211).
    I try with Memcachy and Batcache but also with other plugins that use memcached, but nothing.
    Very Strange situation.
    Is there someone who can help me?
    Thanks.

Add a Comment

Your email address will not be published. Required fields are marked *

GET LATEST NEWS AND TIPS

  • Yes, please, I agree to receiving my personal Plesk Newsletter! WebPros International GmbH and other WebPros group companies may store and process the data I provide for the purpose of delivering the newsletter according to the WebPros Privacy Policy. In order to tailor its offerings to me, Plesk may further use additional information like usage and behavior data (Profiling). I can unsubscribe from the newsletter at any time by sending an email to [email protected] or use the unsubscribe link in any of the newsletters.

  • Hidden
  • Hidden
  • Hidden
  • Hidden
  • Hidden
  • Hidden

Related Posts

Knowledge Base