Translate

Consistent Hashing

Updated On : 20-10-2025

Consistent Hashing क्या है? — System Design में इसकी ज़रूरत और आसान समझ (हिंदी)

मान लीजिए आपके पास एक cache cluster है और आपके पास 10,000 users के requests हैं। अगर आपने simple mod-based hashing लगाया है और एक नया server जोड़ना पड़ा — तो बहुत सारा डेटा relocate होगा। क्या होगा अगर कुछ ऐसा हो जो सिर्फ़ छोटा सा portion ही move करे? यही काम करता है Consistent Hashing — जो scalable systems में data redistribution की problem को smartly solve करता है।


Consistent Hashing का परिचय

Consistent Hashing एक hashing technique है जो distributed systems में data placement और re-balancing की complexity कम करती है। यह खासकर तब काम आती है जब nodes (servers) dynamically जुड़ते या हटते हैं—इस स्थिति में consistent hashing सुनिश्चित करता है कि केवल न्यूनतम डेटा ही relocate हो।

Traditional Hashing की समस्या (Why simple hashing fails)

मानक hashing strategy: key → hash(key) → hash % N, जहाँ N = number of servers। यह सरल है, पर इसका बड़ा drawback है—जब N बदलता है (node add/remove), तब लगभग सभी keys नई machines पर चलने लगते हैं। इसे "re-hashing problem" कहते हैं।

इसके परिणामस्वरूप बहुत सारा data network पर move होगा, जिससे downtime और high latency आ सकती है। इसलिए हमें ऐसी approach चाहिए जो node-churn की स्थिति में सिर्फ़ कुछ ही keys को relocate करे।

🔁 Rehashing Comparison — Mod Hashing vs Consistent Hashing
Scenario Mod-Hashing (Classic) Consistent Hashing
Add a new server node 100% keys rehashed 1 / N keys rehashed (very small)
Remove a server node 100% keys rehashed again Only keys from that node redistributed
Average rehashing percentage 60–100% (depends on server count) ~5–10% typical

Consistent Hashing कैसे काम करता है (Ring diagram)

Consistent Hashing एक logical circle या ring बनाता है।

  1. Hash function (जैसे SHA-1) का output range [0, 2^m - 1] माना जाता है और इसे circular space पर map किया जाता है।
  2. हर node (server) के लिए hash(node_id) compute कर के ring पर उसका position रखा जाता है।
  3. हर key के लिए hash(key) compute किया जाता है और clockwise direction में first node जिसे key के hash के बाद आता है, वही key का owner माना जाता है।

जब एक नया node जोड़ते हैं, तो केवल उस node के clockwise range में आती हुई keys ही नई node पर जाएँगी—बाकी keys unaffected रहेंगी। इसी वजह से data movement कम होती है।

Interactive: Consistent Hashing Ring — Add Node & See Moved Keys

यह छोटा demo दिखाता है कि कैसे consistent hashing में नयी node जोड़ने पर केवल कुछ keys ही relocate होते हैं — न कि सभी। नीचे Add Node दबाकर experiment करके देखिए।

Nodes: 0
Click "Add Node" to insert a node on the ring

How it maps (simplified): each key is placed at a random point on the ring. A key belongs to the first node found when traversing clockwise from the key position. When a node is added, only keys that map to that new node (or affected neighbor) move — not every key.

Legend: Node Stable Key Moved Key

Virtual Nodes (VNode) और Load Balancing

एक practical enhancement है Virtual Nodes (VNodes) — हर physical server को कई virtual nodes के रूप में ring पर multiple positions दी जाती हैं।

फायदा:

  • Load distribution अधिक uniform होता है।
  • Cluster में node heterogeneity (different capacity) handle करना आसान होता है—आप ज्यादा capacity वाले physical node को अधिक VNodes दे सकते हैं।
  • जब node fail हो, उसकी responsibilities कई VNodes पर विभाजित होने से impact कम होता है।

Example: अगर 3 physical nodes हैं और हर node को 100 virtual nodes दिए गए हैं, तो total 300 positions होंगी—जिससे hash collisions और hot-spots कम होते हैं।


// Step 1️⃣ — Create physical nodes
nodes = ["NodeA", "NodeB", "NodeC"]

