How to: Tune and Speed up WordPress Site

A slow website means users will potentially leave your website before it even loads. Check your WordPress site speed through 365andup.com and take your report. Use the report to make WordPress specific optimizations that improve load times.

A good page load time is below 2 seconds. Google recommends a >200ms response time.

Studies shows that the average human attention span have reduced from 12 seconds to 7 seconds in the period 2000 to 2016. i.e you have very little time to show your content and convince the users to stay on your site. According to studies a 1 second delay in page load time can lead to 7% loss in conversions, 11% fewer page views and 16% decrease in customer satisfaction.

Also Google and other search engines have started penalizing slow websites by pushing them down in the search results which results in low traffic for the website for slower websites. So, if you want more traffic, subscribers and revenue from your website then you must make your WordPress website fast.

2 primary factors i.e your cache techniques and hosting are the 2 things that have the biggest impact on load times.

The primary causes for a slow WordPress website are;

  • Web Hosting – When your hosting server is not properly configured then it can hurt your website speed.
  • WordPress Configuration – If your WordPress site is not serving cached pages then it will overload your server thus causing your website to be slow.
  • Page Size – Mainly images that are not optimized for web.
  • Bad Plugins – If you’re using a poorly coded plugin, then it can significantly slow down your website.
  • External scripts – External scripts such as ads, font loaders, etc can also have a huge impact on your website performance.

1.Update WordPress:-

Update WordPress core, theme, plugins, and framework if you use one. WordPress is updated frequently. Each update will not only offer new features, but also fix security issues and bugs. Your WordPress theme and plugins may have regular updates, too. As a website owner, it’s your responsibility to keep your WordPress site, theme, and plugins updated to the latest versions. Not doing so may make your site slow and unreliable, and make you vulnerable to security threats.

2.Upgrade your Hosting:-

Your WordPress hosting service plays an important role in website performance. The optimization techniques available to you will depend on your hosting setup.

On a shared hosting server you share the server resources with many other customers. Another option is to use a managed WordPress hosting service. But, in both cases, your access level is limited, and you won’t be able to tune server side configuration.and if your neighbouring site gets a lot of traffic, then it can impact the entire server performance which in turn will slow down your website.

If you are on your own dedicated/VPS hosting, go ahead with the best ways that we found to consistently speed up your WordPress.

3.Apache Tweaks:-

Apache is a fast, reliable, and flexible server but is heavy on resources by default. If you are running a VPS, and using it just for WordPress, you can make some small tweaks to your configuration and get some significant performance gains.

Please note, by default Apache comes with lots of unnecessary installed modules. Some modules that are particularly resource eating, that you should disable if you don’t need them.So it’s recommended to disable all those modules that are not in use. You can list all the compiled modules of web server, using following command;
# grep LoadModule /etc/httpd/conf.modules.d/00-base.conf

To disable the particular module, you can insert “#” at the beginning of that line and restart the service.

Apache MPM Prefork Module

This Multi-Processing Module (MPM) implements a non-threaded, pre-forking web server. This module controls the number of processes and spare processes Apache will start and run. This is especially important if you are running a small VPS that is handling MySQL and Apache.

Prefork and worker are two type of MPM apache provides. Both have their merits and demerits.
By default mpm is prefork which is thread safe.

Prefork MPM uses multiple child processes with one thread each and each process handles one connection at a time.

Worker MPM uses multiple child processes with many threads. Each thread handles one connection at a time.

# httpd -V | grep MPM
Server MPM: prefork

Most critical hardware item to be taken into account is the amount of RAM allocated for each Account/Apache process. While you cannot control this directly, but can restrict the number of processes/values by adjusting the following values in the apache configuration file;

 # vi /etc/httpd/conf/httpd.conf

StartServers       8
MinSpareThreads          5
MaxSpareThreads          20
ServerLimit      256
MaxRequestWorkers    30
MaxConnectionsPerChild    1000

