Skip to content

Consistent hashing

Sometimes a request has to reach one particular server: the one that holds the user’s cache entries, or a shard of the data, or the session. A balancer can keep a table of where each key went, which costs memory and has to be shared. It can also compute the server from the key, with a hash. A hash function turns a key into a number that looks random but is always the same for the same key, so any balancer computes the same answer without sharing anything. nginx has a hash directive for it, and HAProxy offers balance source for server affinity by IP address and balance uri for cache servers.

The simplest rule is hash mod N: with N servers numbered from 0, send a key to the server numbered hash mod N.

Hash mod N works until N changes. A key stays on its server only if the hash gives the same remainder for the old and the new number of servers. Take 4 servers growing to 5. Of the 20 possible pairs of remainders, a hash mod 4 and a hash mod 5, a random hash is equally likely to give any, and only 4 of the 20 are equal: 1 key in 5 stays, and 80% move. Removing one of 4 servers is the same: 3 of the 12 possible pairs are equal, so 1 key in 4 stays and 75% move. Counted on 20,000 keys, the model gives 79.8% and 74.8%.

Almost every key moving is expensive when the server holds something for the key. A cache that was warm is cold, because each key has to be fetched again from where it came from, and the origin takes the whole load at once. A shard has to be copied to another server, almost in full.

Mental model. Put the servers and the keys on the same circle. A key belongs to the first server clockwise from it. A server that joins takes over only the keys between itself and the server before it, and a server that leaves hands its keys to the server after it.

That circle is consistent hashing. It was introduced by Karger and his co-authors for caching on the Web. Their paper’s abstract describes a consistent hash function as one that changes minimally as its range changes, and the paper contrasts it with standard hashing, where a small change in the set of buckets forces a total remapping. nginx’s hash with the consistent parameter uses what it calls the ketama method, which it says remaps only a few keys when a server is added or removed. Envoy’s ring hash balancer states a share: with the ring partitioned appropriately, adding or removing one host of N affects only 1/N of the requests.

A ring is built in two steps. Each server is given a number of places on the circle, found by hashing the server’s name and the number of the place. Each key is hashed to a position on the same circle, and goes to the server that owns the first place at or after that position, going round.

The number of places matters. With one place per server, the places fall unevenly, and a server can own a long arc. These are the shares of the circle that four servers own, from the model’s hash:

Places per server Smallest share Largest share
1 11.7% 39.0%
10 17.6% 33.4%
100 21.6% 27.5%
1,000 24.6% 25.3%

An even split would be 25% each. More places even it out, at the price of a bigger ring to search.

Now count what moves when a server joins, on the same 20,000 keys, going from 4 servers to 5 and from 4 to 3:

Method A server joins A server leaves
Hash mod N 79.8% 74.8%
Ring, 1 place per server 11.5% 39.0%
Ring, 100 places per server 21.5% 24.3%
Ring, 1,000 places per server 20.6% 24.6%

With 100 places each the ring moves about a fifth of the keys when a server joins, which is the share that the new server should own, and about a quarter when a server leaves, which is exactly the leaving server’s own keys. With one place per server the numbers wander, because the shares do.

Places also decide who inherits. When a server leaves, its keys go to the servers that follow its places. With one place each, the leaving server’s keys go to a single neighbour: in the model, the three servers left hold 18.6%, 11.9% and 69.6% of the keys, and one of them took nearly everything the leaver held. With 100 places each, the leaver’s keys are split among all three, which end with 34.6%, 33.1% and 32.3%.

The lab has Consistent hash as an algorithm. It hashes each session to the ring, with 100 places for each server, so a session always reaches the same server. Set Traffic to 120 and read its row. Its Mean is 117.5 ms against 34.8 ms for round robin, its 99th percentile is 709.1 ms against 150.8 ms, and its Busiest server receives 38% of the requests against 25%.

Requests reach a load balancer, which places each one on one of several servers. Each server has its own waiting line. Choose how the balancer decides, slow one server down, switch on sticky sessions, and make a server fail or be replaced, then compare what every algorithm does with the identical requests.

160 req/s
Servers
4
ClientsHealthy<1%Load balancerHealthy<1%ServersSaturated80%
ClientsHealthy<1%Load balancerHealthy<1%ServersSaturated80%

Each dot stands for many requests. The numbers show the real rate.

Servers saturated: 160 req/s against request capacity of 200 req/s.

Load balancer: the same requests under every algorithm

The balancer
1×
0%
Health checks
5 s
3
During the run
Utilisation
80%Saturated107% without the last server
99th percentile
311.8 msone shared queue: 142.4 ms
Failed requests
00% of the requests

Round robin, 160 requests per second on 4 servers, 80% utilised: half of the requests took under 48.3 ms, 95% under 201.1 ms and 99% under 311.8 ms. The busiest server received 25% of the requests, where an even split would give 25%. No request failed. One shared queue, which no balancer can run, would give a 99th percentile of 142.4 ms.

Round robin: what each server did
ServerShare of requestsBusyWaiting in line99th percentile
Server 125%81%2.1348.4 ms
Server 225%83%2.3315.8 ms
Server 325%82%1.7291.1 ms
Server 425%81%1.8246.3 ms
The same requests, under every algorithm
AlgorithmMeanMedian95th percentile99th percentileFailedBusiest server
Round robin · shown above68.3 ms48.3 ms201.1 ms311.8 ms025%
Random103.8 ms73.7 ms301.9 ms433.8 ms025%
Least connections40.6 ms30.1 ms113.8 ms172.0 ms025%
Power of two choices48.9 ms37.4 ms135.0 ms193.8 ms025%
Consistent hash305.4 ms74.5 ms987.0 ms997.4 ms2,977 (15.2%)39%
One shared queue (benchmark)36.2 ms28.2 ms99.0 ms142.4 ms0—

