← sources

Understanding Consistent Hashing Correct Me If I'm Wrong

source: reddit (reddit:webdev)published 2026-06-06 07:52ingested 2026-06-06 08:28

retained text

<!-- SC_OFF --><div class="md"><p>Why we need it ?</p> <p>Suppose we have multiple databases and want to distribute data among them.</p> <p>Instead of searching every database when we need some data, we use a rule that tells us exactly which database should store a particular record.</p> <p>Method 1: Modulo Based Distribution</p> <p>Imagine we have 3 databases DB-A , DB-B , DB-C Each record has a unique ID. Now We decide the database using ID % Number_of_Databases for e.g. 16 % 3 = 1 So record 16 goes to database index 1 (DB-B). This works fine until we add another database. The same record becomes 16 % 4 = 0 Now record 16 should be stored in DB-A instead of DB-B. The problem is that when the number of databases changes, a huge amount of data gets remapped to different databases. This can cause Massive data migration , Increased CPU and network usage</p> <p>Method 2: Consistent Hashing</p> <p>Instead of using modulo, imagine a circular ring numbered from 0 to 99. We place our databases on the ring: </p> <p>DB-A -&gt; 0<br /> DB-B -&gt; 25<br /> DB-C -&gt; 50<br /> DB-D -&gt; 75</p> <p>Now we pass the data unique id through a hash function and it will give the location of that data on the ring for e.g. User ID = 12345 hash(12345) = 42 now we get the position we Move clockwise. Store the data in the first database you encounter This means we store the 42 position data at the DB-C</p> <p>Now What Happens When We Add a New Database?</p> <p>Suppose we add DB-E -&gt; 37 now only the data between 26 to 37 needs to move from DB-C to DB-E. The rest of the data stays exactly where it was. This is the biggest advantage of Consistent Hashing much less data migration , easier scaling , lower operational cost</p> <p>Now there is one more thing in this method which is Virtual Nodes</p> <p>One issue is that some databases may receive much more traffic than others. To balance the load, the same database can appear multiple times on the ring.</p> <p>DB-A -&gt; 0, 40, 80<br /> DB-B -&gt; 25, 65<br /> DB-C -&gt; 13, 50, 90<br /> DB-D -&gt; 75</p> <p>These extra positions are called virtual nodes.</p> <p>Any corrections? Is there anything else I should know about this topic? Please let me know.</p> </div><!-- SC_ON --> &#32; submitted by &#32; <a href="https://www.reddit.com/user/No-Resolution-4054"> /u/No-Resolution-4054 </a> <br /> <span><a href="https://www.reddit.com/r/webdev/comments/1tyb0ue/understanding_consistent_hashing_correct_me_if_im/">[link]</a></span> &#32; <span><a href="https://www.reddit.com/r/webdev/comments/1tyb0ue/understanding_consistent_hashing_correct_me_if_im/">[comments]</a></span>

document fetched 2026-06-06 08:28