Skip to content
Memcached

add / replace / append / prepend

Conditional writes and in-place string concatenation.

By EZ4Code Team
addreplaceappendprepend

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