The use of consistent hash algorithm in memcached

Source: Internet
Author: User

I. Overview

1, our memcache client (here I see the source of Spymemcache), using a consistent hash algorithm Ketama data storage node selection. Unlike the conventional hash algorithm, we only hash the key we want to store the data, and allocate it to different node storage. The consistent hash algorithm computes the hash of the server where we want to store the data, and then confirms where each key is stored.

2, the application of the conventional hash algorithm and its drawbacks

The most common way is the way of the hash modulo. For example, the number of machines available in the cluster is n, then the data request with a key value of K is simple enough to be routed to a hash (k) mod n corresponding machine. Indeed, this structure is simple and practical. But in some of the fast-growing web systems, such solutions still have some drawbacks. With the increase of system access pressure, the cache system has to increase the corresponding speed and data carrying capacity of the cluster by increasing the machine node. Increase the machine means in accordance with the way of the hash, in the time of increasing the machine node, a large number of cache, cache data need to be re-established, or even the overall cache data migration, the moment will bring a very high system load on the DB, set the DB server downtime.

3, the design of distributed cache system, the consistency hash algorithm can help us solve what problems?

The core point of distributed cache design: When designing a distributed caching system, we need to equalize the distribution of the key, and after adding the cache server, the cache will be migrated to a minimum.

The consistency hash algorithm mentioned here Ketama the practice is: Select the specific machine node is not only rely on the key to cache the hash itself, but the machine node itself is also a hash operation.


Second, consistent hash algorithm scenario description (reproduced)

1. Hash machine node


First find the Machine node hash value (how to calculate the Machine node hash?) IP can be used as a hash parameter. Of course there are other ways), and then distribute it to a ring in the 0~2^32 (clockwise distribution). As shown in the following:

Figure A

There are machines in the cluster: A, B, C, D, E five machines, through a certain hash algorithm we distribute it to the ring as shown.


2. Access method

If there is a write cache request where the key value is K, the calculator hash value is hash (k), the hash (k) corresponds to a point in the graph –1 ring, if the point corresponding to a specific machine node is not mapped, then look clockwise until the first time to find the node with the mapped machine, The node is the target node that is determined, and if it exceeds the 2^32 still cannot find the node, hit the first machine node. For example, the hash (K) value is between A~b, then the hit machine node should be a B node (such as).


3, increase the processing of nodes

For example, –1, on the basis of the original cluster to add a machine f, the increase process is as follows:

The hash value of the computer node that maps the machine to a node in the ring, such as:

Figure II

After adding the Machine node F, the access policy does not change, still according to (2) in the manner of access, when the cache is still unavoidable, the data that cannot be hit is the hash (K) in increasing the node before the data between c~f. Although there is still a hit problem caused by the increase of the node, but compared with the traditional method of hashing, the consistency hash has reduced the data to a minimum.

Consistent hashing minimizes the redistribution of hash keys. In addition, in order to achieve a better load balancing effect, often in a small number of servers need to increase the virtual node to ensure that the server can be evenly distributed on the ring. Because of the general hash method, the map location of the server is unevenly distributed. Using the idea of a virtual node, allocate 100~200 points on the circle for each physical node (server). This can suppress uneven distribution and minimize cache redistribution when the server is increasing or decreasing. The user data is mapped on a virtual node, which means that the user data is actually stored on the actual physical server represented by the virtual node.
Here is a diagram that describes the virtual nodes that need to be added for each physical server.


Might

The x-axis represents a virtual node multiplier (scale) that needs to be scaled for each physical server, and the y-axis is the actual number of physical servers, and it can be seen that when the number of physical servers is very small, a larger virtual node is needed, and less nodes are required, as can be seen from the graph, when the physical server has 10 It is almost necessary to add 100~200 virtual nodes to each server to achieve a true load balancer.

Third, the Spymemcache source to demonstrate the virtual node application

1, the above description of the consistency hash algorithm has a potential problem is:
(1), the node hash will be unevenly distributed on the ring, so that a large number of keys in the search for nodes, there will be key hit each node probability difference is large, unable to achieve effective load balancing.
(2), if there are three nodes node1,node2,node3, distributed in the ring when the three nodes close to the key on the ring to find the node, a large number of key clockwise is always assigned to Node2, and the other two nodes are found to be very small probability.

2, the solution of this problem can be:
Improve the hash algorithm, evenly distribute each node to the ring; [citation] Use the idea of a virtual node to allocate 100~200 points for each physical node (server) on a circle. This can suppress uneven distribution and minimize cache redistribution when the server is increasing or decreasing. The user data is mapped on a virtual node, which means that the user data is actually stored on the actual physical server represented by the virtual node.

When viewing the spy Memcached client, it was found that it adopted a hash algorithm called Ketama to solve Memcached distributed problem with the idea of virtual node.

3. Source Code Description

The client uses TreeMap to store all nodes and simulates a circular logical relationship. In this loop, the nodes are sequentially related, so the TreeMap key must implement the comparator interface.
How does that node fit into this ring?

