Viewing WordPress View all News

WordPress Object Cache

It is not unusual for WordPress to run dozens or even hundreds (yikes!) of database queries when putting together a page. What’s worse, these queries aren’t the sort from children’s bedtime stories. They’re the dirty ones, full of temporary tables, JOINs on JOINs on JOINs, generic data types, and insufficient indexing. They’re the MySQL equivalent of The Wire.

As traffic loads increase, these computationally-heavy operations can quickly lead to a bottleneck, making your site sluggish or bringing it offline altogether.

To get a better idea of your own database use (or abuse), install a plugin like Query Monitor, which puts detailed query stats in the admin toolbar.

If you’re nearing the limit of what MySQL can handle, there are a few basic things you should consider doing:

  1. Go through your plugins and deactivate and delete anything that isn’t being used.
  2. Set reasonable post limits (10 or fewer) for archive pages.
  3. If you have a custom theme, try to minimize the number of secondary queries being run inside The Loop.

Beyond that, well, that’s the purpose of this article: Object Caching!

WordPress has the ability to cache query results (and other key/value data) in memory for later retrieval so it doesn’t have to pester MySQL on repeat requests.

This can dramatically reduce the load on MySQL, while maintaining comparable speed.

The main disadvantage of Object Cache is that objects are, well, cached. This means that changes made in the backend might not be immediately reflected on the front end.

This can be a deal breaker for applications with transactional data like e-commerce sites, unless the code contains strategic calls to wp_cache_flush(). But for content-driven sites like blogs and portfolios, it can be the perfect solution.

Object Cache also takes over handling of “transient” data, which otherwise get stored in the wp_options table. This will both speed up plugins and themes that rely on the transient API, and also reduce bloat in the database (there is no automatic garbage collection process run against wp_options, so data remains forever, and ever, and ever… (unless the same cache key is requested again)).

WordPress Object Caching is designed with extensibility in mind. All it needs is an API for key/value storage and retrieval.

There are innumerable candidates for the job, so let’s just focus on some of the most common:

XCache

XCache is my favorite PHP opcode cacher (opcode cache, incidentally, will also speed up the execution of your PHP scripts in general).

It is lightweight, scalable, and supports the latest versions of PHP.

To get started, install the XCache PHP extension (available in most Linux repositories), tweak the INI settings* (variable cache is the relevant feature here), and restart PHP.

After that, you can then enable Object Caching in WordPress by installing XCache Object Cache Backend or a more comprehensive caching solution like W3 Total Cache.

If you have multiple sites running on the same server, you need to ensure you are running version 3.0.3 or later.

The XCache extension comes bundled with admin scripts you can copy to your web root to get an idea of how cache is being utilized. You should install this after it has been running for a while to see if the memory allocations need to be raised or lowered (just make sure you restrict access, and delete it when you’re done!). Remember, the memory settings are per-process, so don’t get carried away.

APC

APC is another PHP opcode cacher, but it is no longer actively developed.

Unless you are running an older version of PHP or your hosting environment comes bundled with it, XCache is a better option.

To get started, install the APC PHP extension, tweak the INI settings, and restart PHP. You can install a standalone plugin like APC Object Cache Backend or, again, go with something like W3TC.

There remains, however, one excellent use case for APC: Facebook’s HHVM engine supports it out of the box! If you have already replaced PHP with HHVM, just install the APC Object Cache Backend plugin and you’re good to go.

Redis

Redis is a powerful key/value caching solution with support for multiple servers.

For complex web applications consisting of multiple servers, it is an ideal solution as the cache can be shared across more than one machine.

For more simple setups, it is a bit much, and noticeably slower than XCache or APC.

To get started, install the Redis server and PHP extension (if you are running HHVM instead of PHP, the “extension” is built-in). Once you have that configured, you can install the Redis Object Cache plugin.

Posted By
Josh Stoik

BBG Tips: Keep WordPress Tidy

WordPress is kind of magical. It gives site operators the power to quickly and effortlessly extend functionality, tweak design, and preview and post new content.

However, this power of immediate evolution – a key feature that has made so many insightful blogs about cats sleeping in weird places possible – can, over time, lead to clutter, increased hardware costs, and even security vulnerabilities.

Organized Desk

Keeping WordPress tidy is as important as keeping your workspace clean.

Thankfully, a little bit of spring cleaning will go a long way. (Even if you don’t get around to it until the end of summer.) There are two areas to focus on:

Disk

First and foremost, conduct a quick census of the plugins installed on your site. If you notice any that aren’t actually being used, deactivate and delete them. All plugins contribute to the overall resource demands made of your server, so at best, unused plugins are needlessly slowing things down.

More importantly, plugins also add a lot of code to your site, code which may contain bugs or security weaknesses that a hacker would love to leverage against you.

Themes are another area that can grow quite cluttered over time. Even though inactive themes won’t contribute one way or another to your site’s performance, you should still delete them from the server as they might contain exploitable security vulnerabilities.

Byte for byte, orphaned thumbnails from uploaded images comprise the most wasted disk space on the average aging blog.

Every time an image is uploaded to WordPress, anywhere from a handful to a boatload of differently-sized thumbnails are generated and saved to the server. The precise dimensions of the thumbnails vary from theme to theme, so for sites that have switched designs, this can lead to a lot of images cropped at resolutions that will never be accessed again.

The plugin Force Regenerate Thumbnails will take care of this, deleting all existing thumbnails, and regenerating only those that are actually required by the current theme. Depending on how many images you have, this can take a while, so go make a sandwich if you’re hungry.

Data

Your database, too, can easily start to look like the dark recesses of an attic, full of tangled and broken holiday decorations, old clothes, and haunted chests. The largest culprit here is usually post revisions.

WordPress maintains a history of all changes made to all posts.

This is nice because it allows you to review any changes you’ve ever made and rollback to a prior version at any time.  But this also generates a lot of bloat, particularly if you can’t decide between desert or dessert or desert or dessert.

Thankfully, this is something you can fix automatically by capping the number of revisions to some sane value. You can do this by adding the following to your wp-config.php file:

//specify the max # of revisions, 3 in this example
define('WP_POST_REVISIONS', 3);

The WP_POST_REVISIONS setting is not enforced retroactively. To remove or prune excessive revisions for existing posts, you can use a plugin like Thin Out Revisions.

The trash can also be an area of database bloat. When you delete a post, it is moved to the trash. Just like the trash on your laptop or the trash in your kitchen, items will linger forever and ever until someone bothers to empty it.

You can automate this task in WordPress, at least, by adding the following to wp-config.php:

//specify the # of days before emptying, 5 in this example
define('EMPTY_TRASH_DAYS', 5);

One last area of data bloat is one that can be really bad on some sites, and nonexistent on others: transient data.  WordPress includes an API for temporarily storing arbitrary key/value pairs for later retrieval.

Most often, transient data is used to cache results that would otherwise take a while to generate, such as a response from another server (for example, a Twitter feed) or the end result of a really convoluted query (like: find all posts published on a Wednesday about apples or oranges but not mangoes…).

By default, WordPress stores these data in the wp_options table.  Though each piece of information is given an expiration, WordPress does not do any automatic garbage collection.

Transient data is only removed if and when it is requested (after expiry).

If a given transient key is not reused, the data will outlive us all.  Fortunately, you can keep expired transient data in check with the help of the aptly named plugin Delete Expired Transients.

That’s it!  Happy cleaning!

Posted By
Josh Stoik