AlgoViz

Memcached

medium 30 min

Memcached is a small, fast, shared cache for plain values.

Video lesson · Chapter 1 of 5

A profile page asks one cache server

0:00 / 3:54

Theory

Read or listen first. About 2 min.

What it is

Memcached is a server that keeps small values in memory under a name. You can set a value, get it, delete it, or add to a counter. A value is a run of bytes: the server does not know what is inside.

Several servers make one large cache, but they do not know about each other. The client library hashes each key and talks to the server that the hash points at.

Why it exists

Asking a database the same question a thousand times wastes a thousand queries. A cache beside the database answers the repeats from memory. That takes load off the database and makes pages quicker.

It does one job, so it can be simple: no data types, no replication, no tables. Simple operations that take constant time are easy to predict and easy to run on many cores.

A short history

  1. 2003

    Brad Fitzpatrick develops Memcached for LiveJournal, according to the project's own page.

  2. August 2004

    Linux Journal describes it and names LiveJournal, Slashdot and Wikipedia among its users.

  3. April 2013

    Facebook engineers publish a paper on their use of it: billions of requests a second over trillions of items.

  4. July 2017

    Version 1.5.0 makes the segmented LRU and background clean-up the defaults.

  5. February 2018

    Version 1.5.6 turns UDP off by default after open servers are used in amplification attacks.

  6. September 2019

    Version 1.5.18 can keep its cache through a planned restart.

Words to know

Item
One key with its value, flags, expiry and bookkeeping.
Page
One megabyte of memory that is cut into chunks of one size.
Slab class
All pages with the same chunk size.
Chunk
One fixed-size place that holds one item.
LRU
Least recently used: the order in which items are evicted.
CAS
Check and set: store only if nobody changed the item since you read it.
Multiget
One request for several keys.
Client-side sharding
The client, not the server, chooses the server for a key.

How it works

Step through the idea, or press Play.

Step 1 of 3

The client hashes the key. And picks one of the servers

Understand it

Start here

The egg trays

Imagine a farm kitchen with egg trays that have fixed cup sizes. Every egg goes into the smallest cup it fits. The trays are quick to use because nobody ever cuts a cup to measure.

Eggs, cups and a hen that can lay more
smallmediumlargeFixed cup sizes

Fixed sizes make it fast and predictable. The price is some wasted room and eviction inside each size.

The whole

Servers that do not know each other

Three independent servers, one cache

Application servers with a Memcached client send get and set commands to three separate Memcached machines, chosen by hashing the key. There are no arrows between the Memcached machines. On a miss the application servers read the database and store the answer.
No arrow joins the Memcached servers. Adding one is a change in the clients' list of servers.

One read, from start to end

  1. 1

    Hash

    get user:42 starts in the client. It hashes the key and picks a server. The same key always gives the same server while the list is unchanged.

  2. 2

    Send

    The client keeps open connections to every server and sends the command to one of them, on TCP port 11211.

  3. 3

    Look up

    A worker thread finds the item in a hash table, checks that it has not expired, and marks it as used. Threads handle connections with libevent, 4 threads by default.

  4. 4

    Hit

    The value comes back with its 32-bit flags, and with a CAS number if you asked with gets. The client turns the bytes back into an object.

  5. 5

    Miss

    The server answers with nothing. The application reads the database and stores the value with a time to live.

  6. 6

    Store

    The server takes a chunk of the right class. If none is free it evicts an old item of that class.

Miss, then hit

This is cache-aside, the normal pattern. Write-behind does not suit Memcached: a crash would lose writes that the database never saw. Choosing a pattern compares them.

Memory

Slab classes

If a server allocated exactly the bytes of each item, years of adding and removing would leave holes of awkward sizes. Memcached instead takes memory in pages of 1 MB and cuts each page into equal chunks. The first class has 96-byte chunks and each next class is about 1.25 times larger, rounded up to 8 bytes.

The first classes with default settings

ClassChunkChunks per 1 MB page
196 B10,922
2120 B8,738
3152 B6,898
4192 B5,461
5240 B4,369
39, the last512 KB2
Items larger than the last chunk size, up to the 1 MB limit, are stored in several linked chunks.