[HTML]View Plaincopyprint?
  1. protected void Setketamanodes (List<memcachednode> nodes) {
  2. TreeMap<Long, Memcachednode> newnodemap  =  New TreeMap < Long , Memcachednode >  ();
  3. int numreps= config. getnoderepetitions ();
  4. for (Memcachednode node:nodes) {
  5. Ketama does some special work with MD5 where it reuses chunks.
  6. if (hashalg = = Hashalgorithm.ketama_hash) {
  7. for (int i=0; I<numreps /4; i++) {
  8. Byte[] Digest=hashalgorithm. COMPUTEMD5 (Config.getkeyfornode (node, i));
  9. for (int h=0; h<4; h++) {
  10. Long k = ((long) (DIGEST[3+H*4]&0XFF) << )
  11. | ((long) (DIGEST[2+H*4]&0XFF) << )
  12. | ((long) (DIGEST[1+H*4]&0XFF) << 8)
  13. | (DIGEST[H*4]&0XFF);
  14. Newnodemap.put (k, node);
  15. GetLogger (). Debug ("Adding node%s in position%d", node, k);
  16. }
  17. }
  18. } else {
  19. for (int i=0; I<numreps; i++) {
  20. Newnodemap.put (Hashalg.hash (Config.getkeyfornode (node, i), node);
  21. }
  22. }
  23. }
  24. Assert newnodemap.size () = = Numreps * Nodes.size ();
  25. Ketamanodes  =  Newnodemap  ;
 protected void Setketamanodes (list<memcachednode> nodes) {Treemap<long, memcachednode> newnodemap = new Treemap<long, memcachednode> (); int numreps= Config.getnoderepetitions (); for (Memcachednode node:nodes) {//Ketama does some special work with MD5 where it reuses chu Nks.if (HashAlg = = Hashalgorithm.ketama_hash) {for (int i=0; i<numreps/4; i++) {byte[] digest= HASHALGORITHM.COMPUTEMD5 (Config.getkeyfornode (node, i)); for (int h=0;h<4;h++) {Long k = ((Long) (digest[3+h*4]& 0xFF) << 24) | ((long) (DIGEST[2+H*4]&0XFF) << 16) | ((long) (DIGEST[1+H*4]&0XFF) << 8) | (Digest[h*4]&0xff); Newnodemap.put (k, node); GetLogger (). Debug ("Adding node%s in position%d", node, k);}} else {for (int i=0; i<numreps; i++) {newnodemap.put (Hashalg.hash (Config.getkeyfornode (node, i), node);}}} Assert newnodemap.size () = = Numreps * Nodes.size (); ketamanodes = Newnodemap; 



The above process can be summarized as follows: Four virtual nodes for a group, the Getkeyfornode method to get this set of virtual node NAME,MD5 encoding, each virtual junction corresponding to Md5 code 16 bytes of 4, forming a Long value, As the only key in this virtual node in the ring. The 10th row K Why is a long type? This is because the long type implements the comparator interface.

After processing the distribution of the formal node on the ring, you can start the game where key is looking for nodes on the ring.
For each key, you have to complete the above steps: Calculate the MD5, according to the MD5 byte array, through the kemata hash algorithm to get the position of key in this ring.

[HTML]View Plaincopyprint?
  1. Memcachednode Getnodeforkey (long hash) {
  2. Final Memcachednode RV;
  3. if (!ketamanodes.containskey (hash)) {
  4. Java 1.6 Adds a Ceilingkey method, but I ' m still stuck in 1.5
  5. In a lot of places, so I ' m doing this myself.
  6. SortedMap<Long, Memcachednode> tailmap= Getketamanodes  (). Tailmap (hash);
  7. if (Tailmap.isempty ()) {
  8. Hash = Getketamanodes  (). Firstkey ();
  9. } else {
  10. Hash = Tailmap  . Firstkey ();
  11. }
  12. }
  13. RV = Getketamanodes  (). get (hash);
  14. return RV;
  15. }
Memcachednode Getnodeforkey (long hash) {final Memcachednode rv;if (!ketamanodes.containskey (hash)) {//Java 1.6 adds a CEI Lingkey method, but I ' m still stuck in 1.5//in a lot of places, so I ' m doing this myself. Sortedmap<long, Memcachednode> tailmap=getketamanodes (). Tailmap (hash); if (Tailmap.isempty ()) {hash= Getketamanodes (). Firstkey ();} else {Hash=tailmap.firstkey ();}} Rv=getketamanodes (). get (hash); return RV;}


The implementation of the above code is on the ring clockwise to find, did not find the first one, and then know the corresponding physical node.

Four, the application scenario analysis

1, Memcache Add method: Through the consistency hash algorithm to confirm the current client corresponding to the Cacheserver hash value and to store data key hash to correspond, confirm cacheserver, get connection for data storage

2, Memcache get method: Through the consistent hash algorithm to confirm the current client corresponding to the Cacheserver hash value and to extract the data hash value, and then confirm the stored cacheserver, get connection for data extraction

V. Summary

1, the consistent hash algorithm is only to help us reduce the number of machines in the cache cluster increase or decrease, the cache data can be rebuilt at least. As long as the number of servers in the cache cluster changes, data hit issues inevitably occur

2, for the data distribution balance problem, through the idea of virtual node to achieve a balanced distribution. Of course, the fewer cache server nodes we need, the more virtual nodes are needed to balance the load.

3, our cache client does not maintain a map to record where each key is stored, all through the hash of the key and Cacheserver (perhaps the IP can be used as a parameter) hash to calculate the current key should be stored on which node.

4. When our cache node crashes. We must lose some of the cache data and do a new consistency match calculation based on the live cache server and key. It is possible to rebuild some data that is not lost ...

5, as to the normal arrival data storage node, how to find the key corresponding data, that is the cache server itself implementation of the internal algorithm, not described here.


This is simply a presentation of how the data is stored and how it is extracted.

Reprint: http://blog.csdn.net/kongqz/article/details/6695417

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

The use of consistent hash algorithm in memcached

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.