Times are for the requests that were answered within a second. The last row is a benchmark and not an algorithm: it needs the servers to take work when they are free.

0 ms
Metrics
ComponentStateUtilisationOffered (req/s)Served (req/s)Rejected (req/s)p50p95p99
ClientsHealthy<1%16016000 ms0 ms0 ms
Load balancerHealthy<1%16016000.03 ms0.15 ms0.23 ms
ServersSaturated80%160160027 ms95 ms138 ms
Traffic
160 req/s
Successful
160 req/s
Error rate
0%
Mean latency
35 ms

Illustrative values, not benchmarks of any real product.

Model notes

Assumptions

  • Each node is one queue, served first-come first-served by several identical slots (instances × concurrency).
  • Requests arrive at random at a steady average rate. Each needs an exponentially distributed time on a server, 20 ms on average. Every algorithm in the table gets the identical requests, so the differences between its rows come from the algorithm and not from the luck of the draw.
  • Each server works on one request at a time, and has a waiting line of its own that holds up to 100 requests. A request that has not been answered after 1 second has failed, and a server does not work on one that has already given up.
  • The balancer knows only how many requests each server holds. It answers instantly, has room for any traffic, and never fails itself.
  • Each figure comes from one run of 120 simulated seconds, after 10 seconds of warm-up, with a fixed random seed. The run can be repeated exactly, but it is one run: a difference of a few per cent between two rows is within the noise.

Simplifications

  • Above capacity there is no steady state. The model switches to a fluid approximation: the node serves at capacity, its queue grows until it reaches its limit, and further requests are rejected.
  • The diagram, and the table of components under it, come from the graph engine: they treat the servers as one pool with one shared queue and never put a request on one server. That is the benchmark in the table, not what any balancing algorithm achieves.
  • A server that fails stops answering without a word, so each request sent to it waits for its timeout. A server whose program has stopped but whose machine is up can refuse connections at once instead, and a balancer can try another server. The model shows neither the refusal nor the retry.
  • A health check here is a probe that fails only when the server is down. Real probes can also fail on a server that is merely busy, and a balancer can also learn from the requests that fail.
  • Sticky sessions: 200 sessions send the sticky share of the traffic, a few of them much more than the rest (a Zipf distribution with exponent 0.8). Each is pinned to one server at random. If its server is taken out, the session is placed again and loses what that server held. Real systems have more sessions, and other distributions.
  • Consistent hash gives each server 100 places on a ring and hashes the session, so a session always reaches the same server, whatever the sticky share. It places requests by session and not by load.
  • A deploy takes out the last server. The new version starts 30 seconds later and is ready at once. The balancer puts it back at once if it was told about the deploy, and at its next passing check if it was not. Real servers take time to start and warm up.
  • Only the first server can be slow, by the factor you set, on every request. Servers of different sizes, or that slow down only under load, are not modelled.
  • There is no network time, connection set-up, TLS or keep-alive, and no difference between layer 4 and layer 7: a request is placed on a server, and nothing is said about how.
  • The one shared queue is a benchmark, not an algorithm that a balancer can run, because it needs the servers to take work when they are free. It shows how much the choice of server costs.

Parameter values are illustrative. They are not benchmarks of any real product.

Choose Algorithm “Consistent hash” and read the table of servers. The sessions are shared out fairly evenly, 49, 46, 57 and 48 of them, and the requests are not: the servers receive 24%, 20%, 17% and 38%. The ring balances the keys. It does not know that a few keys send much more than the rest, as the lesson on sticky sessions found: the heaviest of the 200 sessions sends 10% of the traffic, and wherever it lands, that server is hot. This is the cost of placing by key and not by load, and the same cost as pinning. It is why the table’s other rows, which look at load, do better here.

What a ring is good at is staying put. Set Traffic to 100, and set The last server to “is removed, then stopped, for a deploy”. Look at the summary: 48 sessions had to move, the ones that the last server owned. All the others stayed where they were. Hash mod N would have moved 148 of the 200.

For hash mod N, each of the remaining servers receives keys that belonged to servers that did not leave, so every cache among them has lost most of what it held and has been handed keys it does not have. For the ring, each remaining server keeps everything it had and gains a share of the leaver’s keys, and the leaver’s own caches are the only ones that go. The cost of a server leaving is then about the size of what the server held, as it should be, and not the size of the whole system.

That is why consistent hashing is used for caches and for sharded stores, and for the balancers of large networks. Google’s Maglev, a software network load balancer, uses consistent hashing, together with connection tracking, to limit the harm that unexpected failures do to connections. Envoy offers two forms, a ring and Maglev, and notes that Maglev aims for minimal disruption but is not as stable as the ring when hosts change.

  • A hash turns a key into a server without a table. Hash mod N moves most keys when N changes: 80% going from 4 servers to 5, and 75% from 4 to 3.
  • A ring puts servers and keys on one circle. A key belongs to the first server place clockwise from it, so a server that joins or leaves moves only the keys next to it: about 21% when one joins and 24% when one leaves, with 100 places each.
  • More places per server even out the shares: for four servers the largest share is 39.0% with 1 place, 27.5% with 100 and 25.3% with 1,000, against an even 25%.
  • A leaving server’s keys are split among the others only if it had many places.
  • A ring balances keys, not load. In the lab the busiest server under consistent hashing receives 38% of the requests, with the sessions spread evenly, because a few sessions send much more.
  • When a server leaves the lab’s ring, 48 sessions move, against 148 for hash mod N.

Next: connection draining, and how to take a server out without cutting its requests.

Your progress

Built by GhaziAlibi.

© ShardCraft. All rights reserved.