AlgoViz

Distributed caching

medium 26 min

A distributed cache spreads keys over several servers, so it can hold more and answer more than one machine.

Video lesson · Chapter 1 of 5

Find one key among several cache machines

0:00 / 3:30

Theory

Read or listen first. About 1 min.

What it is

A distributed cache is a cache made of several servers that acts like one. Each key lives on one of them, or on a few if it is copied. All application servers see the same cached data.

The part that makes it work is a rule: from the key alone, any client can work out which server to ask. Nobody needs to search all of them.

Why it exists

One cache server has a limit on memory, on network and on requests. When the hot data no longer fits, or too many requests arrive, the choice is a bigger machine or more machines.

Sharing also removes waste. If ten application servers each keep their own copy, the same value is stored ten times and may differ between them. A shared cache stores it once.

A short history

  1. 1997

    Karger and co-authors at MIT introduce consistent hashing, written for distributed caching on the web.

  2. 2003

    Memcached is released. Its servers do not know each other: clients spread the keys.

  3. 2007

    Amazon's Dynamo paper describes virtual nodes, where each server owns several points on the ring.

  4. 2013

    Facebook publishes a USENIX paper about running Memcached as a large distributed cache.

  5. 2015

    Redis 3.0 ships Redis Cluster, which assigns 16,384 slots to servers.

Words to know

Node
One cache server in the group.
Partitioning
Splitting the keys so each node holds a part. Also called sharding.
Hash ring
A circle of numbers. Keys and nodes get places on it, and a key belongs to the next node clockwise.
Virtual node
One of several places a server takes on the ring.
L1 and L2
A small cache inside the program, then the shared cache over the network.
Serialisation
Turning a value into bytes for the network, and back.

How it works

Step through the idea, or press Play.

Step 1 of 3

Hash the key. Turn it into a number that any client computes the same way

Understand it

Start here

Hikers and rucksacks

A group of hikers carries snacks. One rucksack cannot hold them all, so they share them out with a rule everyone knows: the first letter of the snack says whose bag it is in.

Who carries the muffin?

The others did not have to swap anything. That is the sign of a good rule.

The idea

Why spread a cache

  • More room

    Memory adds up over nodes, so the cache can grow to terabytes.

  • More requests

    Load is divided, because each node answers only for its keys.

  • Shared state

    All application servers see the same values.

  • Smaller failures

    Losing a node loses a part of the cache, not all of it. Copies need replication.

One shared cache, three machines

Users reach two application servers through a load balancer. Both application servers use the same hash rule and send each key to one of three cache machines. On a miss an application server reads the database.
Both application servers apply the same rule, so they ask the same machine for the same key.

How many nodes for the data

N=⌈hot datamemory×usable share⌉=⌈30064×0.75⌉=⌈6.25⌉=7N = \left\lceil \frac{\text{hot data}}{\text{memory} \times \text{usable share}} \right\rceil = \left\lceil \frac{300}{64 \times 0.75} \right\rceil = \lceil 6.25 \rceil = 7
An example: 300 GB of hot data on 64 GB machines that we fill to 75%. Check the request rate too, and take the larger answer.

Alone first

Local cache or shared cache

Local cache (inside the program)

  • Very fast: no network
  • Simple to build
  • But each server has its own copy
  • But limited by one server's memory
  • But copies may differ between servers

Shared cache (over the network)

  • One copy for all servers
  • Grows by adding nodes
  • Keeps going when a node is lost, with more misses
  • But each call costs a network trip, often about a millisecond
  • But values must be turned into bytes and back, and it is one more system to run

When to use what

UseWhen
LocalData belongs to one server, is small, must be read in microseconds, and may be a little old
SharedData is shared, larger than one machine, or must outlive a restart of an application server, such as sessions
BothA few keys are very hot and the rest are many. Local for seconds, shared for longer

The rule

Partitioning by remainder

The simplest rule is the remainder after division: hash(key) % number_of_nodes. With three nodes, remainder 0 goes to node 1, remainder 1 to node 2 and remainder 2 to node 3. It is even and easy, until the number of nodes changes.

One key before and after

NodesCalculationNodeResult
3100 mod 3 = 1Node 2hit
4100 mod 4 = 0Node 1miss, read the database again

How many keys move from 3 to 4 nodes

