<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Zaid on Medium]]></title>
        <description><![CDATA[Stories by Zaid on Medium]]></description>
        <link>https://medium.com/@predcodes695?source=rss-aa603a447d2a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*b3BBjR0uc8a-8ObW</url>
            <title>Stories by Zaid on Medium</title>
            <link>https://medium.com/@predcodes695?source=rss-aa603a447d2a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 21:04:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@predcodes695/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Secret Behind Netflix, Cassandra, and CDNs: Consistent Hashing Explained]]></title>
            <link>https://medium.com/@predcodes695/the-secret-behind-netflix-cassandra-and-cdns-consistent-hashing-explained-f1bd6ec63489?source=rss-aa603a447d2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1bd6ec63489</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Zaid]]></dc:creator>
            <pubDate>Fri, 03 Oct 2025 13:05:34 GMT</pubDate>
            <atom:updated>2025-10-03T18:33:24.225Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How one elegant algorithm powers the world’s largest distributed systems</em></p><p>Imagine you’re <strong>Netflix</strong> or <strong>Hotstar</strong>. You have millions of users watching content simultaneously, petabytes of data distributed across thousands of servers worldwide, and you need to add new servers every day to handle growth. Here’s the nightmare scenario:</p><p><strong>Traditional approach</strong>: Add one new server → 99% of your cached data becomes invalid → millions of cache misses → origin servers overload → system crashes → users see the dreaded spinning wheel.</p><p><strong>With consistent hashing</strong>: Add one new server → only 1% of data moves → system barely notices → users keep binge-watching.</p><p>This is the magic of consistent hashing, and by the end of this article, you’ll understand exactly how it works and implement it yourself in Go.</p><h3>The Problem: Why Simple Hashing Breaks at Scale</h3><p>Let’s start with what seems like a reasonable approach. You have 3 cache servers and want to distribute user sessions:</p><pre>// Naive approach<br>serverIndex := hash(userID) % 3</pre><p>Works beautifully! user:12345 always goes to the same server. Fast, deterministic, simple.</p><p>But then your startup takes off. You add a 4th server:</p><pre>serverIndex := hash(userID) % 4  // Changed from 3 to 4</pre><p><strong>Disaster</strong>: Almost <strong>EVERY</strong> user’s hash changes. Here’s why:</p><pre>Before (N=3), Server count is 3:<br>- user:12345 → hash=97 → 97 % 3 = 1 → Server 1<br>- user:67890 → hash=54 → 54 % 3 = 0 → Server 0</pre><pre>After (N=4), Server added, count becomes 4:<br>- user:12345 → hash=97 → 97 % 4 = 1 → Server 1 ✓ (lucky!)<br>- user:67890 → hash=54 → 54 % 4 = 2 → Server 2 ✗ (moved!)</pre><p><strong>The brutal math</strong>: When you change from N to (N+1) servers, approximately <strong>(N)/(N+1)</strong> of your keys remap. With 100 servers, that’s 99% of your data!</p><h3>Real-World Consequences</h3><ul><li><strong>Cache invalidation</strong>: Billions of cached items suddenly invalid</li><li><strong>Origin server overload</strong>: Must re-fetch everything from source</li><li><strong>Cascading failures</strong>: Overloaded servers fail, making things worse</li><li><strong>Network saturation</strong>: Terabytes of data moving between servers</li><li><strong>Cost</strong>: AWS charges for data transfer — this gets expensive fast</li></ul><h3>Enters Consistent Hashing: The Elegant Solution</h3><p>Consistent hashing was invented at MIT in 1997 by <strong>David Karger</strong> and colleagues.</p><p>The core insight is beautiful: <strong>What if we stopped using the modulo operation entirely?</strong></p><h3>The Ring: A New Mental Model</h3><p>Instead of thinking about servers as slots 0, 1, 2, 3…, imagine a circle (a “ring”) representing all possible hash values from 0 to 2³²-1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*DFkWL9Ulnk4yBrcWVEo24A.png" /></figure><p><strong>How it works:</strong></p><p>1. Both <strong>servers</strong> and <strong>keys</strong> are hashed to positions on the ring (0 to 2³² — 1).</p><p>2. To find which server handles a key: start at the key’s position and walk <strong>clockwise</strong>/<strong>anticlockwise</strong> until you hit a server. Here we go clockwise for depiction.</p><p>3. Example: <strong><em>key k1</em></strong> at position 300M → walks clockwise → finds <strong>Server A</strong> at 500M</p><p>4. If you reach the end (2³²-1), the ring <strong>wraps around</strong> to position 0.</p><h3>The reason of server’s identifiers being hashed:</h3><p>The answer lies itself in the core problem: <strong><em>Distribution</em></strong>!</p><p>Imagine you have a ring from 0 to 2³²-1 (that’s 4.3 billion positions).</p><p><strong>Scenario 1: Don’t hash servers, just place them sequentially.</strong></p><blockquote>Server A → position 0<br>Server B → position 1 <br>Server C → position 2</blockquote><p><strong>Now hash your keys:</strong></p><blockquote>hash(“user:12345”) = 923,847<br>hash(“user:67890”) = 2,394,823,847<br>hash(“cart:palm”) = 45,293</blockquote><p><strong>The problem:</strong> Your servers are clustered at positions 0, 1, 2 (the very beginning of the ring), but your keys are scattered across 4.3 BILLION positions.</p><p>How do you map key at position 923,847 to a server at position 0, 1, or 2? You’d need to use modulo:</p><blockquote>923,847 % 3 = server 0</blockquote><p><strong>But wait</strong> — this is exactly the problem consistent hashing was trying to AVOID! We’re back to modulo hashing, which means adding/removing a server remaps 99% of keys. Therefore, we hash servers. It fixes everything related to this.</p><p>By hashing servers, we distribute them across the <strong>SAME</strong> space as the keys:</p><blockquote>hash(“server-a.example.com”) = 500,000,000 (position 500M)<br>hash(“server-b.example.com”) = 1,900,000,000 (position 1.9B)<br>hash(“server-c.example.com”) = 3,800,000,000 (position 3.8B)</blockquote><p>Now servers are spread throughout the 0 to 4.3B space, just like keys.</p><h3>The Beautiful Part: Adding a Server</h3><p>Watch what happens when we add Server D:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*xrBDkjvIhyV7EKkAj3iSAw.png" /></figure><p>Only keys between Server A and Server D need to move (from the old owner, Server B, to the new server, Server D). Everything else stays put!</p><p><strong>Mathematical guarantee</strong>: Adding the Nth server moves only <strong>~1/N</strong> of keys. Add server #100? Only ~1% of keys relocate. This is <em>optimal</em> — you can’t do better than this.</p><h3>The Virtual Nodes Optimization</h3><p>Basic consistent hashing has a problem: random positioning creates uneven distribution. Some servers might get huge ring segments, others tiny ones.</p><h3>The Problem Visualized</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*H7H-oNiUjYNNM5bAArxqUQ.png" /></figure><p>In this scenario, the least load is handled by the server A, then a little bit more load is handled by server B. But the major most chunk is just left for server C, thus overburdening the server, which can lead to failures.</p><h3>The Solution: Virtual Nodes (v-nodes)</h3><p>Instead of placing each physical server once, place it MANY times with different identities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tnYPGtuAa5A4-dE53Vj6nw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DGVqUdK4JjPPhFf-v7yKOQ.png" /></figure><p>Now Server A appears as:</p><ul><li>server-a#0 → position 392,847</li><li>server-a#1 → position 2,847,392</li><li>server-a#2 → position 1,493,829</li><li>… (150 times total)</li></ul><p><strong><em>Result: With 150 random samples per server, distribution averages out to within ±5–10% of perfect balance.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*E-F9P_sCd1ZFTvAMNfrqLQ.png" /><figcaption>A clearer visual of virtual nodes depicting database servers.</figcaption></figure><h3>How Virtual Nodes Achieve Balance</h3><p><strong>The Law of Large Numbers:</strong> Instead of one random position per server (which can be unlucky), each server gets 150 random positions. These 150 samples average out to create uniform distribution.</p><p><strong>The Result:</strong> With 450 virtual nodes thoroughly mixed around the ring (150 per server), each physical server ends up owning approximately 33.3% of the key space. The variance is typically within ±5%, compared to the massive 86% — 88% imbalance without virtual nodes.</p><p><strong>Key Takeaway:</strong><br> <strong><em>More virtual nodes = better distribution.</em></strong></p><p>Production systems typically use <strong>150–256 vnodes</strong> per server for optimal balance between distribution quality and memory overhead.</p><h3>Bonus: Heterogeneous Hardware</h3><p>More powerful servers? Give them more virtual nodes:</p><pre>// Server A: 2x capacity → 300 virtual nodes<br>// Server B: 1x capacity → 150 virtual nodes<br>// Server C: 1x capacity → 150 virtual nodes</pre><pre>// Result: Server A handles ~2x the load</pre><p>Automatic load balancing based on capacity!</p><h3>Case Study 1: Apache Cassandra</h3><p><strong><em>Cassandra is a distributed No-SQL database that uses consistent hashing as its core partitioning strategy.</em></strong></p><h3>Architecture Overview:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZjUKtSCGII-QzN7HBPV_eA.png" /></figure><h3>Key innovations in the architecture:</h3><h3><strong>1. Coordinator Pattern</strong></h3><p>Any node can receive a request and act as the coordinator. The coordinator:</p><ul><li>Hashes the partition key to find target nodes</li><li>Forwards the request to replicas</li><li>Aggregates responses</li><li>Returns result to client</li></ul><h3><strong>2. Virtual Nodes (Since v1.2)</strong></h3><ul><li>Each physical node owns 256 token ranges (configurable)</li><li>Automatic token assignment — no manual configuration</li><li>Adding/removing nodes is seamless</li><li>Load automatically rebalances across cluster</li></ul><h3><strong>3.</strong> Hinted Hand-off</h3><p>When a replica node is temporarily unavailable:</p><ul><li>Coordinator stores a “hint” locally</li><li>Once node recovers, hints are replayed</li><li>Ensures eventual consistency without complex recovery</li></ul><p><strong>Why This Matters</strong>:</p><ul><li>Linear scalability: Add nodes, increase throughput proportionally</li><li>No single point of failure: Any node can coordinate</li><li>Even distribution: Virtual nodes prevent hotspots</li><li>Automatic rebalancing: No manual intervention needed</li></ul><h3>Real Numbers from Production</h3><p>A typical Cassandra deployment:</p><ul><li><strong>6-node cluster</strong> with 256 vnodes each = 1,536 total virtual nodes</li><li>Adding 7th node: Only <strong>14.3%</strong> of data moves (1/7)</li><li><strong>Rebalancing time</strong>: Minutes, not hours</li><li><strong>Impact on reads</strong>: Minimal — most data stays in place</li></ul><h3>Case Study 2: Memcached with Ketama</h3><p>Memcached itself doesn’t implement consistent hashing — it’s a simple key-value cache. But <strong>Ketama</strong>, a popular client library, adds consistent hashing for multi-server deployments.</p><h3>The Memcached Problem</h3><pre>Traditional Memcached (without Ketama):<br>- 10 cache servers<br>- Server 5 crashes<br>- ALL keys remap (9 servers instead of 10)<br>- 100% cache miss rate<br>- Origin database gets hammered</pre><h3>Ketama’s solution:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*tSCzROTMixkNfWLHF4BWcw.png" /></figure><h3>Ketama Implementation Details:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4jNsfzA6pdeFPWd5IT1RmQ.png" /><figcaption>When server #3 fails, only those keys are passed on to the next server clockwise</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I-bRrXhY3lHQ2fH4sFkIsA.png" /></figure><p><strong>Virtual Nodes</strong>: 160 vnodes per server (hardcoded in original)</p><pre>// Ketama uses MD5 for hashing<br>for (i = 0; i &lt; 40; i++) {  // 40 * 4 = 160 points<br>    sprintf(vnode_key, &quot;%s-%d&quot;, server_id, i);<br>    md5_digest = MD5(vnode_key);<br>    // Use 4 points from each MD5 hash<br>    for (j = 0; j &lt; 4; j++) {<br>        point = extract_32bits(md5_digest, j);<br>        ring[point] = server;<br>    }<br>}</pre><p><strong><em>Why 160 Virtual Nodes?</em></strong></p><p>Empirical testing by the Ketama developers showed that <strong>160 vnodes</strong> provides:</p><ul><li><strong>Good distribution</strong>: Load variance within ±10% across servers</li><li><strong>Reasonable memory</strong>: Not excessive overhead for the hash ring</li><li><strong>Fast lookups</strong>: Binary search in O(log 160) = ~7–8 comparisons</li><li><strong>Optimal for caching</strong>: Balances distribution quality vs. computational cost</li></ul><p>The choice of <strong><em>40 iterations × 4 extractions</em></strong> was based on practical testing rather than theoretical optimization.</p><p><strong><em>How 160 nodes are created:</em></strong></p><p>1. Loop 40 times (i = 0 to 39)</p><p>2. For each iteration, create vnode key: &quot;memcached-1-0&quot;, memcached-1-1&quot;...</p><p>3. Compute MD5 hash (produces 128 bits = 16 bytes)</p><p>4. Extract 4 different 32-bit values from the 128-bit hash</p><p><strong><em>Result: 40 loops × 4 positions = 160 virtual nodes</em></strong></p><h3>Real-World Impact: Vimeo Case Study</h3><p>Vimeo’s cache infrastructure (before migrating to other solutions):</p><ul><li><strong>50 Memcached servers</strong></li><li><strong>~2TB of cached video thumbnails</strong></li><li><em>Server failure impact with Ketama</em>: <strong>2% cache miss increase</strong> (only failed server’s keys)</li><li><em>Without Ketama:</em> <strong>100% cache miss spike</strong> (all keys remap)</li></ul><p><strong>Cost savings</strong>:</p><ul><li>Origin server load: 50x reduction during failures</li><li>Network egress: <strong><em>Prevented $10K+/hour spikes</em></strong></li><li>User experience: No visible impact during maintenance</li></ul><h3>Advanced Topics</h3><h3>1. Bounded-Load Consistent Hashing</h3><p><strong>Problem</strong>: Popular keys can still overload a single server.</p><p><strong>Solution</strong>: Track load per server. If a server exceeds threshold, route to next server on ring.</p><pre>func (r *Ring) GetWithLoad(key string, loads map[string]int, maxLoad int) string {<br>    hash := r.hash(key)<br>    idx := sort.Search(len(r.keys), func(i int) bool {<br>        return r.keys[i] &gt;= hash<br>    })<br>// Try up to N servers;<br>    for i := 0; i &lt; len(r.keys); i++ {<br>        position := (idx + i) % len(r.keys)<br>        node := r.hashMap[r.keys[position]]<br>        if loads[node] &lt; maxLoad {<br>            return node<br>        }<br>    }<br>    // Fallback: return first server anyway<br>    return r.hashMap[r.keys[idx]]<br>}</pre><p><strong><em>Used by: Google’s load balancers</em></strong></p><h3>2. Jump Consistent Hash</h3><p>A more recent algorithm (2014) that’s even more efficient:</p><ul><li><strong>No storage required</strong>: Stateless algorithm</li><li><strong>O(log n) time</strong>: But faster constants than traditional consistent hashing</li><li><strong>Perfect balance</strong>: Exact 1/n split every time</li></ul><p><strong>Trade-off</strong>: Can’t handle weighted servers or custom placement.</p><h3>3. Rendezvous Hashing (HRW)</h3><p>Alternative approach: For each key, hash with every server, pick highest:</p><pre>func GetServer(key string, servers []string) string {<br>    var bestServer string<br>    var bestScore uint32<br>for _, server := range servers {<br>        score := hash(key + server)<br>        if score &gt; bestScore {<br>            bestScore = score<br>            bestServer = server<br>        }<br>    }<br>    return bestServer<br>}</pre><p><strong>Pros</strong>: Simple, no data structure needed.</p><p><strong>Cons</strong>: O(n) lookups — too slow for large clusters</p><h3>When NOT to Use Consistent Hashing</h3><p>Consistent hashing isn’t always the answer:</p><p><strong>&gt; Small, stable clusters</strong> (&lt; 5 nodes, rarely change)</p><ul><li>Simple modulo hashing is fine</li><li>Complexity not worth it</li></ul><p>&gt; <strong>Need perfect balance</strong></p><ul><li>Consistent hashing gives ~5–10% variance</li><li>For critical load balancing, use weighted round-robin</li></ul><p>&gt; <strong>Hot keys dominate</strong></p><ul><li>Single key hitting 10% of requests? Consistent hashing can’t help</li><li>Need application-level caching or sharding</li></ul><p><strong>&gt; Complex queries with joins</strong></p><ul><li>DHT lookups are great for key-value</li><li>Multi-key queries require scatter-gather (expensive)</li></ul><p><strong>&gt; Best for</strong>:</p><ul><li>Large clusters (10+ nodes)</li><li>Frequent topology changes</li><li>Cache invalidation is costly</li><li>Simple key-value access patterns</li></ul><h3>Interview Tips</h3><p>When asked to design a distributed system using consistent hashing:</p><p><strong>1. Start with the problem</strong></p><ul><li>“Why not simple hashing?”</li><li>Quantify the cost of remapping</li></ul><p><strong>2. Introduce the ring</strong></p><ul><li>Draw it clearly</li><li>Show hash positions for both keys and servers</li></ul><p><strong>3. Mention virtual nodes</strong></p><ul><li>Explain the distribution problem</li><li>Typical values: 100–150 replicas</li></ul><p><strong>4. Discuss trade-offs</strong></p><ul><li>Time complexity: O(log n) lookups</li><li>Space: O(n×replicas) — usually negligible</li><li>Distribution variance: ±5–10%</li></ul><p><strong>5. Cover edge cases</strong></p><ul><li>Empty ring</li><li>Single server (all keys go there)</li><li>Server removal (keys redistributed to next server)</li></ul><p><strong>6. Production considerations</strong></p><ul><li>Replication: Use GetN() for redundancy</li><li>Monitoring: Track key distribution across servers</li><li>Gradual rollout: Add virtual nodes incrementally</li></ul><h3>Conclusion: Why It Matters</h3><p><em>Consistent hashing is one of those rare algorithms that’s both theoretically beautiful and practically essential. It powers:</em></p><ul><li><strong>Cassandra</strong>: Billions of writes per day at Apple</li><li><strong>DynamoDB</strong>: Amazon’s managed database serving AWS</li><li><strong>CDNs</strong>: Akamai, Cloudflare routing petabytes of content</li><li><strong>Memcached/Redis</strong>: Caching layers for Netflix, Twitter, Facebook</li><li><strong>Chord DHT</strong>: Peer-to-peer systems and blockchain networks</li></ul><p>The key insight — mapping both keys and nodes to a ring — transforms a seemingly intractable problem (minimizing key remapping) into an elegant solution with mathematical guarantees.</p><p>Next time you’re streaming Netflix without buffering, or your tweet loads instantly, or your Zoom call doesn’t drop — there’s a good chance consistent hashing is working invisibly in the background, keeping the internet running smoothly.</p><h3>Further Resources</h3><p>📚 <strong>Original Paper</strong>: <a href="https://dl.acm.org/doi/10.1145/258533.258660">Consistent Hashing and Random Trees</a> — Karger et al., 1997</p><p>📄 <strong>Amazon Dynamo Paper</strong>: The paper that popularized consistent hashing — <a href="https://www.allthingsdistributed.com/files/amazon-dynamo-sosp2007.pdf">PDF</a></p><p>🎓 <strong>Cassandra Documentation</strong>: <a href="https://cassandra.apache.org/doc/latest/architecture/dynamo.html">Data Distribution</a></p><p>💻 <strong>Production Implementation</strong>: <a href="https://github.com/buraksezer/consistent">buraksezer/consistent</a> — Includes bounded-load variant</p><p>🎬 <strong>Video</strong>: <a href="https://www.youtube.com/watch?v=zaRkONvyGr8"><strong>Consistent Hashing Explained</strong></a>, <a href="https://youtu.be/vccwdhfqIrI?si=gbE0AedSl_DF2i2e"><strong>Another Explanation</strong></a></p><p><em>Written by pred695/Zaid. If you found this helpful, consider following me for more deep dives into distributed systems! Code examples on the way!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1bd6ec63489" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>