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.

Video lesson · Chapter 1 of 5

Two additions erase fifty points

0:00 / 3:28

Theory

Read or listen first. About 1 min.

What it is

High-concurrency caching is the craft of letting many threads, processes or servers read and write the same cached data at the same moment without wrong results and without long queues.

There are two separate problems. Correctness: two writers must not destroy each other's work. Throughput: protecting the data must not make everyone wait in one line.

Why it exists

A cache is the busiest shared thing in many programs. A mistake that shows up once in a million operations happens every second at a million operations a second.

The most popular item is the hardest case. Spreading keys over many servers does not help when everyone wants the same key.

A short history

  1. 1965

    Edsger Dijkstra publishes a solution to the mutual exclusion problem: how to let only one program into a critical section.

  2. 1971

    Courtois, Heymans and Parnas describe how to synchronise readers and writers.

  3. 2004

    Java 5 is released with the java.util.concurrent package, which includes ConcurrentHashMap.

  4. 2013

    Facebook publishes a USENIX paper about running Memcached at very large scale.

  5. 2017

    Go 1.9 adds sync.Map, a map made for a few concurrent patterns.

Words to know

Race condition
The result depends on which thread happens to be first.
Critical section
Code that only one thread may run at a time.
Mutex
A lock with one holder.
Read-write lock
Many readers together, or one writer alone.
CAS
Compare-and-swap: store a new value only if the old one is still what you saw.
Contention
Waiting because others use the same lock or key.
Deadlock
Threads wait for each other in a circle and none can go on.

How it works

Step through the idea, or press Play.

Step 1 of 3

Make each change one step. A lock, compare-and-swap, or an atomic method of the map

Understand it

Start here

Face painting at the fair

Every child at the fair wants the tiger. The painters use a stencil of it. How many stencils there are, and who may touch one, decides whether the queue moves.

Everyone wants the tiger

When the design changes, all four stencils must be changed. Copies buy speed and cost updates.

The trouble

What goes wrong

  • Race conditions

    Threads read, change and write the same data at the same time.

  • Lost updates

    One thread's write removes another's change.

  • Contention

    Too much locking, and everyone waits. More cores do not help.

  • Deadlocks

    Two threads each hold one lock and wait for the other's.

A lost update

A adds 50 and B adds 100. Both started from 100, so A's addition is gone, without any error.

Where the sharing happens

PlaceWho competesTools
Inside one processThreadsLocks, concurrent maps, CAS
One async programTasks at each awaitAn async lock, or no await in the middle
Several serversProcesses on the networkAtomic commands, check and set, short locks with an expiry

One at a time

A mutex

A mutex has one holder. All others wait. It is the simplest tool, and it makes a whole read-change-write safe when every access uses it.

Text
mutex.lock()                # wait until it is freetry:    value = cache.get(key)  # only one thread here    cache.set(key, value + 1)finally:    mutex.unlock()          # always release
Locking the get and the set separately is not enough: another thread can come between.

Advantages

  • Simple to understand
  • One thread at a time, guaranteed
  • No race if every access takes it
  • Works for any kind of change

Disadvantages

  • Readers wait for readers
  • Can become the bottleneck
  • Deadlocks if locks are nested in different orders
  • Low throughput with many threads

The limit of one lock

Xmax=1theld=12 μs=500,000 operations per secondX_{max} = \frac{1}{t_{held}} = \frac{1}{2\,\mu s} = 500{,}000 \text{ operations per second}
If the lock is held for 2 microseconds each time, no number of threads passes 500,000 a second. Holding it during a 20 ms database read gives 50.

Readers together

A read-write lock

Three states

Many readers or one writer, never both.

Five reads of 10 microseconds each

LockHow they runTime
MutexOne after anotherabout 50 microseconds
Read-write lockTogether, on five coresabout 10, plus the lock's own work
For very short reads, the bookkeeping of a read-write lock can cost more than it saves. Measure.

It fits read-heavy data: 90% reads or more, such as configuration, reference lists and caches that rarely change. Watch two things. A constant stream of readers may starve a writer, depending on the lock. And upgrading from read to write needs a second check, because another writer may have come first.

No waiting