remainder: 1−312=75%ring: 1N+1=14=25%\text{remainder: } 1 - \tfrac{3}{12} = 75\% \qquad \text{ring: } \tfrac{1}{N+1} = \tfrac{1}{4} = 25\%
Of any 12 hash values in a row, only 0, 1 and 2 have the same remainder for 3 and 4. A ring moves only the new node's share.

What a change does to the cache

ChangeRemainderHash ring
Add a node, 3 to 4about 75% of keys moveabout 25% move, to the new node
Remove a node, 4 to 3about 75% moveabout 25% move, those of the lost node
A node crashesmost reads miss togetheronly its share misses
Each moved key is one miss. 75% of reads going to the database at once can take it down.

The better rule

A hash ring

This is a short version. Consistent hashing has the full story.

  1. 1

    Place the nodes

    Hash each node to a place on a circle of numbers, for example 0 to 2^32.

  2. 2

    Place the key

    Hash the key with the same function.

  3. 3

    Walk clockwise

    The first node you meet owns the key. Past the end, continue from the start.

  4. 4

    Change the group

    A new node takes only the keys between itself and the node before it.

Walk clockwise

Places on a circle of 360 degrees. A key belongs to the next node at or after it.

Virtual nodes make the shares even

Points per serverLargest share of 3 servers
152%
1041%
15036%
Measured with the program in the Code tab and 20,000 keys. A perfect share is 33%. More points give a better balance and use more memory.

Who decides

Three places for the rule

Client, proxy or cluster

SystemRuleWho decides
MemcachedUsually a hash ringClient library, or a proxy
Redis Cluster16,384 hash slots, not a ringServers hold the map, clients learn it
Dynamo (the paper)Ring with virtual nodesAny node
CassandraToken ringAny node
The last two are databases. They use the same idea for stored data.

Growing

Adding and removing nodes

Adding a node without a stampede

Without the loading step, its share of reads all go to the database first. See cache warming and the thundering herd.

Adding a node

  • It joins at its points on the ring
  • It takes keys from each neighbour before its points
  • About 1 in N+1 keys move, the rest stay
  • Load hot keys first, then shift traffic slowly

Removing a node

  • Its keys go to the next nodes clockwise
  • All other keys stay
  • About 1 in N keys miss
  • If it is planned, copy its keys first

Rules of thumb for automatic scaling

SignalAction
Memory above 80% and evictions riseAdd a node
Memory below 30% for daysRemove a node, slowly
One node much hotter than the restLook for a hot key first, a new node will not help
Starting points, not laws. Each change moves keys, so do not let the group grow and shrink all day.

Two levels

A local cache in front

L1, then L2, then the database

Keep the local copy short, because nobody tells it when the value changes.

Average read time with two levels

T=h1t1+(1−h1) h2t2+(1−h1)(1−h2) tmiss=0.5(0.01)+0.45(1)+0.05(21)≈1.5 msT = h_1 t_1 + (1-h_1)\,h_2 t_2 + (1-h_1)(1-h_2)\,t_{miss} = 0.5(0.01) + 0.45(1) + 0.05(21) \approx 1.5\,\text{ms}
Assumed: half of reads hit L1 in 0.01 ms, 90% of the rest hit L2 in 1 ms, and a full miss takes 21 ms. Without L1 it is 0.9 + 2.1 = 3 ms.

Trade-offs

What you gain and what you pay

Advantages

  • Grows by adding nodes
  • All application servers share the same data
  • Can survive a node loss, and stays available with copies
  • Few keys move when the group changes
  • Load is spread

Challenges

  • A network trip for each call
  • Turning values into bytes and back
  • More to operate
  • Hot spots: one very hot key still lives on one node
  • A network split can leave clients with different views of the group

A node does not answer. What now?

Removing a node too quickly makes it flap in and out, and each time some keys move. See cache replication for copies.

Summary

The whole topic in one minute.

A distributed cache spreads keys over servers by a rule every client can follow. The rule should move as few keys as possible when the group changes, which is what a hash ring or a slot table does.

You pay for it with a network trip, serialisation and more parts that fail. Use a local cache for small hot data, a shared one for everything else, and size the database for the moment a node is lost.

  • A distributed cache spreads keys over nodes by a rule all clients share.
  • A remainder moves about 75% of keys from 3 to 4 nodes. A ring moves about 25%.
  • Virtual nodes even out the shares and spread the load of a lost node.
  • A shared cache costs a network trip. A local cache in front hides it for hot keys.
  • Size the database for the misses after a node is lost.

Sources