Install Memcached in 5 Minutes
Installing Memcached is actually easier than you might think. With no complex configuration required, you can get it up and running immediately on Ubuntu/Debian—the go-to operating systems for modern servers.
1. Installation on Ubuntu
sudo apt update
sudo apt install memcached libmemcached-tools -y
2. Check Status
The service will start automatically after installation. Use this command to ensure it’s running:
sudo systemctl status memcached
3. Quick Test with Telnet
Instead of writing code right away, you can “talk” directly to Memcached via Telnet. This method is extremely useful for quick debugging.
telnet localhost 11211
# Syntax: set <key> <flags> <exptime> <bytes>
set session_id 0 60 5
abc12
# Get data: get <key>
get session_id
# Result:
# VALUE session_id 0 5
# abc12
# END
In this example, I’m storing a session_id with the value abc12 for 60 seconds. Everything happens in less than a millisecond.
Why Does Memcached Still Thrive Despite Redis’s Power?
Many engineers ask: “Why use Memcached when Redis has more features?”. The answer lies in focus. While Redis tries to do everything, Memcached focuses on doing one thing only: caching data at lightning speed.
Memcached is a distributed in-memory key-value store. It doesn’t care about complex logic; it only understands strings and serialized objects. This simplicity is exactly what helps it achieve incredibly high throughput.
Practical Strengths:
- Multi-threaded Architecture: This is the secret weapon. Memcached takes full advantage of multi-core CPUs (e.g., servers with 32 or 64 cores). Redis is (essentially) single-threaded for command processing, so in pure throughput benchmarks, Memcached often takes the lead.
- Slab Memory Allocation: This mechanism allows the server to run for years without slowing down due to RAM fragmentation.
- Resource Efficiency: If you only need to store sessions or cache SQL results, Memcached consumes significantly less RAM and CPU than Redis.
Real-world Comparison: Memcached vs Redis
Here is a comparison table based on my practical project deployment experience:
| Feature | Memcached | Redis |
|---|---|---|
| Data Types | Simple Strings only | Lists, Hashes, Sets, Geospatial… |
| Processing | Multi-threaded (Better multi-core utilization) | Single-threaded (Has I/O threads in newer versions) |
| Persistence | No (Lost on reset) | Yes (Writes to disk) |
| Key/Value Limits | Max value 1MB | Value up to 512MB |
Choosing Strategy: Choose Memcached if you need a pure caching layer for systems with massive traffic (e.g., 100,000 requests/second). Choose Redis when you need complex data structures or don’t want to lose your cache when restarting the server.
Slab Allocation Mechanism: The Secret to Stability
Memory fragmentation is a nightmare for in-memory systems. If RAM is allocated haphazardly, the server will eventually report it’s out of RAM even though many small gaps remain.
Memcached solves this by dividing RAM into “Slab Classes.” For example, Class 1 contains only 64-byte slots, and Class 2 contains 128-byte slots. When you store 100 bytes of data, it goes into a 128-byte slot. Accepting a few wasted bytes ensures the system never has to perform expensive Garbage Collection, keeping latency consistently ultra-low.
Using with Python (Practical Example)
Here is how I typically use it to reduce Database load (simulating a 3-second query):
import time
from pymemcache.client.base import Client
# Connect to Memcached
client = Client(('localhost', 11211))
def get_user_profile(user_id):
# Try to get from cache first
cache_key = f'user:{user_id}'
data = client.get(cache_key)
if data:
return data.decode('utf-8')
# If cache miss, simulate DB query
time.sleep(3)
result = f"Profile for user {user_id}"
# Store for 10 minutes
client.set(cache_key, result, expire=600)
return result
# First time: 3s wait
print(get_user_profile(99))
# Second time: Instant response
print(get_user_profile(99))
Crucial Security Notes
Don’t let Memcached’s simplicity fool you. When moving to production, keep these two things in mind:
1. Block Port 11211 Immediately
By default, Memcached does not require a password. In 2018, GitHub suffered a record-breaking 1.35 Tbps DDoS attack because hackers exploited publicly accessible Memcached servers. Always configure -l 127.0.0.1 or use a Firewall to only allow access from your App Server’s IP.
2. Increase RAM Limits
By default, Memcached only uses 64MB of RAM—a very modest amount for modern applications. Increase it based on your available resources:
# Edit in /etc/memcached.conf
-m 1024 # Increase to 1GB RAM
Memcached might not be flashy, but it is a hardworking and extremely reliable “worker.” If you need maximum speed for simple tasks, don’t hesitate to choose it.