Compare-and-swap

  1. 1

    Read

    Read the value and its version: value 100, version 5.

  2. 2

    Compute

    Make the new value: 101.

  3. 3

    Swap if unchanged

    If the version is still 5, store 101 as version 6.

  4. 4

    Or try again

    If the version changed, start over, after a short random pause.

One wins, one retries

Good for

  • Small changes: counters, flags, a pointer
  • Low to moderate contention
  • Code that must not block
  • No deadlock, and some thread always makes progress

Watch out

  • Many retries when contention is high
  • The ABA problem: changed and changed back looks unchanged. A version number prevents it
  • Harder to get right
  • One thread can be unlucky for long

Ready made

Concurrent data structures

LanguageUseKnow
JavaConcurrentHashMapReads do not lock. Computing a missing value is one step, but keep it short, because other updates may wait
Gosync.Map, or a map with RWMutexsync.Map suits keys written once and read often, or goroutines with separate keys
Pythondict with threading.LockSingle dict operations are safe in CPython with the GIL. Read, change, write is not
NodeMap, plus an async lockOne thread, but another task can run at every await
For Java caches with size limits and expiry, a library such as Caffeine does this and eviction.

A map split into shards, each with its own lock

One application machine. Threads hash each key to one of four shards. Each shard has its own lock and its own part of the memory. On a miss the machine reads the database.
Two threads wait for each other only when their keys fall in the same shard.

Chance that another thread is in my shard

P=1−(1−1S)T−1T=8, S=32:;1−(3132)7≈20%P = 1 - \left(1 - \tfrac{1}{S}\right)^{T-1} \qquad T = 8,\ S = 32:; 1 - \left(\tfrac{31}{32}\right)^{7} \approx 20\%
With 8 threads all inside the map at once and keys spread evenly. With one lock it is 100%. Shards cost memory: a lock and a table each.

Misses

Many misses on one key

Concurrency hurts most at a miss: a hundred threads see nothing and all ask the database. Let one load and the others wait for its result. The topic thundering herd covers this fully.

One loader per key

The lock is per key, so loads of other pages are not held up.

Hot keys

When everyone wants one thing

Local copies in front of the shared cache

Users reach three application servers. Each server holds its own local copy of the hot key for one second. The shared cache machine is asked only when a local copy is old.
The reads stay on the application servers. The shared cache sees one refresh per server per second.

What local copies save

shared reads=serverslocal life=501 s=50/sin place of200,000/s\text{shared reads} = \frac{\text{servers}}{\text{local life}} = \frac{50}{1\,\text{s}} = 50/\text{s} \quad\text{in place of}\quad 200{,}000/\text{s}
50 servers, one second, one loader per server. The cost is a value that can be a second old.

Three ways to cool a hot key

WayHowCost
Local copyKeep it in each server for a secondSlightly old values
Several namesStore it under 10 names and read one at randomTen writes for each change
Read from replicasSpread reads over copies of the nodeMore machines, lag
See distributed caching, cache replication and consistency.

Choose

Trade-offs and a decision

ApproachThroughputComplexityBest for
MutexLow when busyLowLittle contention, any change
Read-write lockHigh for longer readsMediumMostly reads
CASHigh when conflicts are rareHighSmall changes
Concurrent mapHighLow, it is built inMost programs
Sharded locksHighMediumMany keys, many cores

Which one?

Guidelines

  • Start with a concurrent map
  • Measure before you optimise
  • Use a read-write lock when reads far outnumber writes
  • Go lock-free only when the lock is the bottleneck

Common mistakes

  • Lock-free code too early
  • A mutex where readers could share
  • Forgetting to release a lock
  • Holding a lock during input or output

Summary

The whole topic in one minute.

Protect every read-change-write as one step. A mutex is the simplest way, a read-write lock lets readers share, and compare-and-swap retries instead of waiting. Concurrent maps have this built in and are the right start.

Then reduce waiting: keep locked sections short, never do slow calls inside them, split one lock into many by key, and make extra copies of the few keys everyone wants.

  • Races lose data silently: make read-change-write one step.
  • A read-write lock allows many readers or one writer.
  • CAS reads, computes and swaps, and retries on a conflict.
  • A lock held for 2 microseconds caps at 500,000 operations a second.
  • Split locks by key, and copy the few hot keys.

Sources