// Step 2️⃣ — Create multiple virtual nodes per physical node
VNODE_COUNT = 3
vNodes = []
for node in nodes:
    for i in range(VNODE_COUNT):
        hashValue = hash(node + "#" + i)
        vNodes.append((hashValue, node))

// Step 3️⃣ — Sort the ring by hash value (0 → 2³²)
vNodes.sortBy(hashValue)

// Step 4️⃣ — Function to find owner node for a given key
function getNodeForKey(key):
    keyHash = hash(key)
    for (vHash, node) in vNodes:
        if keyHash <= vHash:
            return node
    return vNodes[0].node  // wrap-around to start

// Step 5️⃣ — Example mappings
getNodeForKey("user_101") → "NodeB"
getNodeForKey("order_55") → "NodeA"
getNodeForKey("txn_700")  → "NodeC"

💡 Explanation: Virtual Nodes evenly spread load across the hash space, so adding/removing a server moves only a few key ranges — improving scalability and balance.

Consistent Hashing के फायदे (Advantages)

  • Minimal re-distribution: Node add/remove पर केवल O(k/N) keys move करते हैं—बहुत कम data migration।
  • Scalability: Large-scale distributed caches और databases में आसानी से scale कर सकते हैं।
  • Fault Tolerance: Node failure पर keys automatic नज़दीकी nodes पर shift हो जाती हैं।
  • Flexible Capacity Management: VNodes के जरिये अलग-अलग सर्वरों को अलग capacity assign कर सकते हैं।

नोट: Consistent Hashing अकेला पूरा सिस्टम नहीं बनाता—यह hashing layer है जो sharding और load balancing के साथ मिलकर काम करती है।

Real-world Use Cases — कहाँ Consistent Hashing उपयोगी है?

कुछ प्रमुख implementations जहाँ Consistent Hashing का इस्तेमाल होता है:

Cassandra

Cassandra distributed database में partitioner के रूप में Consistent Hashing का प्रयोग होता है—यह node additions/removals के साथ minimal data movement सुनिश्चित करता है।

Redis Cluster

Redis Cluster में keyspace को slots में बाँटा जाता है; हालांकि कुछ Redis setups consistent hashing inspired approaches अपनाते हैं, खासकर custom client-side sharding में।

Amazon Dynamo (historical)

Dynamo paper में भी consistent hashing और virtual nodes का concept central है—यही ideas modern NoSQL stores को प्रभावित करते हैं।

📘 Case Study: How Cassandra Rebalances When a Node is Added

मान लीजिए आपके पास Cassandra क्लस्टर में 3 nodes हैं — Node A, Node B और Node C। हर node hash ring का एक हिस्सा own करता है। अब जब आप Node D add करते हैं, तो Cassandra को कुछ data ranges नए node में move करनी होती हैं ताकि load balance रहे।

A B C D

जब Node D जुड़ता है, तो Cassandra ring को re-partition करती है — कुछ hash ranges जो पहले Node B और Node C के पास थीं, अब Node D को मिलती हैं। उदाहरण के लिए:

Hash Range Old Owner New Owner (After Node D)
0x00 - 0x3F Node A Node A
0x40 - 0x7F Node B Node D
0x80 - 0xBF Node C Node D
0xC0 - 0xFF Node A Node A

🔄 इस तरह Cassandra बिना पूरे cluster को rehash किए केवल उन data ranges को move करती है जो नए node के हिस्से में आती हैं। इसका मतलब — कम downtime, बेहतर scalability और smooth load balancing

System Design में कब और क्यों Consistent Hashing चाहिए?

जब आपका system इन समस्याओं से जूझ रहा हो:

  • Dynamic scaling (nodes frequently added/removed)
  • Huge keyspace और बहुत से read/write operations
  • Low-latency cache (e.g., distributed cache layer)
  • Need for even load distribution और fault tolerance

System design interview में अगर आपको distributed cache या sharded database design पूछा जाए, तो consistently hashing use-case और VNode optimization बताना high-impact answer होगा।

1️⃣ URL Shortener Design (Bitly-like)

Goal: Long URLs → Short codes with fast redirection & analytics.

