Skip to content
Memcached

Expiration, Eviction & TTL Strategy

Choose TTLs wisely and understand how Memcached evicts under pressure.

By EZ4Code Team
expirationttlevictionlru

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 eviction

Explanation

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