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.
Video lesson · Chapter 1 of 5
Two additions erase fifty points
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
1965
Edsger Dijkstra publishes a solution to the mutual exclusion problem: how to let only one program into a critical section.
1971
Courtois, Heymans and Parnas describe how to synchronise readers and writers.
2004
Java 5 is released with the java.util.concurrent package, which includes ConcurrentHashMap.
2013
Facebook publishes a USENIX paper about running Memcached at very large scale.
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.
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.
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
Where the sharing happens
| Place | Who competes | Tools |
|---|---|---|
| Inside one process | Threads | Locks, concurrent maps, CAS |
| One async program | Tasks at each await | An async lock, or no await in the middle |
| Several servers | Processes on the network | Atomic 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.
mutex.lock() # wait until it is freetry: value = cache.get(key) # only one thread here cache.set(key, value + 1)finally: mutex.unlock() # always releaseAdvantages
- 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
Readers together
A read-write lock
Three states
Five reads of 10 microseconds each
| Lock | How they run | Time |
|---|---|---|
| Mutex | One after another | about 50 microseconds |
| Read-write lock | Together, on five cores | about 10, plus the lock's own work |
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
Read
Read the value and its version: value 100, version 5.
- 2
Compute
Make the new value: 101.
- 3
Swap if unchanged
If the version is still 5, store 101 as version 6.
- 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
| Language | Use | Know |
|---|---|---|
| Java | ConcurrentHashMap | Reads do not lock. Computing a missing value is one step, but keep it short, because other updates may wait |
| Go | sync.Map, or a map with RWMutex | sync.Map suits keys written once and read often, or goroutines with separate keys |
| Python | dict with threading.Lock | Single dict operations are safe in CPython with the GIL. Read, change, write is not |
| Node | Map, plus an async lock | One thread, but another task can run at every await |
A map split into shards, each with its own lock
Chance that another thread is in my shard
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
Hot keys
When everyone wants one thing
Local copies in front of the shared cache
What local copies save
Three ways to cool a hot key
| Way | How | Cost |
|---|---|---|
| Local copy | Keep it in each server for a second | Slightly old values |
| Several names | Store it under 10 names and read one at random | Ten writes for each change |
| Read from replicas | Spread reads over copies of the node | More machines, lag |
Choose
Trade-offs and a decision
| Approach | Throughput | Complexity | Best for |
|---|---|---|---|
| Mutex | Low when busy | Low | Little contention, any change |
| Read-write lock | High for longer reads | Medium | Mostly reads |
| CAS | High when conflicts are rare | High | Small changes |
| Concurrent map | High | Low, it is built in | Most programs |
| Sharded locks | High | Medium | Many 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.