One reason for high server load on a server running a PHP application is the repeated execution of the same database queries. For example, if the contents of an online store’s catalog are updated several times an hour, there’s little point in retrieving them from MySQL all over again with every visitor request. It is much more efficient to temporarily store the query result in RAM and use it when processing subsequent requests.
Memcached - a distributed caching server that stores data in RAM as “key-value” pairs - is designed to solve such problems. A PHP application can store arrays, strings, calculation results, objects, and other data in it - data that would otherwise require additional resources to retrieve.
In this article, we’ll walk through how to install Memcached on a Linux server, connect it to PHP, set up data caching, and verify that the entire system is working properly. For this example, we’ll use Debian 13 and Ubuntu 24.04 LTS with standard packages from the distribution repositories.
What’s the Difference Between Memcached, Memcache, and OPcache?
In the context of PHP, two nearly identical names are often encountered: memcache and memcached. These are different PHP extensions designed to interact with the same caching server.
The memcache extension provides the Memcache class, whereas memcached uses the libmemcached library and provides the Memcached class. Their APIs differ, so unfortunately, you cannot simply replace one extension with the other in an existing application.
For the examples that follow, we’ll use the memcached extension.
OPcache deserves a separate mention; it also stores data in RAM but serves a completely different purpose. It caches the compiled bytecode of PHP scripts, eliminating the need for the interpreter to recompile the source code. Memcached, in turn, works with the application’s data itself. It is possible - and often makes sense - to use these technologies simultaneously.
Installing Memcached on Linux
To connect PHP to Memcached, you need to install two components: the caching server itself, which will run in the background, and the PHP extension that allows the application to access it.
First, as usual, let’s update the package index and install both components:
sudo apt update sudo apt install memcached php-memcached
If the server uses multiple versions of PHP, the extension should be installed for a specific version of the interpreter. For example, for PHP 8.3 on Ubuntu 24.04, the installation command will look like this:
sudo apt install php8.3-memcached
In Debian 13, the default version of PHP is PHP 8.4, so the corresponding package is called php8.4-memcached.
After installation, enable the Memcached service and check its status:
sudo systemctl enable --now memcached sudo systemctl status memcached
If the service has started successfully, its status will be listed as active (running). However, before connecting an application to it, it is advisable to check the caching server’s configuration.
Configuring Memcached and Restricting Network Access
In Debian and Ubuntu, Memcached’s startup parameters are specified in the file /etc/memcached.conf. Before editing this file, let’s save a backup copy:
sudo cp -a /etc/memcached.conf /etc/memcached.conf.bak sudo nano /etc/memcached.conf
If PHP and Memcached are running on the same server, the following settings are sufficient:
-m 128 -p 11211 -l 127.0.0.1 -U 0
Here, the -m parameter specifies the amount of memory in megabytes allocated for storing cached objects, -p specifies the TCP port, -l limits listening to specific network interfaces, and -U 0 disables UDP.
Note that 128 MB in this case does not represent the total RAM usage limit for the Memcached process. Some additional memory will be required to handle connections and internal data structures.
You should only modify the existing directives, leaving the rest of the configuration file’s parameters unchanged.
It is worth noting that port 11211 should not be opened for internet access. With the default configuration, Memcached does not require client authentication; therefore, an unauthorized user who gains access to the service could potentially read, modify, and delete cached data.
If the PHP application is hosted on a separate VPS, it is best to use an isolated private network or a VPN to interact with Memcached, further restricting access via a firewall.
Apply the settings:
sudo systemctl restart memcached
When the service is restarted, the contents of the regular Memcached cache will be lost. If the server is already serving a live application, you should expect a possible temporary increase in database load.
You can check the network sockets with the following command:
sudo ss -lntup | grep ':11211'
With the configuration shown above, Memcached should accept TCP connections only at the address 127.0.0.1:11211, and there should be no UDP socket.
Connecting the Memcached Extension to PHP
After installing the package, check whether the extension is loaded by the interpreter:
php --ri memcached
The command should display information about the extension, its version, and configuration parameters.
However, there is one caveat. The command-line version of PHP (CLI) and PHP-FPM use separate configuration files, so successfully loading the extension in the console does not guarantee that it will be available to the web application.
If the site runs via PHP-FPM, restart the corresponding service. For example, on Ubuntu 24.04:
sudo systemctl restart php8.3-fpm
For Debian 13 with the default PHP:
sudo systemctl restart php8.4-fpm
If you’re using Apache with the mod_php module, you’ll need to restart Apache. Nginx itself does not need to be restarted, since the extension is loaded by the PHP interpreter.
On a live server, it’s best to restart PHP-FPM or Apache during periods of low traffic.
Checking the PHP Connection to Memcached
To verify that PHP can actually write to and retrieve data, let’s create a small test script test-memcached.php:
<?php
$cache = new Memcached();
$cache->addServer('127.0.0.1', 11211);
$key = 'test:' . bin2hex(random_bytes(8));
if (!$cache->set($key, 'Memcached works!', 60)) {
exit($cache->getResultMessage() . PHP_EOL);
}
$value = $cache->get($key);
if ($cache->getResultCode() !== Memcached::RES_SUCCESS) {
exit($cache->getResultMessage() . PHP_EOL);
}
echo $value . PHP_EOL;
$cache->delete($key);
Let’s run it from the console:
php test-memcached.php
If the script runs successfully, it will output the string Memcached works!.
The addServer() method registers the server address with the Memcached client, but a connection is not established immediately. That is why, for a thorough test, it is not enough to simply create an instance of the Memcached class: you must perform at least one write or read operation.
To test via PHP-FPM, you can temporarily run this same script through the web server, restricting access to it, and then delete the file once the diagnostics are complete.
Caching SQL Query Results
Simply connecting Memcached to PHP does not speed up the website’s performance. The application must determine on its own which data to cache, when to update it, and what to do if the required key is missing.
One common caching approach is called Cache-Aside. The application first searches for data in the cache and only if it is not found does it query the original source, after which it stores the result in Memcached.
Suppose the website needs to regularly display a list of active product categories. In this case, the corresponding function might look like this:
function getCategories(PDO $pdo, Memcached $cache): array
{
$key = 'shop:categories:active:v1';
$categories = $cache->get($key);
$code = $cache->getResultCode();
if ($code === Memcached::RES_SUCCESS) {
return $categories;
}
if ($code !== Memcached::RES_NOTFOUND) {
error_log($cache->getResultMessage());
}
$stmt = $pdo->query(
'SELECT id, name FROM categories WHERE active = 1'
);
$categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (!$cache->set($key, $categories, 300)) {
error_log($cache->getResultMessage());
}
return $categories;
}
This function takes an existing database connection established via PDO and a configured instance of the Memcached class. On the first call, the data will be retrieved from the database and stored in the cache for 300 seconds. Subsequent calls to the function will not need to execute an SQL query as long as the corresponding record remains available in Memcached.
Why does this example use getResultCode() instead of the usual check on the return value? The reason is that PHP allows you to store the boolean value false in Memcached. Consequently, checking the result of the get() method for equality to false does not always allow you to determine whether the record is missing from the cache or whether that specific value was stored there previously.
Furthermore, the function shown will continue to work with the database even if the caching server is unavailable.
Cache Lifetime and Refresh
The entry’s lifetime, or TTL (Time to Live), is passed as the third argument to the set()method:
$cache->set('example:key', $data, 600);
In this case, the data will be available for no more than ten minutes. If you pass the value 0, the entry will have no set expiration time, although Memcached will still be able to evict it if memory is low.
However, Memcached has one peculiarity to keep in mind when setting a long TTL: values up to and including 30 days are interpreted as the number of seconds, while values above this threshold are interpreted as absolute time in Unix Timestamp format.
However, it is not always advisable to wait for an entry to expire naturally. For example, after changing a category name in the database, it is advisable to immediately delete the corresponding cache entry:
$cache->delete('shop:categories:active:v1');
On the next request, the application will retrieve the latest data from the database and rebuild the cache. This operation is called cache invalidation.
Also, if multiple applications share a single Memcached instance, it makes sense to add unique prefixes to the keys. This will help avoid accidental name collisions among entries. However, it’s important to remember that such prefixes do not provide application isolation from a security standpoint.
Storing PHP Sessions in Memcached
In addition to caching application data, Memcached can be used to store user sessions. This is particularly convenient when a PHP application runs simultaneously on multiple web servers that require a shared session storage.
To do this, specify the following in the PHP configuration serving the application:
session.save_handler = memcached session.save_path = "127.0.0.1:11211"
For example, when using PHP 8.3 and PHP-FPM, the corresponding directives can be set in the /etc/php/8.3/fpm/php.inifile.
After making these changes, you’ll need to restart PHP-FPM. If the application uses its own session handler, the configuration should be performed using the application or framework itself.
Before switching to Memcached, keep in mind that existing file-based sessions will not be automatically migrated, and users may need to re-authenticate.
Additionally, since Memcached stores data in RAM, restarting the service or evicting entries due to insufficient memory may result in the loss of user sessions. For this reason, it is advisable to allocate a separate Memcached instance for storing sessions so that the regular application cache does not compete with sessions for available memory.
If session loss is unacceptable due to application requirements, you should consider a different storage solution.
How to Evaluate Memcached Performance
To determine how effectively caching is being used and whether the server has enough allocated memory, you can use the getStats() method:
<?php
$cache = new Memcached();
$cache->addServer('127.0.0.1', 11211);
print_r($cache->getStats());
Among the returned statistics, the following are of particular interest:
get_hits- the number of successful cache hits;get_misses -the number of requests where the desired key was missing;evictions -the number of entries evicted before their expiration time;bytes -the current amount of memory occupied by stored entries;limit_maxbytes -the set memory limit for storing objects;curr_items -the current number of entries.
The ratio of successful cache hits to the total number of read operations is called the Cache Hit Ratio; the higher this metric, the more often the application retrieves the required data from the cache.
If, however, the number of evictions is constantly increasing, the cause may be insufficient allocated memory or an ineffective caching strategy. It is best to evaluate these metrics over time, since statistics accumulated since the service was launched do not always reflect the current load.
However, increasing the Memcached memory size alone does not guarantee that the website will run faster. Caching efficiency depends primarily on how often the application reuses cached data and how many resources would be required to retrieve that data without the cache.