Complete Guide to Retrieving All Keys in Memcached: From Telnet to Toolchain

Nov 24, 2025 · Programming · 17 views · 7.8

Keywords: Memcached | Key Enumeration | Telnet | stats Commands | Cache Debugging

Abstract: This article provides an in-depth exploration of various methods to retrieve all stored keys in Memcached instances. It begins with a detailed analysis of the core workflow using stats items and stats cachedump commands through Telnet sessions, covering slab identification, cache dumping, and key extraction. The article then introduces professional tools like memcdump and memcached-tool, along with an analysis of the underlying principles in PHP implementation. Through comprehensive code examples and operational demonstrations, it systematically addresses the technical challenges of Memcached key enumeration, suitable for development debugging and system monitoring scenarios.

Technical Background of Memcached Key Enumeration

In the daily operation and development debugging of distributed caching systems like Memcached, retrieving all currently stored key names is a common but non-standardized requirement. Since Memcached was originally designed as a high-performance key-value store without direct key enumeration interfaces, this presents challenges for developers during debugging processes.

Key Enumeration Methods via Telnet Session

Connecting to the Memcached server through Telnet represents the most fundamental approach to key enumeration. First, establish the connection:

telnet 127.0.0.1 11211

Slab Identification Phase

Execute the stats items command to obtain all active slab identifiers:

stats items
STAT items:3:number 1
STAT items:3:age 498
STAT items:22:number 1
STAT items:22:age 498
END

The first number in the output (such as 3 and 22) represents the slab id, indicating different memory allocation units.

Cache Dump Operation

For each identified slab id, use the stats cachedump command for key enumeration:

stats cachedump 3 100
ITEM views.decorators.cache.cache_header..cc7d9 [6 b; 1256056128 s]
END

stats cachedump 22 100
ITEM views.decorators.cache.cache_page..8427e [7736 b; 1256056128 s]
END

The second parameter (100) specifies the maximum number of keys to return, which can be adjusted based on actual requirements. The ITEM line contains complete key names and metadata information.

Usage of Professional Toolchain

Beyond manual Telnet operations, the Memcached ecosystem provides specialized tools to simplify the key enumeration process.

memcdump Tool

memcdump (sometimes called memdump) is a dedicated command in the libmemcached-tools package:

memcdump --servers=localhost

This command directly returns all stored key names without requiring manual slab structure parsing.

memcached-tool Utility

The built-in memcached-tool in newer Memcached versions offers more powerful functionality:

memcached-tool localhost:11211 dump | less

This command not only enumerates key names but also outputs corresponding values, suitable for comprehensive cache data inspection.

Underlying Principles of PHP Implementation

By examining the implementation of PHP's Memcached::getAllKeys method, we can understand the complete algorithm flow for key enumeration. The core logic consists of three main phases:

Connection Establishment and Slab Discovery

Establish a raw socket connection to the Memcached server via fsockopen, send the stats items command, and parse the response to identify all active slab identifiers:

$mem = @fsockopen($host, $port);
$r = @fwrite($mem, 'stats items' . chr(10));
while (($l = @fgets($mem, 1024)) !== false) {
    $l = trim($l);
    if ($l == 'END') break;
    $m = [];
    $r = preg_match('/^STAT\sitems\:(\d+)\:/', $l, $m);
    if ($r == 1) {
        $a_slab = $m[1];
        if (!array_key_exists($a_slab, $slab)) {
            $slab[$a_slab] = [];
        }
    }
}

Key Extraction Process

Iterate through each slab, send the stats cachedump command, and parse ITEM responses:

foreach ($slab as $a_slab_key => &$a_slab) {
    $r = @fwrite($mem, 'stats cachedump ' . $a_slab_key . ' 100' . chr(10));
    while (($l = @fgets($mem, 1024)) !== false) {
        $l = trim($l);
        if ($l == 'END') break;
        $m = [];
        $r = preg_match('/^ITEM\s([^\s]+)\s/', $l, $m);
        if ($r == 1) {
            $a_key = $m[1];
            $a_slab[] = $a_key;
        }
    }
}

Result Integration and Cleanup

Merge key names distributed across various slabs into a unified array, then close the connection to release resources:

$keys = [];
foreach ($slab AS &$a_slab) {
    foreach ($a_slab AS &$a_key) {
        $keys[] = $a_key;
    }
}
@fclose($mem);
unset($mem);
return $keys;

Technical Points and Considerations

Several critical issues require attention in practical applications. First, the performance limitations of the stats cachedump command—it may not return all keys in a slab, particularly in high-load environments. Second, this method is primarily suitable for development debugging scenarios, as frequent use in production environments may impact cache performance.

For large-scale Memcached clusters, using toolchain approaches rather than manual Telnet operations is recommended to improve efficiency and reliability. Additionally, subtle differences in command support and output formats across different Memcached versions should be noted.

Application Scenarios and Best Practices

Key enumeration functionality holds significant value in multiple scenarios: cache status inspection during development debugging, data validation during system migration, and key distribution statistics for performance analysis. It's advisable to perform such operations during off-peak hours and set reasonable limits on the number of returned keys to avoid unnecessary pressure on production systems.

Through the various methods introduced in this article, developers can select the most appropriate key enumeration solution based on specific requirements, effectively addressing this common challenge in Memcached operations.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.