add / replace / append / prepend
Conditional writes and in-place string concatenation.
Code
# add — store ONLY if key does NOT exist
add session:abc 0 600 8
new-user
# STORED (key was absent)
# NOT_STORED (key already exists)
# replace — store ONLY if key exists
replace session:abc 0 600 8
returning
# STORED (key existed)
# NOT_STORED (key was absent)
# append / prepend — concatenate to existing value (no ttl change)
set greeting 0 0 5
hello
# STORED
append greeting 0 0 6
world
# STORED
get greeting
# VALUE greeting 0 11
# hello world
# Note: append/prepend do NOT let you change flags or ttl; existing
# flags and ttl are preserved. Use cas to change metadata atomically.Explanation
add only writes if the key is new (useful for locks/initialization); replace only writes if the key exists (useful for refresh-on-existing patterns). append/prepend concatenate bytes to the existing value without changing flags or ttl — handy for building log lines or buffers. None of these update exptime, so a cached value you append to will still expire on its original schedule. For atomic metadata changes use cas. All four return STORED / NOT_STORED / EXISTS / NOT_FOUND, letting you branch on the outcome.
More Memcached Snippets
set / get — Basic Key-Value
Store and retrieve values by key with expiration and flags.
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).
Expiration, Eviction & TTL Strategy
Choose TTLs wisely and understand how Memcached evicts under pressure.
Text vs Binary Protocol & Consistent Hashing
Pick the right protocol and shard across servers without reshuffling.