🔹 Step-by-Step Approach

  • Use a Hash Function or Base62 encoding for unique short IDs.
  • Store mapping in a NoSQL DB (like DynamoDB or Cassandra).
  • Use Cache (Redis) for frequent redirects.
  • Add Write API → Generate + Store Short URL.
  • Add Read API → Resolve short code → long URL.

🧠 Scaling:

Sharding by short-code prefix; CDN for redirect latency; Kafka for analytics stream.

Client API Server DB/Cache

2️⃣ Real-Time Chat System

Goal: Handle millions of concurrent users with reliable message delivery.

  • Frontend: WebSocket connection via gateway.
  • Backend: Message Queue (Kafka/RabbitMQ) for buffering.
  • Database: Cassandra for storing messages (partition by user_id).
  • Delivery: Pub/Sub push model.

Scalability: Stateless chat servers, partition queues by chat_id, use Redis for presence tracking.

Client Chat Server Kafka Queue

3️⃣ Notification System Design

Deliver millions of push, email & SMS notifications reliably.

  • Producer: Event Source (e.g., Order Confirmed)
  • Queue: Kafka or SQS for decoupling.
  • Consumer: Worker → Template → Channel (FCM/SES/SMS)

Key idea: Retry with exponential backoff + Dead Letter Queue.

4️⃣ File Storage System Design

Support uploads, downloads, versioning & metadata management.

  • Frontend: Upload via signed URL (S3/GCS).
  • Metadata: RDS or MongoDB.
  • Chunks: Split large files into 5–10 MB pieces.
  • Scaling: CDN + background compression.

5️⃣ Rate Limiter Design

Goal: Limit API requests per user/IP for fair usage.

  • Store token counts in Redis using Sliding Window Algorithm.
  • Use Lua script to atomically update counters.
  • Apply globally using API Gateway.

Formula:
allowed = limit × (elapsed_time / window)

Interview Tips — Common Questions और Short Answers

1) Consistent hashing को explain कीजिए।

Short answer: Consistent hashing एक hashing technique है जो keys को ring पर map करती है और node add/remove पर minimal keys ही relocate करती है।

2) Virtual nodes का क्या role है?

Short answer: VNodes physical node पर multiple positions बनाकर load uniform करता है और heterogenous capacity handle करता है।

3) अगर node fail हो जाए तो keys कैसे recover होंगी?

Short answer: Replication के साथ—आप प्रत्येक key की copies अलग-अलग nodes पर रखें; primary node fail पर replica serve कर लेता है।

Tip: interview में diagram के साथ clock-wise lookup और short complexity notes (O(1) average for lookup with appropriate data structures) दिखाएँ।

👉 Structure every answer like: 

(1) Clarify Requirements → (2) Estimate Scale → (3) Design Components → (4) Handle Scalability → (5) Fault Tolerance → (6) Trade-offs.

FAQ — अक्सर पूछे जाने प्रश्न

Q1: Consistent Hashing और Modulo Hashing में मुख्य अंतर क्या है?

A: Modulo hashing में N change होने पर लगभग सभी keys का mapping बदलता है; जबकि Consistent Hashing में केवल O(1/N) भाग keys move होते हैं।

Q2: क्या Consistent Hashing से hot-spots पूरी तरह हट जाते हैं?

A: नहीं—पर VNodes और dobre hashing strategies से hotspots काफी कम किए जा सकते हैं।

Q3: क्या कोई standard hash function चाहिए?

A: बदलाव के लिए robust hash (e.g., SHA-1 या MurmurHash) use करते हैं—speed और distribution दोनों ध्यान में रखें।

Q4: Consistent Hashing के साथ किन mechanisms की ज़रूरत होती है?

A: Replication, failure detection, and rebalancing orchestrators की आवश्यकता होती है—consistent hashing केवल placement strategy है।

Q5: क्या यह technique केवल key-value stores के लिए है?

A: नहीं—यह distributed caches, partitioned message queues और अन्य sharded systems में भी उपयोगी है।

📌 Further reading

🧑‍💻 About the Author

Anurag Rai एक टेक ब्लॉगर और नेटवर्किंग विशेषज्ञ हैं जो Accounting, AI, Game, इंटरनेट सुरक्षा और डिजिटल तकनीक पर गहराई से लिखते हैं।

Post a Comment

Blogger

Your Comment Will be Show after Approval , Thanks

Ads

 
↑ Top