How to Inspect and View All Key/Value Pairs in a Memcached Cache


2 views

When working with Memcached in production environments, developers often need to inspect what's actually stored in the cache. Unlike databases, Memcached doesn't provide a straightforward way to view all cached items, which can make debugging and maintenance challenging.

Memcached offers several commands for cache inspection:

stats items      # Shows all slabs with items
stats cachedump  # Dumps keys in specified slab
get [key]        # Retrieves specific value

For example, to dump keys from slab 1:

stats cachedump 1 100  # 100 is the limit of keys to show

The simplest way is to connect directly to Memcached:

telnet localhost 11211
stats items
stats cachedump [slab_id] [limit]
get specific_key

Here's a Python script to dump all keys:

import memcache
mc = memcache.Client(['localhost:11211'])

def dump_keys():
    slabs = mc.get_stats('items')[0][1]
    for slab in slabs:
        if 'items' in slab:
            slab_id = slab.split(':')[1]
            keys = mc.get_stats('cachedump ' + slab_id + ' 100')[0][1]
            for key in keys:
                print(key)

Several tools provide better visualization:

  • memcached-tool (part of memcached package)
  • phpmemcacheadmin
  • memcached-top

Remember that:

  1. stats cachedump is an undocumented feature
  2. It may impact performance on large caches
  3. Not all clients implement these commands

For production systems:

# Use with care and only when necessary
# Consider implementing your own logging
# Limit access to cache inspection tools

The most direct way to inspect Memcached content is using the telnet/nc protocol. Connect to your Memcached server and use these commands:

telnet localhost 11211
stats items
stats cachedump [slab_id] [limit]
get [key_name]

Example workflow:

$ telnet 127.0.0.1 11211
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
stats items
STAT items:1:number 5
STAT items:1:age 420
[...]
stats cachedump 1 10
ITEM user_1001 [15 b; 1609459200 s]
ITEM session_4829 [120 b; 1609459300 s]
get user_1001
VALUE user_1001 0 15
{"id":1001,"name":"John"}
END

For developers who prefer visual interfaces:

  • memcached-tool: Perl script included with Memcached
  • phpMemcachedAdmin: Web-based dashboard showing keys and values
  • Memcached Manager: Windows GUI tool for administration

Here's how to scan all keys in Python using python-memcached:

import memcache
mc = memcache.Client(['localhost:11211'], debug=0)

# This is approximate - Memcached doesn't officially support key iteration
for slab_id in [1,2,3,4,5]:  # Common slab IDs
    items = mc.get_stats('cachedump {} 100'.format(slab_id))
    if items:
        for line in items[0][1].split('\n'):
            if line.startswith('ITEM'):
                key = line.split()[1]
                print(f"Found key: {key} - Value: {mc.get(key)}")

For Node.js developers:

const memcached = require('memcached');
const client = new memcached('localhost:11211');

client.items((err, data) => {
  const slabs = Object.keys(data);
  slabs.forEach(slab => {
    client.cachedump(slab, 100, (err, items) => {
      items.forEach(item => {
        client.get(item.key, (err, value) => {
          console.log(Key: ${item.key}, Value: ${value});
        });
      });
    });
  });
});

Memcached wasn't designed for key enumeration - these methods have caveats:

  • The cachedump command may return incomplete results
  • There's no guarantee you'll get all keys
  • Production use may impact performance
  • Results aren't consistent across Memcached versions
  1. Always connect to non-production instances first
  2. Limit the number of items dumped (e.g., cachedump 1 100)
  3. Consider adding debug keys for important values
  4. Log critical cache operations in your application