StartServers:- The StartServers directive sets the number of child server processes created on startup. As the number of processes is dynamically controlled depending on the load.
MinSpareThreads:- The MinSpareServers directive sets the desired minimum number of idle child server processes.
MaxSpareThreads:- The MaxSpareServers directive sets the desired maximum number of idle child server processes.
MaxClients:- MaxClients directive sets the limit of the number of simultaneous requests that can be supported.
MaxRequestWorkers:- The MaxRequestWorkers directive sets the limit on the number of simultaneous requests that will be served.
MaxConnectionsPerChild:- The MaxConnectionsPerChild directive sets the limit on the number of connections that an individual child server process will handle.

KeepAlive and KeepAliveTimeout

The Keep-Alive extension and the persistent connection provide long-lived HTTP sessions which allow multiple requests to be sent over the same TCP connection. When a client uses a Keep-Alive connection, it will be counted as a single “request” for the MaxConnectionsPerChild directive, regardless of how many requests are sent using the connection.

# vi /etc/httpd/conf/httpd.conf
KeepAlive On

Keep Alive Timeout is the number of seconds Apache httpd will wait for a subsequent request before closing the connection.Setting KeepAliveTimeout to a high value may cause performance problems in heavily loaded servers. The higher the timeout, the more server processes will be kept occupied waiting on connections with idle clients.

# vi /etc/httpd/conf/httpd.conf
KeepAliveTimeout 5

Adjust Timeout

This directive tells Apache how many seconds to wait while receiving an incoming request, processing it, and sending back a response. Default value is 300 secs, but it is best to keep this value as low as possible to prevent resource wastage.

Timeout 40

4.Mysql Innodb Tweaks:-

Databases are the “brains” of your website: They store the valuable data that you show on your pages. The content management systems have to rely on databases (SQL, NoSQL, XML, JSON and such) to store your data. WordPress has no difference, it uses MySQL to store the static and dynamic content along with your website information, WordPress settings, user details and so on.

Please note that Databases have a powerful standard to keep, serve and alter your data, but if you use them wrong and forget to maintain, they will get fat and bloated, which lead to slowness of the websites.

Ensure that an upgraded Mysql version with InnoDB storage is using in your server. MariaDB/MySQL 5.5.4 introduces new configuration settings for the InnoDB storage engine. This can greatly improve MySQL’s InnoDB performance, both in read and write operations. One of those settings is innodb_buffer_pool_instances. The innodb_buffer_pool_instances divides the InnoDB buffer pool into separate instances. To enable multiple buffer pool instances, set the innodb_buffer_pool_instances configuration option to a value greater than 1 up to 64 (the max).

vi /etc/my.cnf

innodb_buffer_pool_size = 128M
innodb_buffer_pool_instances = 2

Please avoid setting innodb_buffer_pool to a value that is higher than the amount of RAM on the server, otherwise it could start to swap out pages and performance will drop quickly.

MySQL Max Connections

The maximum number of simultaneous client connections permitted is controlled by the max_connections system variable. The default value is 151 to improve performance when MySQL is used with the Apache Web server. mysqld actually permits max_connections+1 clients to connect. The extra connection is reserved for use by accounts that have the SUPER privilege. Please keep in mind that, too many connections can cause high RAM usage and lock up your MySQL server.

You could update Max Connections without restarting the service by;

# mysql -u root -p
mysql> set global max_connections := 150;

MySQL thread_cache_size

The thread_cache_size directive sets the amount of threads that your server should cache. The default value is 0 (no caching), which causes a thread to be set up for each new connection and disposed of when the connection terminates. Set thread_cache_size to N to enable N inactive connection threads to be cached. thread_cache_size can be set at server startup or changed while the server runs. A connection thread becomes inactive when the client connection with which it was associated terminates.

You could calculate the thread cache hit rate percentage from the following formula;

100 - ((Threads_created / Connections) * 100)

MySQL query_cache_size

The query cache stores the text of a SELECT statement together with the corresponding result that was sent to the client. When it is enabled, if an identical statement is received later, the server retrieves the results from the query cache rather than parsing and executing the statement again. So the query cache can be useful in an environment where you have tables that do not change very often and for which the server receives many identical queries.

