The slab allocator is the thing to understand to explain Memcached's memory behaviour. Memory is divided into 1 MB pages, each assigned to a slab class. A slab class holds items up to a given size - the classes grow by a configurable factor (-f, default 1.25), so there are classes for roughly 96 bytes, 120, 152, and so on up to 1 MB. An item is stored in the smallest class that fits it.
Two consequences follow. There is always internal waste: a 130-byte item in a 152-byte class wastes 22 bytes, and across millions of items that is real memory. Tuning the growth factor trades waste against the number of classes.
And there is slab calcification, which is the genuinely surprising failure. Once a page is assigned to a slab class, it historically stayed there. So an application that cached small items for a week and then changed to large ones found all its memory assigned to the small class, with the large class evicting constantly while stats showed plenty of free memory in the small class. Modern Memcached has slab automove and slab reassign to rebalance pages, and slab_reassign_rescues tells you it is working - but understanding the mechanism is what makes the symptom legible, and a sudden change in item size distribution is still a thing to watch for after a deployment.
The LRU is segmented, in three parts: HOT for new items, WARM for items read again, and COLD for eviction candidates. An LRU crawler moves items between them and reclaims expired items in the background. This makes Memcached's eviction notably better than a naive LRU - a single scan over cold data does not flush your working set, which is the classic LRU weakness.
Reading the metrics correctly is the operational skill. The distinctions that matter:
evictions- items removed to make room. Rising means undersized memory, or churn.evicted_unfetched- items evicted without ever being read. This is pure waste: you paid to store something nobody used. A high proportion means you are caching the wrong things.expired_unfetched- items that expired unread. Similar signal, less urgent.get_hits/get_misses- the hit ratio, the headline number.evicted_time- how long the last evicted item had been in the cache. This is the most underused Memcached metric: it tells you your effective cache lifetime. Ifevicted_timeis 40 seconds and your TTLs are 300, your TTLs are fiction - items are being evicted long before they expire, and raising the TTL will change nothing.reclaimed- expired items whose space was reused.curr_connectionsagainst-c- connection exhaustion.
Client-side hashing is how a pool works, and it is worth being precise about. The server knows nothing about other servers. The client hashes the key to pick a node. With naive modulo hashing (hash(key) % node_count), adding or removing a node changes the mapping of almost every key - so losing one node of five invalidates roughly 80% of the cache, not 20%, and that is a cold-cache event dressed as a single node failure.
Consistent hashing (ketama) places nodes on a hash ring so that losing one node remaps only its own keys. Losing one node of five invalidates about 20%. This is the difference between a survivable incident and an outage, it is a client configuration option, and the default in some clients is still modulo - which makes checking it a real task rather than a formality.
Laboratory exercise 4 - a measured improvement.
Load at least one million items with a realistic size distribution. Declare a baseline: five operations with p50, p95 and p99, plus the hit ratio, evictions, evicted_unfetched and evicted_time.
Demonstrate slab behaviour: inspect stats slabs and record the class distribution and the internal waste. Then cause calcification - fill the instance with small items, then switch to large ones - and record the evictions in the large class while memory sits in the small one. Then show slab automove rebalancing, with slab_reassign_rescues.
Use evicted_time properly: set TTLs of 300 seconds, undersize memory so evicted_time is well below that, and show that raising the TTL changes nothing. Then size memory correctly and show evicted_time rising above the TTL. That is what correctly-sized means.
Compare the growth factor: run with -f 1.25 and -f 1.08 on the same data and compare waste and class count.
Measure the hashing difference: a five-node pool with modulo hashing and with ketama. Remove one node in each and record the hit ratio immediately after. The difference should be roughly 80% against 20%.
Measure multi-get at one, three and five nodes.
Deliverable: the benchmark report with all percentiles at each step, the slab class distribution with waste, the calcification demonstration and its rebalance, the evicted_time experiment with the TTL conclusion, the growth factor comparison, the hashing comparison with both hit ratios, and one change that did not help.
# ==================================================================
# THE SLAB ALLOCATOR. What explains Memcached's memory behaviour.
# ==================================================================
# Memory -> 1 MB PAGES -> each assigned to a SLAB CLASS.
# A class holds items up to a size; classes grow by -f (default 1.25):
# class 1: 96 B class 2: 120 B class 3: 152 B ... 1 MB
# An item goes in the SMALLEST CLASS THAT FITS IT.
stats slabs
# STAT 3:chunk_size 152
# STAT 3:chunks_per_page 6898
# STAT 3:total_pages 48
# STAT 3:total_chunks 331104
# STAT 3:used_chunks 330980
# STAT 3:free_chunks 124
# STAT 3:mem_requested 43027400
#
# INTERNAL WASTE:
# used_chunks x chunk_size = 50,308,960 bytes allocated
# mem_requested = 43,027,400 bytes actually wanted
# waste = 7,281,560 bytes (14.5%)
#
# A 130-byte item in a 152-byte class wastes 22 bytes. Across
# millions of items that is real memory. Tuning -f trades waste
# against the number of classes:
# -f 1.25 fewer classes, more waste per item
# -f 1.08 more classes, less waste, more pages needed per class
# Measure both on YOUR size distribution.
stats items
# STAT items:3:number 330980
# STAT items:3:age 412 <- oldest item in this class
# STAT items:3:evicted 48201
# STAT items:3:evicted_time 38 <- SEE BELOW. The key metric.
# STAT items:3:outofmemory 0
# ==================================================================
# SLAB CALCIFICATION: the genuinely surprising failure.
# ==================================================================
# Once a page is assigned to a class, it historically STAYED THERE.
# So:
# week 1: cache small items -> all 64 MB assigned to class 3
# week 2: switch to large items -> class 9 has almost no pages and
# EVICTS CONSTANTLY, WHILE stats SHOWS PLENTY OF FREE
# MEMORY IN CLASS 3
#
# That symptom - "evictions high, memory free" - is incomprehensible
# without knowing the mechanism, which is why the mechanism is worth
# knowing.
#
# Modern Memcached rebalances:
# memcached -m 64 -o slab_reassign,slab_automove=1
stats
# STAT slab_reassign_rescues 1204 <- it IS working
# STAT slab_reassign_evictions_nomem 0
# STAT slabs_moved 48
#
# Manual, if you need it:
# slabs reassign 3 9 (take a page from 3, give to 9)
#
# A SUDDEN CHANGE IN ITEM SIZE DISTRIBUTION AFTER A DEPLOYMENT is
# still a thing to watch for. It presents as unexplained evictions.
# ==================================================================
# THE SEGMENTED LRU: better than a naive LRU.
# ==================================================================
# HOT new items
# WARM items read AGAIN
# COLD eviction candidates
# An LRU crawler moves items between segments and reclaims expired
# items in the background.
#
# The benefit: A SINGLE SCAN OVER COLD DATA DOES NOT FLUSH YOUR
# WORKING SET - the classic naive-LRU weakness. A batch job reading
# a million items once does not evict the hundred keys your front
# page needs.
# -o lru_maintainer,lru_crawler
stats
# STAT lru_crawler_running 0
# STAT crawler_reclaimed 48201
# STAT crawler_items_checked 1204000
# STAT lru_bumps_dropped 0
stats settings
# ==================================================================
# READING THE METRICS CORRECTLY. The operational skill.
# ==================================================================
stats
# STAT curr_items 998412 <- INCLUDES EXPIRED. Not live data.
# STAT total_items 48201337
# STAT bytes 66584320
# STAT limit_maxbytes 67108864
# STAT get_hits 94820133
# STAT get_misses 1204887 -> hit ratio 98.7%
# STAT evictions 482013 <- removed to make ROOM
# STAT evicted_unfetched 120488 <- EVICTED WITHOUT EVER BEING READ.
# PURE WASTE: you paid to store
# something nobody used. A high
# proportion means you are CACHING
# THE WRONG THINGS.
# STAT expired_unfetched 48201
# STAT reclaimed 912044
# STAT curr_connections 412
# STAT listen_disabled_num 0 <- > 0: CONNECTION LIMIT HIT. Every
# client was refused. Raise -c.
# STAT cmd_get 96025020
# STAT cmd_set 4820133
# STAT bytes_read / bytes_written
# ==================================================================
# evicted_time: THE MOST UNDERUSED MEMCACHED METRIC.
# ==================================================================
stats items
# STAT items:3:evicted_time 38
#
# = how long the LAST EVICTED ITEM had been in the cache.
# = YOUR EFFECTIVE CACHE LIFETIME.
#
# If evicted_time is 38 SECONDS and your TTLs are 300:
# YOUR TTLs ARE FICTION. Items are evicted long before they expire.
# RAISING THE TTL WILL CHANGE NOTHING. Either add memory or cache
# less.
#
# That is the whole lab experiment, and it reframes how you think
# about TTL tuning: a TTL above evicted_time is a wish.
#
# CORRECTLY SIZED means evicted_time comfortably EXCEEDS your TTLs,
# so items leave because they EXPIRED, not because they were pushed
# out.
# ==================================================================
# CLIENT-SIDE HASHING. The server knows nothing about other servers.
# ==================================================================
# The CLIENT hashes the key to pick a node.
#
# MODULO: node = hash(key) % node_count
# Adding or removing a node changes the mapping of ALMOST EVERY KEY.
# LOSING 1 NODE OF 5 INVALIDATES ~80% OF THE CACHE, not 20%.
# That is a COLD-CACHE EVENT dressed up as a single node failure,
# and Module 5 is about surviving it.
#
# CONSISTENT HASHING (ketama): nodes placed on a hash ring, with
# virtual nodes for balance.
# Losing 1 node of 5 remaps ONLY ITS OWN KEYS: ~20%.
#
# 80% vs 20% is the difference between an outage and an incident.
#
# IT IS A CLIENT CONFIGURATION OPTION, AND THE DEFAULT IN SOME
# CLIENTS IS STILL MODULO. Checking yours is a real task, not a
# formality:
# python pymemcache HashClient -> ketama by default
# PHP memcached.sess_consistent_hash / OPT_LIBKETAMA_COMPATIBLE
# Java spymemcached KetamaConnectionFactory (NOT the default)
# Ruby dalli -> ketama by default
# Go gomemcache -> MODULO. No ketama at all.
#
# MEASURE IT. Five nodes, remove one, record the hit ratio
# immediately after, with each hashing scheme. The numbers make the
# argument.
# ==================================================================
# Connection and item limits
# ==================================================================
# -c 1024 max simultaneous connections
# -t 4 worker threads (about one per core; more rarely helps)
# -I 2m max item size (fragmentation cost)
# -m 4096 memory in MB
# -f 1.08 slab growth factor
# -n 48 minimum chunk size
# -o modern enables the current recommended option set
# -o no_lru_crawler (do not; the crawler is good)
Discussion
No questions on this topic yet. Sign in to ask the first one.