Memcached

High-performance distributed memory caching system for reducing database load and speeding up dynamic web applications.

Overview

Memcached is a free, open-source, high-performance distributed memory object caching system. It is designed to speed up dynamic web applications by alleviating database load through 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.

Memcached server is source compiled from the official memcached.org gzipped tarball and is installed by default with Centmin Mod. See the FAQ for why source compiled vs RPM packages.

Key Benefits

  • Reduced database load — Cache frequently accessed queries and objects in memory to reduce MariaDB/MySQL queries.
  • Sub-millisecond response times — In-memory key-value store provides extremely fast data retrieval.
  • Simple key-value storage — Easy to integrate with PHP applications using memcache or memcached extensions.
  • Distributed architecture — Can scale horizontally across multiple servers for high-availability setups.

Installation

Memcached is installed by default during the initial Centmin Mod LEMP stack installation. You can also install or reinstall it through the centmin.sh menu.

Menu Option 10 — Memcached Server Re-install

Use centmin.sh menu option 10 to reinstall the Memcached server daemon. This source compiles Memcached from the official tarball.

centmin.sh

Then select option 10 from the menu to reinstall the Memcached server.

PHP Memcache/Memcached Extensions

The PHP memcache and memcached extensions are installed along with the libmemcached library as part of the PHP compilation process. These extensions allow your PHP applications to communicate with the Memcached server.

Both the memcache and memcached PHP extensions are installed during PHP compilation (Centmin Mod v1.2.3 and higher). The libmemcached C client library is also installed as a dependency.

For additional PHP extensions and addons, see the PHP-FPM Extensions and Addons pages.

Disabling Memcached

If you do not use Memcached server, you can disable it:

service memcached stop
chkconfig memcached off

To re-enable Memcached server:

service memcached start
chkconfig memcached on

Configuration

The Memcached server configuration is managed through the sysconfig file. Key settings control memory allocation, network binding, port, and connection limits.

Configuration File

/etc/sysconfig/memcached

Key Settings

Setting Default Description
PORT 11211 TCP port Memcached listens on
USER memcached User that runs the Memcached process
MAXCONN 1024 Maximum number of simultaneous connections
CACHESIZE 8 Memory allocated in megabytes (MB)
OPTIONS "" Additional command-line options

Changing Memory Allocation

To increase or decrease Memcached server's allocated memory size, edit the CACHESIZE variable in /etc/sysconfig/memcached. The value is in megabytes. For example, to allocate 256MB:

CACHESIZE="256"

After changing the configuration, restart Memcached:

service memcached restart

Or use the Centmin Mod command shortcut:

memcachedrestart

If the memcachedrestart shortcut does not work, you can re-create the command shortcuts:

echo "service memcached stop" >/usr/bin/memcachedstop ; chmod 700 /usr/bin/memcachedstop
echo "service memcached start" >/usr/bin/memcachedstart ; chmod 700 /usr/bin/memcachedstart
echo "service memcached restart" >/usr/bin/memcachedrestart ; chmod 700 /usr/bin/memcachedrestart

PHP Extensions

Centmin Mod installs both the memcache and memcached PHP extensions. While the names are similar, they are distinct extensions with different features and APIs.

Feature php-memcache php-memcached
C Library Built-in libmemcached
Binary Protocol No Yes
SASL Auth No Yes
Multi-get Yes Yes
CAS Tokens No Yes
Consistent Hashing Yes Yes

The php-memcached extension (with the "d") is generally recommended for new projects as it offers more features including binary protocol support, SASL authentication, and CAS (Check and Set) token support. See the PHP-FPM Extensions page for more details.

Usage Examples

Below are basic PHP code examples for connecting to and using Memcached in your applications.

Using php-memcached Extension

<?php
// Create a new Memcached instance
$mc = new Memcached();

// Add server (host, port)
$mc->addServer('127.0.0.1', 11211);

// Store a value (key, value, expiration in seconds)
$mc->set('my_key', 'Hello Memcached!', 3600);

// Retrieve a value
$value = $mc->get('my_key');
echo $value; // Output: Hello Memcached!

// Delete a key
$mc->delete('my_key');

// Store an array
$mc->set('user_data', [
    'name' => 'John',
    'email' => 'john@example.com'
], 3600);

// Retrieve the array
$user = $mc->get('user_data');
print_r($user);
?>

Using php-memcache Extension

<?php
// Create a new Memcache instance
$mc = new Memcache();

// Connect to server
$mc->connect('127.0.0.1', 11211);

// Store a value (key, value, compression, expiration)
$mc->set('my_key', 'Hello Memcache!', 0, 3600);

// Retrieve a value
$value = $mc->get('my_key');
echo $value; // Output: Hello Memcache!

// Close connection
$mc->close();
?>

Database Query Caching Pattern

<?php
$mc = new Memcached();
$mc->addServer('127.0.0.1', 11211);

$cache_key = 'db_query_' . md5('SELECT * FROM users WHERE active = 1');
$result = $mc->get($cache_key);

if ($result === false) {
    // Cache miss - query the database
    $pdo = new PDO('mysql:host=localhost;dbname=mydb', 'user', 'pass');
    $stmt = $pdo->query('SELECT * FROM users WHERE active = 1');
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Store in cache for 5 minutes
    $mc->set($cache_key, $result, 300);
}

// Use $result (from cache or database)
print_r($result);
?>

Monitoring

There are several ways to monitor your Memcached server's performance and statistics. For more detailed monitoring approaches, see the Centmin Mod community forums.

Check Memcached Status

service memcached status

View Memcached Statistics

Use the stats command via the memcached protocol to view detailed statistics:

echo "stats" | nc 127.0.0.1 11211

Key Statistics to Monitor

Statistic Description
get_hits Number of successful cache lookups (cache hits)
get_misses Number of failed cache lookups (cache misses)
curr_items Current number of items stored in cache
bytes_read Total bytes read from the network by this server
bytes_written Total bytes written to the network by this server
evictions Number of items removed to free memory for new items (high value indicates need for more memory)

PHP-based Statistics

You can also retrieve statistics from within PHP:

<?php
$mc = new Memcached();
$mc->addServer('127.0.0.1', 11211);

$stats = $mc->getStats();
print_r($stats);

// Calculate hit rate
$server = $stats['127.0.0.1:11211'];
$hits = $server['get_hits'];
$misses = $server['get_misses'];
$total = $hits + $misses;

if ($total > 0) {
    $hit_rate = ($hits / $total) * 100;
    echo "Cache hit rate: " . round($hit_rate, 2) . "%\n";
}
?>

A high number of evictions indicates that Memcached needs more memory. Increase the CACHESIZE value in /etc/sysconfig/memcached and restart the service. If you prefer Redis server instead of Memcached, check out how to install it via the Addons page.