Consistent hashing (with JAVA Implementation Version)

Source: Internet
Author: User
Https://weblogs.java.net/blog/2007/11/27/consistent-hashingPosted by tomwhite on November 27,200 7 at am PST

I 've bumped into consistent hashing a couple of times lately. The paper that introduced the idea (Consistent hashing and random trees: distributed caching protocols for relieving
Hot spots on the World Wide Web
David kargerEt al) Appeared ten years ago, although recently it seems the idea has quietly been finding its way into more and more services, from Amazon 'sdynamo
To memcached (courtesy oflast. FM). So what is consistent hashing and why shoshould you care?

The need for consistent hashing arose from limitations experienced while running collections of caching machines-Web caches, for example. If you have a collectionNCache machines then a common way of Load Balancing processing SS them is to put objectO
In cache machine numberHash (o)MoDN. This works well until you add or remove cache machines (for whatever reason), for thenNChanges and
Every object is hashed to a new location. This can be catastrophic since the originating content servers are swamped with requests from the cache machines. it's as if the cache suddenly disappeared. which it has, in a sense. (This is why you shoshould
Care-consistent hashing is needed to avoid swamping your servers !)

It wocould be nice if, when a cache machine was added, it took its fair share of objects from all the other cache machines. equally, when a cache machine was removed, it wocould be nice if its objects were shared between the remaining machines. this is exactly
What consistent hashing does-ConsistentlyMaps objects to the same cache machine, as far as is possible, at least.

The basic idea behind the consistent hashing algorithm is to hash both objects and caches using the same hash function. the reason to do this is to map the cache to an interval, which will contain a number of object hashes. if the cache is removed then its
Interval is taken over by a cache with an adjacent interval. All the other caches remain unchanged.

Demonstration

Let's look at this in more detail. The hash function Actually maps objects and caches to a number range. This shoshould be familiar to every Java programmer-hashCodeMethod on
ObjectReturns
int
, Which lies in the range-231 to 231-1. imagine mapping this range into a circle so the values wrap around. here's a picture of the circle with a number of objects (1, 2, 3, 4) and caches (a, B, c) marked
At the points that they hash to (based on a dimo-fromweb caching with consistent hashing by David karger
Et al):

To find which cache an object goes in, we move clockwise round the circle until we find a cache point. so in the dimo-above, we see object 1 and 4 belong in cache A, object 2 belongs in cache B and object 3 belongs in cache C. consider what happens if
Cache C is removed: Object 3 now belongs in cache A, and all the other object mappings are unchanged. if then another cache D is added in the position marked it will take objects 3 and 4, leaving only object 1 belonging to.

This works well, cannot the size of the intervals assigned to each cache is pretty hit and miss. since it is essential random it is possible to have a very non-uniform distribution of objects between caches. the solution to this problem is to introduce
The idea of "virtual nodes", which are replicas of cache points in the circle. So whenever we add a cache we create a number of points in the circle for it.

You can see the effect of this in the following plot which I produced by simulating storing 10,000 objects in 10 caches using the code described below. on the X-axis is the number of replicas of cache points (with a logarithmic scale ). when it is small,
We see that the distribution of objects processing SS caches is unbalanced, since the standard deviation as a percentage of the mean number of objects per cache (on the Y-axis, also logarithmic) is high. as the number of replicas increases the distribution of Objects
Becomes more balanced. This experiment shows that a figure of one or two hundred replicas achieves an acceptable balance (a standard deviation that is roughly between 5% and 10% of the mean ).

Implementation

For completeness here is a simple implementation in Java. In order for consistent hashing to be effective it is important to have a hash function thatmixes
Well. Most implementationsObject'ShashCodeDo
NotMix well-for example, they typically produce a restricted number of small integer values-so we haveHashFunctionInterface to allow a custom hash function to be used. MD5 hashes are
Recommended here.

import java.util.Collection;import java.util.SortedMap;import java.util.TreeMap;public class ConsistentHash<T> { private final HashFunction hashFunction; private final int numberOfReplicas; private final SortedMap<Integer, T> circle = new TreeMap<Integer, T>(); public ConsistentHash(HashFunction hashFunction, int numberOfReplicas,     Collection<T> nodes) {   this.hashFunction = hashFunction;   this.numberOfReplicas = numberOfReplicas;   for (T node : nodes) {     add(node);   } } public void add(T node) {   for (int i = 0; i < numberOfReplicas; i++) {     circle.put(hashFunction.hash(node.toString() + i), node);   } } public void remove(T node) {   for (int i = 0; i < numberOfReplicas; i++) {     circle.remove(hashFunction.hash(node.toString() + i));   } } public T get(Object key) {   if (circle.isEmpty()) {     return null;   }   int hash = hashFunction.hash(key);   if (!circle.containsKey(hash)) {     SortedMap<Integer, T> tailMap = circle.tailMap(hash);     hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey();   }   return circle.get(hash); }}

The circle is represented as a sorted map of integers, which represent the hash values, to caches (of TypeTHere ).
WhenConsistentHashObject is created each node is added to the Circle map a number of times (controllednumberOfReplicas). The location
Of each replica is chosen by hashing the node's name along with a numerical suffix, And the node is stored at each of these points in the map.

To find a node for an object (getMethod),Hash Value of the objectIs used to look in the map. Most of the time there will not be a node stored at this hash value (since the hash
Value space is typically much larger than the number of nodes, even with replicas), so the next node is found by looking for the first key in the tail map. if the tail map is empty then we wrap around the circle by getting the first key in the circle.

Usage

So how can you use consistent hashing? You are most likely to meet it in a library, rather than having to code it yourself. for example, as mentioned abve, memcached, a distributed memory Object Caching System, now has clients that support consistent hashing.
Last. FM's
Ketama by Richard Jones was the first, and there is now ajava implementation bydustin
Sallings (which was red my simplified demonstration implementation above ). it is interesting to note that it is only the client that needs to implement the consistent hashing algorithm-The memcached server is unchanged. other systems that employ consistent
Hashing implements dechord, which is a distributed Hash Table implementation, and Amazon's dynamo, which is a key-value store (not available outside Amazon ).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.