To set the size of the query cache, set the query_cache_size system variable. Setting it to 0 disables the query cache, as does setting query_cache_type=0. By default, the query cache is disabled.

When you set query_cache_size to a nonzero value, keep in mind that the query cache needs a minimum size of about 40KB to allocate its structures.

The query_cache_size value is aligned to the nearest 1024 byte block. The value reported may therefore be different from the value that you assign.

Please find the below query cache config for a normal wordpress installation;

query_cache_type = 1
query_cache_limit = 256K
query_cache_min_res_unit = 2k
query_cache_size = 80M

MySQL max_allowed_packet

MySQL always splits data into packets. The max_allowed_packet directive defines the maximum size of packet or any generated/intermediate string, or any parameter that can be sent. The largest possible packet that can be transmitted to or from a MySQL 5.6 server or client is 1GB.

max_allowed_packet=16M

5.Use a Content Delivery Network (CDN):-

Users from different geographical locations may experience different loading times for the site. Location of your web hosting servers can have an impact on site speed. Using a CDN (Content Delivery Network) can help to speed up loading times for the users. A CDN is a network made up of servers all around the world. Each server will store “static” files used to make up your website. Static files are unchanging files such as images, CSS, and JavaScript, unlike the WordPress pages which are “dynamic”.

When using a CDN, every time a user visits your website they are served with the static files from whichever server is closest to them. Your own web hosting server will also be faster since the CDN is doing a lot of the work.

Working of CDN:

Upon setup CDN uses technologies like anycast, ligttpd and BGP to transmit the static content files from web host’s server to a network of servers that are dispersed at different geographic locations around the world, caching the contents of the file.

When the user’s browser requests a static file that is linked to a CDN, the CDN redirects the request from originating site’s server to a point of presence that is closest to the user. User’s proximity to web servers impact on load time. The closer the CDN server is to user is, the faster the site loads for them.

Advantages of CDN:
  • Speed – Having a CDN clearly improves site load time.
  • Crash Resistance – CDN allows you to distribute the load to multiple servers instead of 100% load from the main server thus making it less likely to crash.
  • Improved user experience – Upon using CDN, there is decline in bounce rate, increase in pageviews and number of pages viewed per user. i.e fast site means improved user experience.
  • Improvement in SEO – Faster sites have higher rank in search engines like Google. CDN makes your site faster, so you need it for your site to be ranked higher in search engines.

6.Installing/Using Memcached:-

Memcached is a general-purpose distributed memory caching system. It is often used to speed up dynamic database-driven websites by caching data and objects in RAM to reduce the number of times an external data source (such as a database or API) must be read.

Installing Memcached and related packages can be done by running just one command;

yum -y install memcached

You could update the configuration changes on “/etc/sysconfig/memcached” . We suggest stick on with 64MB cache size, and gradually raise as needed.

Then restart and enable Memcached at boot;

# systemctl restart memcached
# systemctl enable memcached
# systemctl status memcached

Now you will need to install memcache PHP plugin

# yum install php-pecl-memcache

Then restart apache and memcached service to reflect the changes.

# systemctl restart memcached
# systemctl restart httpd

Please run the following command to verify Memcache PHP module is loaded;

# php -m | grep mem
memcache

7.Installing/Using Varnish:-

Varnish is a web application accelerator, also known as a caching HTTP reverse proxy, which is designed for content-heavy dynamic web sites as well as heavily consumed APIs. As we all knew nobody like to wait ages for a page to load. Varnish can increase the performance of your website and prevent the web server from overloading in case of high server traffic. Varnish receives requests from clients and tries to answer them from the cache. If it cannot answer from the cache it will forward request to the origin server and fetch the response, then store it in cache and same time deliver it to the client. When Varnish has a cached response ready, it is typically delivered in a matter of microseconds.

Before installing Varnish, you will have to install the EPEL repository. You can do this by running the following command;

# yum install -y epel-release

Once it is completed you will be able to install varnish from the following command;

# yum -y install varnish

To configure varnish to start at boot, run the following command;

# systemctl enable varnish

