Introduction Memcached divides memory into slab classes with fixed chunk sizes. When application object sizes do not align well with slab chunk sizes, significant memory is wasted as internal fragmentation. This reduces effective cache capacity and increases eviction rates for objects that could otherwise fit in memory.
Symptoms - `stats slabs` shows large `free_chunks` in some classes but `evictions` in others - Memory usage shows high utilization but cache hit rate is low - `stats items` shows `evictions` increasing while total memory is not full - Object sizes cluster around values between slab class boundaries - Cache hit rate drops as effective capacity is much lower than allocated memory
Common Causes - Default growth factor (2.0) creates chunk sizes that do not match object distribution - Application stores objects of uniform size (e.g., 500 bytes) in a 1024-byte slab class - No slab class tuning performed after deployment - Mixed workload with both small and large objects - Memcached started with default settings without analyzing object sizes
Step-by-Step Fix 1. **Analyze current slab class distribution": ```bash # Get slab class information echo "stats slabs" | nc localhost 11211
# Get item sizes echo "stats items" | nc localhost 11211 ```
- 1.**Check the current growth factor and slab sizes":
- 2.```bash
- 3.# Start memcached with verbose mode to see slab sizes
- 4.memcached -vv 2>&1 | head -30
- 5.# Shows: slab class 1: chunk size 96 perslab 10922
- 6.# slab class 2: chunk size 120 perslab 8738
- 7.# etc.
- 8.
` - 9.**Restart with an optimized growth factor":
- 10.```bash
- 11.# Default growth factor is 2.0. Use 1.25 for finer granularity
- 12.memcached -m 4096 -f 1.25 -n 128 -p 11211 -d
# -f 1.25: growth factor between slab classes # -n 128: minimum chunk size (bytes) # -m 4096: max memory in MB ```
- 1.**Use stats sizes to analyze actual object distribution":
- 2.```bash
- 3.# Enable detailed size tracking (adds overhead, use temporarily)
- 4.memcached -o track_sizes
# After collecting data, analyze echo "stats sizes" | nc localhost 11211 # Shows: size count # This reveals the actual distribution of stored object sizes ```
- 1.**Separate object types into different Memcached instances":
- 2.```bash
- 3.# Run separate instances for different object sizes
- 4.memcached -p 11211 -m 2048 -f 1.25 -n 64 # Small objects (sessions)
- 5.memcached -p 11212 -m 2048 -f 1.5 -n 512 # Large objects (rendered pages)
- 6.
`