Memcached or Redis
easy 25 minMemcached and Redis both keep data in memory and answer in well under a millisecond on the server.
See it run
The same jobs on both servers: a plain read, a ranked board, a restart, a choice of type and a set of servers.
Operations
A plain get
Both servers answer a simple read. They differ in who does the work inside.
Step 1 of 4
Two servers, one key
Each server holds user:123. Memcached has several worker threads. Redis runs commands on one.
Step 1: Two servers, one key
def get_user(cache, key): return cache.get(key)- Round trips
- 1
- Work in the app
- None
- Database read
- 1 trip, much slower
For this job both are fine. The network takes most of the time.
In the real world
The same memcached or redis doing real jobs. Pick one and step through it.
The team caches product pages and wants a live top 100.
Step 1 of 4
Product pages
Whole pages, read often, easy to rebuild. Either server fits.
Step 1: Product pages
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Storing a board as one value
criticalTwo clients read, change and write. The second write removes the first one's change.
Wrongboard = json.loads(mc.get("board"))board["ana"] += 10mc.set("board", json.dumps(board))Rightr.zincrby("board", 10, "ana")# or, with Memcached, gets and cas with a retryNo memory limit or policy on a Redis cache
criticalRedis does not evict by default. Once full, writes fail, or the machine runs out of memory.
Wrong# redis.conf# maxmemory not setRightmaxmemory 4gbmaxmemory-policy allkeys-lruSetting the count and the expiry separately
majorIf the program dies between the two commands, the counter never expires and the user is blocked for good.
Wrongn = r.incr(key)if n == 1: r.expire(key, 60)Rightn = r.eval(LIMIT_SCRIPT, 1, key, 60)# INCR and EXPIRE run as one stepListing keys in production
majorKEYS walks every key in one command while everybody waits.
Wrongfor k in r.keys("user:*"): refresh(k)Rightfor k in r.scan_iter("user:*", count=500): refresh(k)
Interview tips
How to explain it
- Both are shared memory over the network.
- Memcached: whole values, many threads.
- Redis: structures, atomic commands, optional disk and replicas.
Memory trick: SIMPLE and RICH
- SIMPLE: plain values, many threads, light.
- RICH: types, logic in the server, cluster, a log.
- Tray for whole things, belt for work on things.
Reach for Redis when
- You rank, queue, count in windows or publish.
- One step must touch several values.
- Data should survive a restart or fail over.
Stay with Memcached when
- Every value is read and written whole.
- Losing it all costs only slow reads.
- Nobody needs another feature.