AlgoViz

High-concurrency caching

medium 28 min

When 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

Thread A+50Cache: counter100Thread B+100

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

Our systemFans200,000 reads/s50 app serversno local copyShared cache200,000 reads/s
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

    critical

    Another thread can change the value between the two locked steps.

    Wrong
    v = cache.get(key)      # locks insidecache.set(key, v + 1)   # locks inside
    Right
    with lock:    cache[key] = cache[key] + 1
  • Slow work inside the lock

    critical

    A 20 ms read caps the whole cache at 50 operations a second.

    Wrong
    with lock:    cache[key] = database.read(key)
    Right
    value = loader.load(key)   # one per key, no map lockwith lock:    cache[key] = value
  • No second check after upgrading

    major

    Between giving up the read lock and getting the write lock, another thread may have stored a value.

    Wrong
    if not seen_under_read_lock:    with rw.writing():        cache[key] = make()
    Right
    with rw.writing():    if key not in cache:        cache[key] = make()
  • An optimistic read of a plain hash map

    major

    With Java's StampedLock, a read during a write can walk a broken table before validation runs. It may fail or loop.

    Wrong
    long s = lock.tryOptimisticRead();V v = hashMap.get(key);   // unsafe
    Right
    V 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.