← Blog · System Design

Understanding Consistent Hashing: A Beginner's Guide

If you've been exploring distributed systems, caching, or load balancing, you've probably heard the term "consistent hashing" thrown around. It might sound intimidating, but I promise it's not as complex as it seems. Let me break it down in a way that makes sense.

The Problem We're Solving

Imagine you're building a system where you need to distribute data across multiple servers. You have 1 million users, and you want to spread them across 3 servers evenly. You might think: "Easy! I'll just use a simple hash function."

You could do something like this:

server_id = hash(user_id) % 3

This means if a user's ID hashes to 42, they go to server 42 % 3 = 0. If it hashes to 75, they go to server 75 % 3 = 0. If it hashes to 100, they go to server 100 % 3 = 1.

This works great! Your users are distributed across all three servers. But here's where things get messy.

What happens when you add a fourth server?

Now you're using hash(user_id) % 4 instead of % 3.

Do you see the problem? Almost every single user will get a different server assignment! If user 42 previously went to server 0 (42 % 3 = 0), now they might go to server 2 (42 % 4 = 2). You'd need to move massive amounts of data, and your system would grind to a halt.

This is called the "rehashing problem," and it's exactly what consistent hashing solves.

Enter Consistent Hashing

Consistent hashing is a technique that ensures when you add or remove servers, most of your data stays where it is. Only a small fraction of data needs to be moved. Think of it as a more intelligent way to distribute data.

The Basic Concept: The Hash Ring

Imagine arranging all possible hash values in a circle. Let's say hash values range from 0 to 360 (like degrees on a compass). The boundaries connect, so after 360 comes 0 again.

Now, place your servers around this circle at specific positions. For example:

  • Server A at position 0°
  • Server B at position 120°
  • Server C at position 240°

When you want to store a user, you:

  1. Hash their ID to get a position on the ring (e.g., 75°)
  2. Find the nearest server going clockwise
  3. Store the user on that server

So if a user hashes to 75°, you go clockwise and find Server B at 120°. That's where they live.

Here's a simple ASCII visualization:

          Server A (0°)
               |
        90°    |    30°
      /        |        \
   180° -------|------- 0°
      \        |        /
       270°    |    330°
               |
         Server C (240°)  Server B (120°)

The Magic: What Happens When You Scale

Now, what if you add Server D at position 180°?

With regular hashing, almost every user gets reassigned. But with consistent hashing, users only move to a different server if they land between an old server and the new server.

For example, if a user hashes to 150°, they previously went to Server B at 120° (clockwise from 150°). But now with Server D at 180°, they still go to Server B at 120°—nothing changes!

Only users in the range from 120° to 180° (between Server B and Server D) need to move. That's a fraction of your data instead of most of it.

This is the beauty of consistent hashing: adding or removing a server only affects a small portion of your data.

How It Works in Code (Simplified)

Here's a simplified Python example to show the basic idea:

import hashlib

class ConsistentHash:
    def __init__(self, servers=None):
        self.ring = {}
        self.sorted_keys = []
        if servers:
            for server in servers:
                self.add_server(server)
    
    def add_server(self, server):
        # Hash the server name to get its position on the ring
        hash_value = int(hashlib.md5(server.encode()).hexdigest(), 16)
        self.ring[hash_value] = server
        self.sorted_keys.append(hash_value)
        self.sorted_keys.sort()
    
    def remove_server(self, server):
        hash_value = int(hashlib.md5(server.encode()).hexdigest(), 16)
        del self.ring[hash_value]
        self.sorted_keys.remove(hash_value)
    
    def get_server(self, key):
        # Hash the key (user ID) to find its position
        hash_value = int(hashlib.md5(key.encode()).hexdigest(), 16)
        
        # Find the next server position going clockwise
        for server_hash in self.sorted_keys:
            if hash_value <= server_hash:
                return self.ring[server_hash]
        
        # If no server found going forward, wrap around to the first server
        return self.ring[self.sorted_keys[0]]

# Usage
ch = ConsistentHash(['server_a', 'server_b', 'server_c'])
print(ch.get_server('user_1'))  # Where does user_1 live?
print(ch.get_server('user_2'))  # Where does user_2 live?

ch.add_server('server_d')  # Add a new server
print(ch.get_server('user_1'))  # Still on the same server!

Real-World Applications

Consistent hashing is used everywhere in modern systems:

Caching layers: When you have multiple cache servers (like Redis or Memcached), you use consistent hashing to decide which server stores each cached value. When you scale your cache horizontally, you don't lose most of your cached data.

Load balancing: Distributing user requests across multiple backend servers. You want the same user to consistently hit the same server (for session affinity), but you also want to add or remove servers without rerouting everyone.

Database sharding: Splitting a large database across multiple machines. Each piece of data goes to a shard based on consistent hashing, making it easy to add more shards as you grow.

Distributed systems: Projects like Apache Cassandra and consistent key-value stores rely on consistent hashing to determine which node stores which data.

The Catch: Virtual Nodes

There's one issue with basic consistent hashing: if your servers are unevenly distributed around the ring, some servers might be responsible for way more data than others. Imagine Server A at 0°, Server B at 1°, and Server C at 180°. Server B would be responsible for almost nothing!

The solution is virtual nodes (also called replicas). Instead of placing each server once on the ring, you place it multiple times (say, 100 times). The physical server now manages 100 virtual positions on the ring, which smooths out the distribution and makes it more balanced.

class ConsistentHashWithVirtualNodes:
    def __init__(self, servers=None, virtual_nodes=3):
        self.ring = {}
        self.sorted_keys = []
        self.virtual_nodes = virtual_nodes
        if servers:
            for server in servers:
                self.add_server(server)
    
    def add_server(self, server):
        # Add multiple virtual nodes for this server
        for i in range(self.virtual_nodes):
            virtual_key = f"{server}:{i}"
            hash_value = int(hashlib.md5(virtual_key.encode()).hexdigest(), 16)
            self.ring[hash_value] = server
            self.sorted_keys.append(hash_value)
        self.sorted_keys.sort()
    
    def get_server(self, key):
        hash_value = int(hashlib.md5(key.encode()).hexdigest(), 16)
        
        for server_hash in self.sorted_keys:
            if hash_value <= server_hash:
                return self.ring[server_hash]
        
        return self.ring[self.sorted_keys[0]]

Key Takeaways

  1. Consistent hashing solves the rehashing problem. When you add or remove servers, only a fraction of data needs to move, not everything.

  2. It uses a hash ring. Servers and data are mapped to positions on a circle, and data goes to the nearest server clockwise.

  3. It's scalable. You can add or remove servers with minimal disruption to your system.

  4. Virtual nodes improve distribution. They prevent uneven load when servers aren't perfectly spaced.

  5. It's everywhere. Cache systems, load balancers, databases, and distributed systems all use consistent hashing.

Next Steps

As you get more comfortable with consistent hashing, explore how real systems implement it. Check out projects like Redis Cluster, Memcached with consistent hashing clients, or distributed databases like Cassandra. Understanding consistent hashing will help you design more scalable systems and appreciate how modern infrastructure handles massive scale.

Happy coding!

consistent-hashingdistributed-systemssystem-designbackend-development

Got a slow dashboard or messy data?Punya dashboard lambat atau data berantakan?

Let's talkAyo ngobrol