Which class, and how much is wasted?

48+8+(20+1)+(60+2)=139 B⇒class 3 (152 B)152−139152≈8.6%48 + 8 + (20 + 1) + (60 + 2) = 139 \text{ B} \Rightarrow \text{class 3 (152 B)} \qquad \frac{152 - 139}{152} \approx 8.6\%
A 48-byte item header, 8 bytes for CAS, a 20-byte key with its end byte, and a 60-byte value with its line end. With factor 1.25 the waste is at most about a fifth of a chunk.
  • Growth factor -f

    1.25 by default. A smaller factor makes more classes and less waste per item.

  • Smallest item -n

    48 bytes for key, value and flags by default. Lower it for millions of tiny items.

  • Largest item -I

    1 MB by default, up to 1 GB. Large values are better split or kept elsewhere.

  • Memory -m

    64 MB by default, almost always too small. It covers items, not connections or the hash table.

Where does a new item go?

An item can only push out items of its own class.

Eviction

What leaves, and calcified memory

Each class keeps its own order of use. Since 1.5.0 that order has segments: new items start in HOT, items read again move to WARM, and the rest drift to COLD, where evictions happen. Items with a short life can have their own segment. A background crawler frees expired items, so they are not only found when somebody asks for them. The general idea is on cache eviction.

Sharding

The client decides

The simplest rule is the hash modulo the number of servers. It is fine until that number changes. Consistent hashing and distributed caching explain the better rules; here is the price of the simple one.

From 3 to 4 servers

h mod 3=h mod 4  ⟺  h mod 12∈{0,1,2}⇒stay=312=25%, moved=75%h \bmod 3 = h \bmod 4 \iff h \bmod 12 \in \{0,1,2\} \Rightarrow \text{stay} = \tfrac{3}{12} = 25\%,\ \text{moved} = 75\%
With consistent hashing about one key in four moves, the share the new server should have. In general modulo moves n of n + 1 when n grows by one.

Rules that clients use

RuleWhen a server is addedNote
ModuloAlmost every key movesNever for a production cache
Ring (Ketama)About 1 in N movesMany points per server, often 100 or more, even out the load
RendezvousAbout 1 in N movesWhat pymemcache's HashClient uses by default
ProxySet in one placemcrouter, or the proxy built into Memcached
All clients must use the same rule and the same list, or they look for the same key in different places. Weights give a larger machine more keys.

One of five servers dies

100 000×(1−0.95)=5 000/s;→;100 000×(0.05+0.955)=24 000/s100\,000 \times (1 - 0.95) = 5\,000 \text{/s} ;\to; 100\,000 \times \left(0.05 + \tfrac{0.95}{5}\right) = 24\,000 \text{/s}
Assumed: 100,000 reads a second and a 95% hit rate. The database suddenly sees almost five times the reads. That, not the lost data, is the danger.

Commands

The small set of operations

