The command set is small and that is the point. set stores unconditionally. add stores only if the key is absent. replace stores only if it is present. append and prepend extend an existing value. cas stores only if the value has not changed since you read it. get and gets retrieve (the second also returning a CAS token). delete removes. incr and decr change a numeric value atomically. touch updates a TTL without fetching the value. flush_all empties everything. stats reports.
That is essentially the whole surface, and a day with telnet covers it.
What Memcached does not do, and why it matters: no persistence - a restart loses everything; no replication - a node's data is gone when the node is; no data structures - values are opaque bytes; no queries, no scanning, no key enumeration in any supported way; no transactions; no clustering - the server knows nothing about other servers, and distribution is entirely the client's job.
The consequence to internalise in Module 1: anything stored only in Memcached is already lost. Every value must be reconstructible from a durable source. A system that cannot rebuild a cached value is not using a cache; it is using an unreliable database.
The limits, which are hard defaults:
- Key: 250 bytes, no spaces and no control characters. A key built by concatenating user input can exceed it, and the failure is a client error - so hash long keys.
- Value: 1 MB by default (raisable with
-I, with a memory-fragmentation cost). An object that grows past it stops being cacheable, silently, at a size you did not predict. - Memory: whatever
-msays, and when it is full Memcached evicts - which, unlike Redis, is the only behaviour and needs no configuration.
TTL semantics have one memorable rule. An expiry of 0 means never expire. A value up to 2,592,000 seconds (30 days) is treated as a relative offset from now. A value above that is treated as an absolute Unix timestamp. So set key 0 2592001 ... does not mean "30 days and one second from now" - it means a moment in January 1970, so the item is already expired and is never returned. This catches people, it fails silently, and the fix is to use absolute timestamps deliberately for anything beyond 30 days.
Also worth knowing: expiry is lazy. An expired item occupies memory until it is next requested or until the LRU crawler reaches it, so curr_items includes expired items and is not a count of live data.
Laboratory exercise 1 - provision and verify.
Stand up Memcached with a deliberately small -m so you can reach eviction, and run it with -vv so you can watch the commands.
Explore the entire command set over telnet, recording the response for each - including the failure responses: NOT_STORED from an add on an existing key, EXISTS from a stale cas, NOT_FOUND from a delete.
Load at least 100,000 items with a documented key scheme and a realistic value size distribution for the capstone's catalogue.
Then demonstrate each limit, with evidence: a key over 250 bytes and the client error; a value over 1 MB and SERVER_ERROR object too large for cache; and memory filling with evictions climbing in stats.
Then demonstrate the 30-day rule: set an item with an expiry of 2592001 and show that a get returns nothing at all.
Finally, show that curr_items includes expired items by setting items with a 1-second TTL, waiting, and comparing curr_items with what get returns.
Deliverable: an idempotent setup script, a README with the key scheme and value size distribution, a transcript of the whole command set with every response, the three limit demonstrations, the 30-day demonstration, and the lazy expiry evidence.
# ------------------------------------------------------------------
# Learn the TEXT PROTOCOL first. It is a handful of commands, and it
# shows you what your client library abstracts away - which matters
# here, because the two most consequential behaviours (key hashing
# and the CAS token) live in the CLIENT, not the server.
# ------------------------------------------------------------------
# docker run -d -p 11211:11211 memcached:1.6 -m 64 -vv
# -m 64 64 MB, deliberately small so you can reach eviction
# -vv verbose: watch every command arrive
# telnet localhost 11211 (or: nc localhost 11211)
version
# VERSION 1.6.21
# ------------------------------------------------------------------
# set <key> <flags> <exptime> <bytes>\r\n<data>\r\n
# ------------------------------------------------------------------
set product:SKU-001 0 300 42
{"name":"Keyboard","price":89.99,"stock":12}
# STORED
# ^flags ^TTL ^byte count - MUST match exactly, or the
# server desyncs and the next
# command fails confusingly
get product:SKU-001
# VALUE product:SKU-001 0 42
# {"name":"Keyboard","price":89.99,"stock":12}
# END
# ------------------------------------------------------------------
# The conditional stores - this is most of the useful behaviour.
# ------------------------------------------------------------------
add product:SKU-001 0 300 5
hello
# NOT_STORED <- the key EXISTS. `add` is "create if absent",
# and it is how you implement a lock.
replace product:SKU-999 0 300 5
hello
# NOT_STORED <- the key is ABSENT. `replace` is "update only".
append product:SKU-001 0 0 5
more
# STORED <- extends an existing value. Note flags and
# exptime are IGNORED by append/prepend.
delete product:SKU-001
# DELETED
delete product:SKU-001
# NOT_FOUND
# ------------------------------------------------------------------
# gets / cas - the compare-and-swap pair. Module 3.
# ------------------------------------------------------------------
set counter 0 300 1
5
# STORED
gets counter
# VALUE counter 0 1 42
# ^^ the CAS TOKEN - a version number
# 5
# END
cas counter 0 300 1 42
6
# STORED <- the token matched
cas counter 0 300 1 42
7
# EXISTS <- STALE TOKEN. Somebody else wrote first.
# Re-read and retry. This is optimistic
# concurrency, and it is the only one here.
# ------------------------------------------------------------------
# Atomic counters, and touch.
# ------------------------------------------------------------------
set hits 0 0 1
0
incr hits 1
# 1
incr hits 5
# 6
decr hits 2
# 4
# Atomic, server-side, no read needed.
# decr FLOORS AT ZERO - it never goes negative, which surprises
# people expecting it to wrap or error.
# incr on a MISSING key -> NOT_FOUND. It does NOT create the key,
# so you need `add` then `incr`, and the add may race - which is
# fine, because add failing means someone else created it.
touch product:SKU-001 600
# TOUCHED <- a new TTL WITHOUT fetching the value.
gat 600 product:SKU-001
# get-and-touch: fetch and extend in one command.
# ------------------------------------------------------------------
# MULTI-GET: matters more than it looks. Module 2.
# ------------------------------------------------------------------
get product:SKU-001 product:SKU-002 product:SKU-003
# VALUE product:SKU-001 0 42
# ...
# VALUE product:SKU-003 0 38
# ...
# END
# MISSES ARE SIMPLY ABSENT from the response - there is no
# placeholder. Your client must diff requested against returned to
# know what missed.
# ------------------------------------------------------------------
# THE LIMITS. Hard defaults.
# ------------------------------------------------------------------
# 1. KEY: 250 BYTES, no spaces, no control characters.
# A key built from concatenated user input CAN exceed it, and the
# failure is a client-side error. HASH LONG KEYS:
# key = "product:" + sha1(long_identifier).hexdigest()
# 2. VALUE: 1 MB by default.
set big 0 300 1100000
<1.1 MB of data>
# SERVER_ERROR object too large for cache
# Raisable with -I 2m, at a memory-fragmentation cost. The real
# risk is an object that GROWS past it silently, at a size you did
# not predict - a product with 400 variants, say.
# 3. MEMORY: whatever -m says. When full, Memcached EVICTS.
# Unlike Redis there is no policy to choose and no "refuse writes"
# mode. Eviction is the only behaviour, and it needs no
# configuration - which is one fewer thing to get wrong.
stats
# STAT evictions 48201 <- climbing: undersized, or churning
# STAT expired_unfetched 912
# STAT evicted_unfetched 4820 <- evicted BEFORE EVER BEING READ.
# Pure waste: you paid to store
# something nobody used.
# ------------------------------------------------------------------
# THE 30-DAY RULE. Memorise this; it fails silently.
# ------------------------------------------------------------------
# exptime = 0 never expires
# exptime <= 2592000 (30 days) RELATIVE seconds from now
# exptime > 2592000 ABSOLUTE UNIX TIMESTAMP
set forever 0 2592001 5
hello
# STORED
get forever
# END <- NOTHING. The item is "expired" since
# January 1970, so it is never returned.
#
# `set key 0 2592001` does NOT mean "30 days and one second". For
# anything beyond 30 days, pass an absolute timestamp DELIBERATELY:
# exptime = int(time.time()) + 86400 * 60
# ------------------------------------------------------------------
# EXPIRY IS LAZY.
# ------------------------------------------------------------------
# An expired item occupies memory until it is next REQUESTED or the
# LRU crawler reaches it. So:
stats
# STAT curr_items 100000 <- INCLUDES EXPIRED ITEMS.
# NOT a count of live data.
stats items
stats slabs
stats sizes # expensive on a large instance; dev only
# ------------------------------------------------------------------
# WHAT MEMCACHED DOES NOT DO. This is the design, not a gap.
# ------------------------------------------------------------------
# no persistence a restart loses EVERYTHING
# no replication a node's data dies with the node
# no data structures values are opaque bytes
# no queries no scanning, no key enumeration
# no transactions CAS per key is all there is
# no clustering THE SERVER KNOWS NOTHING ABOUT OTHER SERVERS.
# Distribution is entirely the CLIENT's job.
#
# THE CONSEQUENCE TO INTERNALISE NOW:
# ANYTHING STORED ONLY IN MEMCACHED IS ALREADY LOST.
# Every value must be reconstructible from a durable source. A system
# that cannot rebuild a cached value is not using a cache - it is
# using an unreliable database.
Discussion
No questions on this topic yet. Sign in to ask the first one.