Background & Why You Need It
During peak hours, an e-commerce website handling several thousand concurrent users (CCU) can easily drive MySQL CPU utilization to 100%. Storage disks hit continuous I/O bottlenecks under the strain of redundant product queries, sending response times spiking from 120ms all the way to 3–5 seconds.
The most straightforward and effective solution is placing an in-memory caching layer between PHP and the database. Memcached handles key-value storage directly in RAM, slashing data retrieval latency down to microseconds instead of tens of milliseconds when reading from SSDs.
While CentOS Stream 9 features a newer kernel and updated libraries, Memcached’s daemon retains its signature strengths: lightweight performance and rock-solid stability. Being multi-threaded, it scales exceptionally well across multi-core CPUs, making it ideal for caching PHP sessions, HTML fragments, and API responses.
If you don’t require complex data structures or disk persistence like Redis offers, Memcached is a far simpler, lower-overhead choice.
Installation
The Memcached package is available in the default AppStream repository of CentOS Stream 9. However, the PHP extension requires enabling the EPEL and Remi repositories.
Step 1: Install Memcached and Management Tools
Run the following command to install Memcached alongside CLI utilities for debugging:
sudo dnf update -y
sudo dnf install -y memcached libmemcached
The libmemcached package provides useful CLI utilities such as memcstat and memccat, allowing you to inspect cache health directly without writing custom test scripts.
Step 2: Enable and Start the Service
Start the daemon and configure it to launch automatically on server reboot:
sudo systemctl enable --now memcached
sudo systemctl status memcached
Step 3: Install the PHP Memcached Extension
To connect WordPress, Laravel, or vanilla PHP applications to Memcached, install the PHP extension:
sudo dnf install -y epel-release
sudo dnf install -y https://rpms.remirepo.net/enterprise/remi-release-9.rpm
sudo dnf install -y php-pecl-memcached
Restart the PHP-FPM service to load the new module:
sudo systemctl restart php-fpm
php -m | grep memcached
If the terminal prints memcached, the extension has been successfully integrated.
Detailed Configuration
All Memcached settings on RHEL and CentOS Stream 9 reside in /etc/sysconfig/memcached. Here, you can configure allocated RAM, listening ports, and allowed bind addresses.
Step 1: Adjust Resource Parameters
Open the configuration file:
sudo nano /etc/sysconfig/memcached
Default contents:
PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="64"
OPTIONS="-l 127.0.0.1,::1"
Here are the parameters to tune based on your infrastructure scale:
- CACHESIZE="512": Amount of RAM allocated for cache (in MB). The default 64MB fills up very quickly. For instance, on a 4GB RAM VPS hosting Nginx and MySQL alongside it, you can allocate 512MB to 1024MB for Memcached.
- MAXCONN="2048": Maximum concurrent connections. This value should be greater than the sum of
pm.max_childrenacross all PHP-FPM pools combined to prevent dropped requests. - OPTIONS="-l 127.0.0.1,::1 -U 0": Eliminates exposure risks. The
-l 127.0.0.1flag restricts the service to localhost. The-U 0flag disables UDP entirely to neutralize UDP reflection DDoS attacks.
Restart the service to apply the changes:
sudo systemctl restart memcached
Step 2: Verify the Connection from PHP
Create a quick test script at /var/www/html/test_memcached.php:
<?php
$m = new Memcached();
$m->addServer('127.0.0.1', 11211);
$key = 'product_detail_102';
$data = $m->get($key);
if ($data) {
echo "[CACHE HIT] Retrieved data from RAM: " . htmlspecialchars($data) . PHP_EOL;
} else {
echo "[CACHE MISS] Querying DB... Loading value into RAM" . PHP_EOL;
$dbData = "iPhone 15 Pro - Price: 25,000,000 VND (Cached at " . date('H:i:s') . ")";
// Cache for 60 seconds
$m->set($key, $dbData, 60);
echo "[STORED] Data saved to Memcached." . PHP_EOL;
}
?>
Run the test directly from your terminal:
php /var/www/html/test_memcached.php
On the first execution, you will see [CACHE MISS]. Running it again immediately will yield [CACHE HIT] with near-instantaneous response times.
Testing & Monitoring
In production environments, you must closely monitor the cache hit ratio and memory eviction rates.
1. Inspect Slab Allocator Metrics with memcached-tool
Use the built-in system script to inspect memory allocation structure:
memcached-tool 127.0.0.1:11211 display
memcached-tool 127.0.0.1:11211 stats
This command provides a detailed breakdown of each Slab Class, chunk sizes, and the number of items stored in RAM.
2. Retrieve Runtime Stats via Socket
Send text commands directly to the daemon port using nc (netcat):
echo "stats" | nc 127.0.0.1 11211
Focus on analyzing four critical performance metrics:
- cmd_get: Total read requests issued by applications.
- get_hits: Number of times requested data was found in RAM. The formula
get_hits / cmd_getyields the hit ratio, which ideally sits between 85% and 95%. - get_misses: Number of cache misses where requests had to fall back to the database.
- evictions: Number of items evicted from RAM before expiration (TTL) due to memory exhaustion. If this count increases continuously by hundreds per minute, increase
CACHESIZEimmediately.
3. Audit Network Ports
Verify that the process is not exposed to public IP ranges:
sudo ss -tulpn | grep 11211
A secure configuration shows only 127.0.0.1:11211 under the TCP protocol. Ensure there are no entries bound to 0.0.0.0:11211 or any open UDP ports.
