set / get — Basic Key-Value
Store and retrieve values by key with expiration and flags.
Code
# telnet / nc style protocol (text)
set user:42 0 3600 13
hello, world!
# STORED
# ^ flags=0 ^ ttl=3600s ^ bytes=13
get user:42
# VALUE user:42 0 13
# hello, world!
# END
get user:42 user:43
# multiple keys in one request (response per key)
delete user:42
# DELETED
incr counter 1
decr counter 1
# Python (pymemcache)
from pymemcache.client.base import Client
c = Client(("localhost", 11211))
c.set("user:42", b"hello, world!", expire=3600, flags=0)
print(c.get("user:42")) # b"hello, world!"Explanation
set writes a value (overwriting any existing); get reads it. The text-protocol line is: <cmd> <key> <flags> <exptime> <bytes> then the data on the next line. flags is an opaque 16-bit int you can use for serialization hints (e.g. 1 = json). exptime is in seconds (0 = no ttl; <=30 days); unix timestamps >30 days are interpreted as absolute. get accepts multiple keys at once for batching. Values are byte strings — serialize JSON/pickle in your client. Keys are max 250 chars, no spaces/newlines.
More Memcached Snippets
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).
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.