
Memcached Telnet Commands Example
Memcached is that reliable workhorse you turn to when you need blazing-fast key-value storage without the overhead of a full database system. While most developers interact with Memcached through client libraries, understanding its raw telnet interface gives you superpowers for debugging, monitoring, and troubleshooting production issues. This deep dive will walk you through essential telnet commands, real-world troubleshooting scenarios, and some lesser-known tricks that’ll make you the Memcached wizard your team didn’t know they needed.
How Memcached Telnet Interface Works
Memcached uses a simple text-based protocol that’s perfect for telnet sessions. When you connect via telnet, you’re essentially speaking the same language that client libraries use under the hood. The protocol is stateless and human-readable, making it ideal for quick diagnostics and manual testing.
The basic communication pattern involves sending commands followed by parameters, and Memcached responds with either the requested data, confirmation messages, or error codes. Unlike HTTP, there’s no request headers or complex formatting β just plain text commands separated by spaces and terminated with carriage returns.
Essential Connection and Basic Commands
First things first β let’s get connected and try some basic operations:
telnet localhost 11211
Once you’re in, here are the fundamental commands every developer should know:
# Store a key-value pair (expires in 3600 seconds)
set mykey 0 3600 11
hello world
STORED
# Retrieve a value
get mykey
VALUE mykey 0 11
hello world
END
# Check if server is alive
version
VERSION 1.6.9
# Get basic stats
stats
STAT pid 1234
STAT uptime 86400
STAT curr_items 1
STAT total_items 15
STAT bytes 64
END
The syntax for storage commands follows this pattern: `command key flags exptime bytes`. The flags parameter is typically 0 unless you’re doing client-side compression or serialization. After entering the command, you type your data on the next line.
Advanced Storage and Retrieval Operations
Beyond basic get/set operations, Memcached offers several specialized commands that can save you from race conditions and provide atomic operations:
# Add only if key doesn't exist
add newkey 0 3600 5
value
STORED
# Replace only if key exists
replace newkey 0 3600 8
newvalue
STORED
# Append to existing value
append newkey 0 3600 6
_added
STORED
# Prepend to existing value
prepend newkey 0 3600 7
prefix_
STORED
# Check and set (CAS) - atomic update
gets newkey
VALUE newkey 0 21 123456789
prefix_newvalue_added
END
cas newkey 0 3600 12 123456789
updated_data
STORED
The CAS (Compare And Swap) operation is particularly useful in high-concurrency scenarios. The number after the data (123456789 in the example) is the CAS token that changes every time the key is modified.
Monitoring and Statistics Commands
Production troubleshooting often starts with understanding what’s happening inside your Memcached instance:
# General statistics
stats
STAT curr_connections 10
STAT total_connections 1500
STAT cmd_get 45231
STAT cmd_set 12043
STAT get_hits 38901
STAT get_misses 6330
STAT evictions 245
STAT bytes_read 15230944
STAT bytes_written 8901234
# Memory usage breakdown
stats slabs
STAT 1:chunk_size 96
STAT 1:chunks_per_page 10922
STAT 1:total_pages 1
STAT 1:total_chunks 10922
STAT 1:used_chunks 1
# Item statistics by slab class
stats items
STAT items:1:number 1
STAT items:1:age 3456
STAT items:1:evicted 0
STAT items:1:outofmemory 0
# Connection information
stats conns
CONN 10 unix:/tmp/memcached.sock
CONN 11 tcp:127.0.0.1:11211
Debugging and Troubleshooting Commands
When things go sideways in production, these commands become lifesavers:
# Enable verbose logging (shows all operations)
verbosity 2
OK
# Flush all data (use with extreme caution!)
flush_all
OK
# Flush all data after 60 seconds delay
flush_all 60
OK
# Check if specific keys exist
get user:1234 session:abc123 cache:homepage
VALUE user:1234 0 25
{"name":"John","id":1234}
VALUE cache:homepage 0 1024
...homepage content...
END
# Quit the telnet session
quit
Here’s a real-world debugging scenario: your application is reporting cache misses for keys you know should exist. Connect via telnet and run:
stats
# Look for high evictions - might indicate memory pressure
stats slabs
# Check if you're running out of space in specific slab classes
get your_missing_key
# Verify the key actually exists and check its expiration
Performance Analysis and Optimization
Understanding your Memcached performance characteristics helps optimize both your caching strategy and server configuration:
Metric | Command | What It Tells You |
---|---|---|
Hit Rate | stats (calculate hits/(hits+misses)) | Cache effectiveness |
Eviction Rate | stats evictions | Memory pressure indicator |
Connection Count | stats curr_connections | Client load and potential bottlenecks |
Memory Utilization | stats slabs | Memory allocation efficiency |
Network Usage | stats bytes_read/bytes_written | Bandwidth consumption |
A healthy Memcached instance typically shows:
- Hit rate above 80% for most applications
- Low eviction count relative to total items
- Stable connection count without rapid spikes
- Even distribution across slab classes
Comparison with Alternative Debugging Methods
Method | Pros | Cons | Best Use Case |
---|---|---|---|
Telnet Commands | Direct access, no dependencies, real-time | Manual process, no automation | Quick troubleshooting, debugging |
memcached-tool | Formatted output, easier parsing | Requires separate tool installation | Regular monitoring, scripting |
Application Logs | Context-aware, integrated workflow | Limited visibility into server state | Application-level debugging |
Monitoring Tools (Nagios, etc.) | Automated, alerting, historical data | Complex setup, potential overhead | Production monitoring |
Real-World Use Cases and Scenarios
Here are some battle-tested scenarios where telnet commands saved the day:
**Scenario 1: Memory Leak Investigation**
# Check for unusual growth patterns
stats
# Note the bytes value
# Wait 5 minutes, check again
stats
# Compare growth rate with expected usage
**Scenario 2: Load Balancer Health Checks**
Many load balancers can use simple telnet commands for health checking:
version
# Should return VERSION x.x.x if healthy
**Scenario 3: Cache Warming Validation**
After deploying cache warming scripts:
stats items
# Check that expected number of items are cached
get critical_key_1 critical_key_2
# Verify your most important keys are present
**Scenario 4: Debugging Client Connection Issues**
stats conns
# Look at current connections
stats
# Check if max_connections is being hit
Security Considerations and Best Practices
Memcached’s telnet interface is powerful but comes with security implications:
- Never expose Memcached ports directly to the internet β always use firewalls or VPNs
- Consider using SASL authentication in production environments
- Be extremely careful with flush_all commands in production
- Use verbosity sparingly as it can impact performance
- Monitor who has telnet access to your Memcached instances
For production environments, consider setting up SSH tunnels for secure access:
ssh -L 11211:memcached-server:11211 user@jump-server
telnet localhost 11211
Integration with Monitoring and Automation
While manual telnet sessions are great for troubleshooting, you can automate many of these commands for monitoring:
#!/bin/bash
# Simple health check script
(echo "stats"; echo "quit") | telnet localhost 11211 | grep "STAT uptime"
You can also integrate these commands with monitoring systems. Many ops teams create simple scripts that parse the stats output and feed it into their monitoring infrastructure.
The beauty of Memcached’s simple protocol is that you can easily build custom monitoring tools tailored to your specific needs. Whether you’re tracking cache hit rates, monitoring memory usage, or debugging weird client behavior, the telnet interface gives you direct access to the server’s internal state.
For comprehensive documentation on all available commands, check the official Memcached protocol documentation. The Memcached project homepage also contains additional resources for advanced configuration and optimization techniques.

This article incorporates information and material from various online sources. We acknowledge and appreciate the work of all original authors, publishers, and websites. While every effort has been made to appropriately credit the source material, any unintentional oversight or omission does not constitute a copyright infringement. All trademarks, logos, and images mentioned are the property of their respective owners. If you believe that any content used in this article infringes upon your copyright, please contact us immediately for review and prompt action.
This article is intended for informational and educational purposes only and does not infringe on the rights of the copyright owners. If any copyrighted material has been used without proper credit or in violation of copyright laws, it is unintentional and we will rectify it promptly upon notification. Please note that the republishing, redistribution, or reproduction of part or all of the contents in any form is prohibited without express written permission from the author and website owner. For permissions or further inquiries, please contact us.