Memcached
medium 30 minMemcached is a small, fast, shared cache for plain values.
See it run
Fixed chunk sizes, eviction inside a class, clients that choose the server, and what a miss costs.
Operations
Store an item
How a 139-byte item finds its chunk.
Step 1 of 5
Four classes
| pages | used | free | evicted | |
|---|---|---|---|---|
| 96 B | 1 | 4000 | 6922 | 0 |
| 120 B | 0 | 0 | 0 | 0 |
| 152 B | 0 | 0 | 0 | 0 |
| 192 B | 1 | 5000 | 461 | 0 |
Two pages are in use, one for the smallest class and one for the largest shown. No class is full.
Step 1: Four classes
need = 48 + 8 + len(key) + 1 + len(value) + 2cls = smallest_class(need)if cls.has_free(): chunk = cls.take()elif pages_left(): cls.cut(new_page()); chunk = cls.take()else: chunk = cls.evict_oldest()chunk.write(key, value)- Cost
- Constant
- Watch out for
- Waste per chunk
- Exact sizes
- no waste, then holes
Small values feel the overhead most. 56 bytes of bookkeeping around a 10-byte value is most of the memory.
In the real world
The same memcached doing real jobs. Pick one and step through it.
The home page entry expires while two servers ask for it.
Step 1 of 4
Both miss
Two misses
The entry has just expired.
Step 1: Both miss
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Hash modulo the number of servers
criticalOne more server turns most reads into misses.
Wrongserver = servers[hash(key) % len(servers)]Rightserver = rendezvous(key, servers)A lock that always succeeds
criticalpymemcache does not wait for the answer by default, so add returns True for everyone.
Wrongif client.add("lock:home", "1", expire=10): ...Rightif client.add("lock:home", "1", expire=10, noreply=False): ...A TTL above 30 days
majorThe server reads it as a date, which is long ago, so the item expires at once.
Wrongclient.set(k, v, expire=60 * 60 * 24 * 60)Rightclient.set(k, v, expire=60 * 60 * 24 * 30)Counting with incr only
minorincr on a missing key fails, and two clients that set 1 lose a count.
Wrongif c.incr(k, 1) is None: c.set(k, "1")Rightif c.incr(k, 1) is None and not c.add(k, "1"): c.incr(k, 1)Open to the network
criticalThere is no password by default.
Wrongmemcached -l 0.0.0.0Rightmemcached -l 10.0.0.11 # private, behind a firewall
Interview tips
How to explain it
- Plain values in memory, many threads.
- Clients choose the server.
- Fixed chunks, eviction per class.
Before production
- Set -m, -c and a private address.
- Consistent or rendezvous hashing.
- TTL on every key.
- Test the database with an empty cache.
Reach for it when
- You only need get, set and delete.
- Everything can be rebuilt.
- You want to use many cores per machine.
Be careful when
- You need structures or copies.
- Pages need hundreds of keys.
- Value sizes change over time.