CommandDoesUse it for
get, getsRead; gets adds the CAS numberReads, and read before cas
setStore, replace what is thereFilling after a miss
addStore only if the key is absentA short lock, the first count
replaceStore only if the key existsRefreshing
append, prependAdd bytes to a valueSmall lists of ids
deleteRemoveInvalidation
incr, decrChange a decimal number atomicallyCounters; fails on a missing key
casStore if unchanged since getsUpdates by several writers
touch, gatSet a new time to live, and readSessions
Keys are at most 250 bytes without spaces. A time to live above 30 days is read as a calendar time in seconds since 1970, a classic bug.
Shell
# talk to a server by hand: command, then the value on its own line$ nc 10.0.0.11 11211set user:42 0 3600 4AshaSTOREDget user:42VALUE user:42 0 4AshaENDadd lock:home 0 10 11STOREDset hits 0 0 10STOREDincr hits 1010
In set user:42 0 3600 4: flags 0, 3,600 seconds, 4 bytes. Newer clients use the meta commands (mg, ms, md), which add options such as serving a stale value.
Python
import jsonfrom pymemcache.client.base import Clientfrom pymemcache.client.hash import HashClientclass JsonSerde:                                     # never unpickle data others can write    def serialize(self, key, value):        if isinstance(value, (str, bytes)):            return value, 1        return json.dumps(value), 2    def deserialize(self, key, value, flags):        return json.loads(value) if flags == 2 else valueone = Client(("localhost", 11211), timeout=0.5, connect_timeout=0.5,             default_noreply=False)                  # wait for the real answermany = HashClient([("mc1", 11211), ("mc2", 11211), ("mc3", 11211)],                  timeout=0.5, connect_timeout=0.5, use_pooling=True, max_pool_size=10,                  serde=JsonSerde(), default_noreply=False)many.set("user:42", {"name": "Asha"}, expire=3600)many.get_many(["user:42", "user:43"])                # missing keys are simply absentmany.set_many({"user:1": "a", "user:2": "b"}, expire=3600)many.delete_many(["user:1", "user:2"])def count(key):    n = one.incr(key, 1)    if n is not None:        return n    if one.add(key, "1", expire=60):                 # only one client wins        return 1    return one.incr(key, 1)def update(key, change, tries=5):    for _ in range(tries):        value, token = one.gets(key)        if value is None:            return False        if one.cas(key, change(value), token):       # True only if nobody changed it            return True    return False
With pymemcache's default noreply, add always returns True, so a lock built on it never refuses. Switch it off wherever the answer matters.

Many keys

The multiget hole

Asking for 100 keys in one request is cheap on one server. On ten servers the same request becomes about ten smaller ones. Adding servers does not reduce the number of requests each server handles: every server still sees one per page, only with fewer keys. That is the multiget hole.

One page, three servers

A good client sends these at the same time, so the page waits for the slowest one, not for the sum.

Helps

  • Parallel requests in the client
  • Keeping one user's small values in one key
  • Hashing on part of the key, so one user's keys share a server
  • A short local cache for very common keys
  • Copies of the whole cache when requests, not memory, are the limit

Costs

  • A busy user makes one server hot
  • A joined value is larger to read and rewrite
  • Copies need more memory and more invalidation

Freshness

Invalidation and stampedes

After a database write, delete the key and let the next read fill it. Deleting twice is harmless, and two writers cannot leave the older value behind by storing in the wrong order. A delete that gets lost leaves a stale value until the time to live ends, so always set one. Cache consistency covers the remaining race between a slow reader and a writer.

One rebuild after a popular key expires

Other cures: refresh early by chance, keep a stale copy, and add random seconds to every TTL. See thundering herd.
Python
import random, time, threadingclass Guarded:    def __init__(self, cache, load):        self.cache, self.load = cache, load    def locked(self, key, ttl=3600):        value = self.cache.get(key)        if value is not None:            return value        if self.cache.add("lock:" + key, "1", expire=10):            try:                return self._fill(key, ttl)            finally:                self.cache.delete("lock:" + key)        for _ in range(50):                          # at most 5 seconds            time.sleep(0.1)            value = self.cache.get(key)            if value is not None:                return value        return self.load(key)    def stale_ok(self, key, ttl=3600, grace=60):        box = self.cache.get(key)                    # [value, fresh_until]        if box is None:            return self._fill(key, ttl, grace)        value, fresh_until = box        early = fresh_until - time.time() < ttl * 0.1 and random.random() < 0.1        if time.time() >= fresh_until or early:            if self.cache.add("lock:" + key, "1", expire=10):                threading.Thread(target=self._fill, args=(key, ttl, grace), daemon=True).start()        return value    def _fill(self, key, ttl, grace=None):        value = self.load(key)        life = ttl + random.randint(0, ttl // 10)    # spread the expiry        if grace is None:            self.cache.set(key, value, expire=life)        else:            self.cache.set(key, [value, time.time() + life], expire=life + grace)        return value
The meta protocol can do this inside the server: mg home t v N30 R30 gives exactly one client the win flag shortly before expiry or on a miss.
Python
import timeclass Breaker:    """Skip the cache for a while after repeated failures."""    def __init__(self, threshold=5, rest=30):        self.threshold, self.rest, self.failures, self.opened = threshold, rest, 0, None    def allow(self):        return self.opened is None or time.monotonic() - self.opened >= self.rest    def record(self, ok):        if ok:            self.failures, self.opened = 0, None        else:            self.failures += 1            if self.failures >= self.threshold:                self.opened = time.monotonic()def read(key, cache, db, breaker):    if breaker.allow():        try:            value = cache.get(key)            breaker.record(True)            if value is not None:                return value        except Exception:            breaker.record(False)    return db(key)