To start varnish, run the following command;

#systemctl start varnish

By default Varnish listens on port 6081. You will need to change port 6081 to 80 so that website requests access the Varnish cache first. You can do this by editing the varnish.params configuration file (/etc/varnish/varnish.params).

VARNISH_LISTEN_PORT=80
VARNISH_STORAGE_SIZE=128M

Now need to make changes in /etc/varnish/default.vcl file. This file contains configuration that points to the content. By default it is set to serve at 8080 and points to host as localhost. The value of .host is localhost by default. It should be replaced with the fully qualified hostname or IP address and .port should be replaced with the web server’s listening port.

# vi /etc/varnish/default.vcl

backend default {
    .host = “your_webserver/IP address”;
    .port = “8080”;
}
backend default {
    .host = “your_webserver/IP address”;
    .port = “8080”;
}
Configure Apache to work with Varnish

By default Apache listens on port 80. Now, you need to make Apache to run behind Varnish caching by changing the default Apache port to 8080 (Which is updated on /etc/varnish/default.vcl).

# /etc/httpd/conf/httpd.conf
Listen 8080

It is always required that you restart all services once changes are made in configuration files.

# systemctl restart httpd
#systemctl restart varnish

We suggest you to wait some days and view varnishstat to get an idea of what your “warm” cache looks like. If you are seeing a lot of misses or that Varnish is utilizing all 128Mb, you can then consider raising the storage value as desired.

8.Enable PHP opcode cache:-

OpCode Caches are performance enhancing extension for PHP and it improves PHP performance by storing precompiled script bytecode in shared memory, thereby removing the need for PHP to load and parse scripts on each request.

Please note, Opcode caching programs, such as XCache, eAccelerator, and OPCache, are not compatible with the suPHP PHP handler. The caching program will either not function, or will function incorrectly.So we strongly recommend the DSO or fcgi PHP handlers for the OPCache opcode cacher. Also avoid installing multiple PHP caching programs on the same system. Multiple opcode caching programs consume excessive memory and degrade system performance.

For PHP 5.5 and above, Zend OpCache is compiled as a shared extension by default unless you specify --disable-all when configuring Or at the time of easyapache.

Now we need to configure the same by uncommenting /adding the following lines to the php.ini file. Also make sure that opcache.so is located in your extensions directory that is specified in the php.ini file. Once it is completed, restart the service to update the changes.

zend_extension=opcache.so
opcache.enable=1
opcache.enable_cli=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
opcache.fast_shutdown=1

9.Configure Cache Techniques:-

Your cache plugin and hosting are the two most important things that improve load times. WordPress pages are dynamic i.e they are built on the fly every time someone visits a post or page on your website. To build your pages WordPress has to run a process to find the required information, put it all together and then display it to the user. This involves a lot of process and this could really slow down your website when you have high traffic. In order to reduce this process every WordPress site need to use a caching plugin. Caching can make your WordPress site anywhere from 2x to 5x faster.

A cache plugin makes a copy of the page after the first load and then serves that cached version to every subsequent user instead of going through the whole page generation process every time. When a user visits your WordPress site which is built using PHP, your server retrieves information from a MySQL database and your PHP files, and then it’s all put together into a HTML content which is served to the user. It’s a long process, but you can skip a lot of it when you use caching instead.

The popular WordPress cache plugins are WP Rocket, WP Super Cache, WP Fastest Cache and W3 Total Cache.

A cache plugin should fix the following items in your report:

  • Minify (all items)
  • Gzip (all items)
  • Inline small CSS/JS
  • Reduce HTTP Requests
  • Leverage browser caching
  • Specify a cache validator
  • Enable keep-alive
  • Add expires headers
  • Reduce DNS lookups
  • Configure entity tags (ETags)
  • Prefer asynchronous resources
  • Remove query strings from static resources
  • Reduce cookie size (if using MaxCDN)
  • Use cookie-free domains (if using MaxCDN)
  • Use a content delivery network (if using MaxCDN)
Rajesh

Author Rajesh
Written on May 18th, 2017