High-concurrency caching
medium 28 minWhen many threads or servers use one cache at once, two things go wrong: updates are lost, and everyone queues for the same lock or the same hot key.
See it run
Five threads, one cache entry. See what breaks without protection and what each kind of protection costs.
Operations
No lock
Two threads add to one counter at the same time. One addition disappears.
Step 1 of 4
Start
The counter is 100. A will add 50 and B will add 100. The right end is 250.
Step 1: Start
def add(key, n): value = cache.get(key) # both read 100 cache[key] = value + n # the second write wins- Waiting
- None
- Correct?
- No
- With a lock
- correct, some waiting
Nothing fails and nothing is logged. That is what makes races dangerous.
In the real world
The same high-concurrency caching doing real jobs. Pick one and step through it.
Every fan opens the same page.
Step 1 of 3
All reads hit one node
- Load on the cache node
- 100%
Node is full
The page is one key, so one cache node gets everything.
Step 1: All reads hit one node
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Locking each step but not the whole
criticalAnother thread can change the value between the two locked steps.
Wrongv = cache.get(key) # locks insidecache.set(key, v + 1) # locks insideRightwith lock: cache[key] = cache[key] + 1Slow work inside the lock
criticalA 20 ms read caps the whole cache at 50 operations a second.
Wrongwith lock: cache[key] = database.read(key)Rightvalue = loader.load(key) # one per key, no map lockwith lock: cache[key] = valueNo second check after upgrading
majorBetween giving up the read lock and getting the write lock, another thread may have stored a value.
Wrongif not seen_under_read_lock: with rw.writing(): cache[key] = make()Rightwith rw.writing(): if key not in cache: cache[key] = make()An optimistic read of a plain hash map
majorWith Java's StampedLock, a read during a write can walk a broken table before validation runs. It may fail or loop.
Wronglong s = lock.tryOptimisticRead();V v = hashMap.get(key); // unsafeRightV v = concurrentMap.get(key);// keep optimistic reads for simple fields
Interview tips
How to explain it
- Make read-change-write one step.
- Then shorten or split the waiting.
- Then copy the few hot keys.
Memory trick: LOCK
- Limit access to critical sections.
- One writer at a time, concurrent readers fine.
- Keep the lock short.
Start with
- A concurrent map from the standard library.
- An atomic increment for counters.
- One loader per key for misses.
Warning signs
- Idle cores and slow requests.
- A database call inside a lock.
- Two locks taken in different orders.