Expiration, Eviction & TTL Strategy
Choose TTLs wisely and understand how Memcached evicts under pressure.
Code
# exptime semantics
set k1 0 0 5 # 0 = no expiration (live until evicted)
hello
set k2 0 30 5 # expires in 30 seconds
world
set k3 0 86400 5 # 1 day
long
set k4 0 100000000 5 # > 30 days => treated as UNIX timestamp
abs
# After expiration, key is removed LAZILY (on next access or eviction),
# not actively swept. Active sweep runs every ~1s but isn't guaranteed.
# Touch — change TTL without rewriting value
touch session:abc 60 # extend to 60s
# Gat (get-and-touch) — read and extend in one round trip
gat 60 session:abc
# Eviction (LRU) — when memory is full and a new item arrives:
# - least recently used item in the matching slab is evicted
# - evictions counter increments
# - ttl does NOT protect from eviction; ttl=0 is just "no timed expiry"
# Strategies:
# hot data -> short TTL (60s) + refresh on miss (read-through)
# sessions -> TTL = session timeout
# computed -> TTL = source-data freshness window
# "permanent" -> TTL 0 + accept eventual evictionExplanation
exptime 0 means no timed expiry (item lives until evicted by LRU). Values ≤ 30 days are seconds-from-now; values > 30 days are treated as absolute UNIX timestamps. Expiration is lazy — items aren't actively deleted at expiry; they're dropped on next access or when memory pressure evicts them. touch changes a TTL without rewriting the value; gat reads and extends in one round trip (great for sessions). Eviction is per-slab LRU: when a slab class is full, the least-recently-used item is bumped to make room — evictions will rise. Tune by giving Memcached enough RAM and matching TTLs to your freshness requirements.
More Memcached Snippets
set / get — Basic Key-Value
Store and retrieve values by key with expiration and flags.
add / replace / append / prepend
Conditional writes and in-place string concatenation.
cas / gets — Compare-And-Swap
Optimistic locking: update a key only if it hasn't changed since you read it.
stats — Server Metrics & Slabs
Inspect memory, hit rate, evictions and per-slab allocation.
flush_all — Invalidate Everything
Logically invalidate all keys instantly (lazy deletion).
Text vs Binary Protocol & Consistent Hashing
Pick the right protocol and shard across servers without reshuffling.