Restart

What survives

EventWhat happens
Crash or plain restartThe cache is empty
Planned restart with -e and SIGUSR1Items are kept in a RAM disk file and reused (1.5.18 and later). Changes made meanwhile are missed
Machine rebootThe cache is empty
Larger than memoryextstore keeps keys in memory and moves values to flash. Still a cache
None of these make Memcached a place to keep the only copy.

Operations

Running it

Shell
# Debian and Ubuntu: apt-get install memcached    macOS: brew install memcachedmemcached -m 4096 -p 11211 -u memcache -l 10.0.0.11 -c 4096 -t 4# -m memory for items in MB (default 64)   -c connections (default 1024)# -t worker threads (default 4)            -l address to listen on# -f chunk growth (default 1.25)           -n smallest item (default 48 B)# -I largest item (default 1m)             -U UDP port (default 0, off)printf 'stats\r\nstats slabs\r\nstats items\r\nquit\r\n' | nc 10.0.0.11 11211
More threads than cores do not help, and the manual advises against 64 or more.

Numbers to watch

StatTells you
get_hits, get_missesHit rate = hits / (hits + misses). From 95% to 90% the database reads double
evictionsLive items pushed out. A steady rise means too little memory, or a starved class
bytes, limit_maxbytesMemory in use against the limit
curr_itemsHow many items are stored
curr_connectionsClose to -c means new clients wait
cmd_get, cmd_setOperations, from which you get rates

Cost and speed. The project's documentation says a fast machine easily handles more than 200,000 requests a second, and much more with tuning. Memory is the main cost, then the network. Memcached is under the BSD licence.

Decide

When to choose it

Choose it for

  • Plain get, set and delete of small values
  • Very many small objects
  • Many cores on one machine
  • Simple scaling by adding servers
  • Data that can always be rebuilt

Choose something else for

  • Lists, sets, rankings, scripts
  • Data that must survive
  • Built-in replication and failover
  • Messages between services
  • Values above a megabyte
  • Transactions beyond one key
AlternativeSameDifferentChoose it when
RedisShared memory cacheData types, persistence, replicas, its own cluster; one command thread per shard. See the comparisonYou need any of those
Local cache (Caffeine)Key-value, TTL, evictionInside one process, no network, not shared; a change is seen only thereSmall, hot, rarely changing data
DynamoDB with DAXRead load off a databaseManaged, only for DynamoDB, same APIYour data is in DynamoDB
Local and shared caches work well together: a few seconds in the process, then Memcached.

The bill

You getYou pay
Throughput on many coresOnly plain values
Low overhead and no crumbling memorySome waste in each chunk
Predictable operationsNo server-side logic
Servers that are easy to addClients that must hash, retry and agree
Long experience at large sitesCopies, failover and warming are yours to build

Summary

The whole topic in one minute.

Memcached is a shared memory for values you can rebuild. Threads give it throughput, slab classes keep memory from crumbling, and simple commands keep every operation short.

What it leaves out is left to you: choosing servers, surviving a lost node, invalidating, and protecting the database from many misses at once. Choose it when get, set and delete are really all you need.

  • Clients choose the server; servers never talk to each other.
  • Items live in fixed chunks; eviction happens inside a class.
  • Change the number of servers only with consistent hashing.
  • Delete on write, TTL always, one rebuild per popular key.
  • Plan for an empty server: the database must survive the misses.
  • Private network only, and no data you cannot rebuild.

Sources