{"id":"6b093dddbd4755deb67ee05e","slug":"consistent-hashing","title":"Consistent hashing ring","summary":"Spread cache keys over servers so that adding or removing a server moves only a small share of keys. A ring with virtual nodes and binary search.","servedLang":"en","availableLangs":["pl","en"],"kind":"code","category":"algorithms","status":"published","difficulty":"hard","topics":[],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["hashing","binary-search","design","distributed-systems","consistent-hashing"],"languages":[{"lang":"typescript","runner":"browser","starter":"/** FNV-1a over UTF-8 bytes + MurmurHash3 finalizer → unsigned 32-bit integer. Ready to use. */\nfunction hash32(s: string): number {\n  let h = 2166136261;\n  for (const b of new TextEncoder().encode(s)) h = Math.imul(h ^ b, 16777619) >>> 0;\n  h ^= h >>> 16;\n  h = Math.imul(h, 0x85ebca6b) >>> 0;\n  h ^= h >>> 13;\n  h = Math.imul(h, 0xc2b2ae35) >>> 0;\n  h ^= h >>> 16;\n  return h >>> 0;\n}\n\nclass HashRing {\n  /** @param replicas virtual nodes per server: \"name#0\" … \"name#(replicas-1)\" */\n  constructor(private readonly replicas: number) {\n    // TODO\n  }\n\n  addNode(name: string): void {\n    throw new Error('Not implemented');\n  }\n\n  removeNode(name: string): void {\n    throw new Error('Not implemented');\n  }\n\n  /** Server of the first virtual node with position >= hash32(key) (wrapping around); null for an empty ring. */\n  getNode(key: string): string | null {\n    throw new Error('Not implemented');\n  }\n}\n","testCount":9,"tests":"function ringOf(replicas, ...servers) {\n  const ring = new HashRing(replicas);\n  servers.forEach((s) => ring.addNode(s));\n  return ring;\n}\n\ntest('hash32 is the specified function', () => {\n  expect(hash32('')).toBe(2872998923);\n  expect(hash32('a')).toBe(444641715);\n  expect(hash32('foobar')).toBe(202221276);\n  expect(hash32('zażółć')).toBe(135053214);\n});\n\ntest('empty ring and a single server', () => {\n  const ring = new HashRing(10);\n  expect(ring.getNode('user:1')).toBeNull();\n  ring.addNode('solo');\n  for (let i = 0; i < 100; i++) expect(ring.getNode('key-' + i)).toBe('solo');\n});\n\ntest('keys go to the next virtual node clockwise', () => {\n  const ring = ringOf(3, 'cache-a', 'cache-b', 'cache-c');\n  const expected = {\n    'user:1': 'cache-b', 'user:2': 'cache-c', 'user:3': 'cache-c', 'session:abc': 'cache-b',\n    'cart:77': 'cache-b', 'order:2026': 'cache-c', 'img/logo.png': 'cache-c', zzz: 'cache-c',\n  };\n  for (const [key, server] of Object.entries(expected)) expect([key, ring.getNode(key)]).toEqual([key, server]);\n});\n\ntest('hashes above the last position wrap around', () => {\n  const ring = ringOf(3, 'cache-a', 'cache-b', 'cache-c');\n  expect(ring.getNode('key-10')).toBe('cache-c');\n  expect(ring.getNode('key-41')).toBe('cache-c');\n});\n\ntest('removing a server moves only its keys', () => {\n  const ring = ringOf(100, 'cache-a', 'cache-b', 'cache-c');\n  const before = Array.from({ length: 10000 }, (_, i) => ring.getNode('key-' + i));\n  ring.removeNode('cache-b');\n  for (let i = 0; i < 10000; i++) {\n    const now = ring.getNode('key-' + i);\n    if (before[i] !== 'cache-b') expect(now).toBe(before[i]);\n    else expect(now).not.toBe('cache-b');\n  }\n  ring.addNode('cache-b');\n  expect(Array.from({ length: 10000 }, (_, i) => ring.getNode('key-' + i))).toEqual(before);\n});\n\ntest('adding a server moves keys only to the new server', () => {\n  const ring = ringOf(100, 'cache-a', 'cache-b');\n  const before = Array.from({ length: 10000 }, (_, i) => ring.getNode('key-' + i));\n  ring.addNode('cache-c');\n  let moved = 0;\n  for (let i = 0; i < 10000; i++) {\n    const now = ring.getNode('key-' + i);\n    if (now !== before[i]) {\n      expect(now).toBe('cache-c');\n      moved++;\n    }\n  }\n  expect(moved).toBeGreaterThan(2000);\n  expect(moved).toBeLessThan(5000);\n});\n\ntest('adding twice and removing a missing server change nothing', () => {\n  const ring = ringOf(50, 'x', 'y');\n  const before = Array.from({ length: 1000 }, (_, i) => ring.getNode('k' + i));\n  ring.addNode('x');\n  ring.removeNode('nope');\n  expect(Array.from({ length: 1000 }, (_, i) => ring.getNode('k' + i))).toEqual(before);\n});\n\ntest('virtual nodes balance the load', () => {\n  const ring = ringOf(150, 'a', 'b', 'c', 'd');\n  const counts = { a: 0, b: 0, c: 0, d: 0 };\n  for (let i = 0; i < 20000; i++) counts[ring.getNode('key-' + i)]++;\n  for (const server of Object.keys(counts)) {\n    expect(counts[server]).toBeGreaterThan(3000);\n    expect(counts[server]).toBeLessThan(7000);\n  }\n});\n\ntest('performance: 100 servers × 200 replicas, 50 000 lookups', () => {\n  const ring = new HashRing(200);\n  for (let i = 0; i < 100; i++) ring.addNode('node-' + i);\n  const counts = new Map();\n  for (let i = 0; i < 50000; i++) {\n    const server = ring.getNode('item:' + i);\n    counts.set(server, (counts.get(server) ?? 0) + 1);\n  }\n  expect(counts.size).toBe(100);\n  expect(counts.get('node-7')).toBe(492);\n  expect(counts.get('node-42')).toBe(511);\n  for (const c of counts.values()) expect(c > 300 && c < 700).toBe(true);\n});\n"},{"lang":"javascript","runner":"browser","starter":"/** FNV-1a over UTF-8 bytes + MurmurHash3 finalizer → unsigned 32-bit integer. Ready to use. */\nfunction hash32(s) {\n  let h = 2166136261;\n  for (const b of new TextEncoder().encode(s)) h = Math.imul(h ^ b, 16777619) >>> 0;\n  h ^= h >>> 16;\n  h = Math.imul(h, 0x85ebca6b) >>> 0;\n  h ^= h >>> 13;\n  h = Math.imul(h, 0xc2b2ae35) >>> 0;\n  h ^= h >>> 16;\n  return h >>> 0;\n}\n\nclass HashRing {\n  /** @param {number} replicas virtual nodes per server: \"name#0\" … \"name#(replicas-1)\" */\n  constructor(replicas) {\n    // TODO\n  }\n\n  addNode(name) {\n    throw new Error('Not implemented');\n  }\n\n  removeNode(name) {\n    throw new Error('Not implemented');\n  }\n\n  /** Server of the first virtual node with position >= hash32(key) (wrapping around); null for an empty ring. */\n  getNode(key) {\n    throw new Error('Not implemented');\n  }\n}\n","testCount":9,"tests":"function ringOf(replicas, ...servers) {\n  const ring = new HashRing(replicas);\n  servers.forEach((s) => ring.addNode(s));\n  return ring;\n}\n\ntest('hash32 is the specified function', () => {\n  expect(hash32('')).toBe(2872998923);\n  expect(hash32('a')).toBe(444641715);\n  expect(hash32('foobar')).toBe(202221276);\n  expect(hash32('zażółć')).toBe(135053214);\n});\n\ntest('empty ring and a single server', () => {\n  const ring = new HashRing(10);\n  expect(ring.getNode('user:1')).toBeNull();\n  ring.addNode('solo');\n  for (let i = 0; i < 100; i++) expect(ring.getNode('key-' + i)).toBe('solo');\n});\n\ntest('keys go to the next virtual node clockwise', () => {\n  const ring = ringOf(3, 'cache-a', 'cache-b', 'cache-c');\n  const expected = {\n    'user:1': 'cache-b', 'user:2': 'cache-c', 'user:3': 'cache-c', 'session:abc': 'cache-b',\n    'cart:77': 'cache-b', 'order:2026': 'cache-c', 'img/logo.png': 'cache-c', zzz: 'cache-c',\n  };\n  for (const [key, server] of Object.entries(expected)) expect([key, ring.getNode(key)]).toEqual([key, server]);\n});\n\ntest('hashes above the last position wrap around', () => {\n  const ring = ringOf(3, 'cache-a', 'cache-b', 'cache-c');\n  expect(ring.getNode('key-10')).toBe('cache-c');\n  expect(ring.getNode('key-41')).toBe('cache-c');\n});\n\ntest('removing a server moves only its keys', () => {\n  const ring = ringOf(100, 'cache-a', 'cache-b', 'cache-c');\n  const before = Array.from({ length: 10000 }, (_, i) => ring.getNode('key-' + i));\n  ring.removeNode('cache-b');\n  for (let i = 0; i < 10000; i++) {\n    const now = ring.getNode('key-' + i);\n    if (before[i] !== 'cache-b') expect(now).toBe(before[i]);\n    else expect(now).not.toBe('cache-b');\n  }\n  ring.addNode('cache-b');\n  expect(Array.from({ length: 10000 }, (_, i) => ring.getNode('key-' + i))).toEqual(before);\n});\n\ntest('adding a server moves keys only to the new server', () => {\n  const ring = ringOf(100, 'cache-a', 'cache-b');\n  const before = Array.from({ length: 10000 }, (_, i) => ring.getNode('key-' + i));\n  ring.addNode('cache-c');\n  let moved = 0;\n  for (let i = 0; i < 10000; i++) {\n    const now = ring.getNode('key-' + i);\n    if (now !== before[i]) {\n      expect(now).toBe('cache-c');\n      moved++;\n    }\n  }\n  expect(moved).toBeGreaterThan(2000);\n  expect(moved).toBeLessThan(5000);\n});\n\ntest('adding twice and removing a missing server change nothing', () => {\n  const ring = ringOf(50, 'x', 'y');\n  const before = Array.from({ length: 1000 }, (_, i) => ring.getNode('k' + i));\n  ring.addNode('x');\n  ring.removeNode('nope');\n  expect(Array.from({ length: 1000 }, (_, i) => ring.getNode('k' + i))).toEqual(before);\n});\n\ntest('virtual nodes balance the load', () => {\n  const ring = ringOf(150, 'a', 'b', 'c', 'd');\n  const counts = { a: 0, b: 0, c: 0, d: 0 };\n  for (let i = 0; i < 20000; i++) counts[ring.getNode('key-' + i)]++;\n  for (const server of Object.keys(counts)) {\n    expect(counts[server]).toBeGreaterThan(3000);\n    expect(counts[server]).toBeLessThan(7000);\n  }\n});\n\ntest('performance: 100 servers × 200 replicas, 50 000 lookups', () => {\n  const ring = new HashRing(200);\n  for (let i = 0; i < 100; i++) ring.addNode('node-' + i);\n  const counts = new Map();\n  for (let i = 0; i < 50000; i++) {\n    const server = ring.getNode('item:' + i);\n    counts.set(server, (counts.get(server) ?? 0) + 1);\n  }\n  expect(counts.size).toBe(100);\n  expect(counts.get('node-7')).toBe(492);\n  expect(counts.get('node-42')).toBe(511);\n  for (const c of counts.values()) expect(c > 300 && c < 700).toBe(true);\n});\n"},{"lang":"python","runner":"browser","starter":"def hash32(s: str) -> int:\n    \"\"\"FNV-1a over UTF-8 bytes + MurmurHash3 finalizer -> unsigned 32-bit integer. Ready to use.\"\"\"\n    h = 2166136261\n    for b in s.encode(\"utf-8\"):\n        h = ((h ^ b) * 16777619) & 0xFFFFFFFF\n    h ^= h >> 16\n    h = (h * 0x85EBCA6B) & 0xFFFFFFFF\n    h ^= h >> 13\n    h = (h * 0xC2B2AE35) & 0xFFFFFFFF\n    h ^= h >> 16\n    return h\n\n\nclass HashRing:\n    def __init__(self, replicas: int) -> None:\n        \"\"\"replicas = virtual nodes per server: \"name#0\" ... \"name#(replicas-1)\".\"\"\"\n        pass  # TODO\n\n    def add_node(self, name: str) -> None:\n        raise NotImplementedError\n\n    def remove_node(self, name: str) -> None:\n        raise NotImplementedError\n\n    def get_node(self, key: str) -> str | None:\n        \"\"\"Server of the first virtual node with position >= hash32(key) (wrapping around); None for an empty ring.\"\"\"\n        raise NotImplementedError\n","testCount":9,"tests":"def ring_of(replicas, *servers):\n    ring = HashRing(replicas)\n    for s in servers:\n        ring.add_node(s)\n    return ring\n\n\ndef test_hash32_is_the_specified_function():\n    for s, h in ((\"\", 2872998923), (\"a\", 444641715), (\"foobar\", 202221276), (\"zażółć\", 135053214)):\n        assert hash32(s) == h, f\"hash32({s!r}): expected {h}, got {hash32(s)}\"\n\n\ndef test_empty_ring_and_single_server():\n    ring = HashRing(10)\n    assert ring.get_node(\"user:1\") is None, \"an empty ring should return None\"\n    ring.add_node(\"solo\")\n    for i in range(100):\n        assert ring.get_node(f\"key-{i}\") == \"solo\"\n\n\ndef test_keys_go_to_the_next_virtual_node_clockwise():\n    ring = ring_of(3, \"cache-a\", \"cache-b\", \"cache-c\")\n    expected = {\"user:1\": \"cache-b\", \"user:2\": \"cache-c\", \"user:3\": \"cache-c\", \"session:abc\": \"cache-b\",\n                \"cart:77\": \"cache-b\", \"order:2026\": \"cache-c\", \"img/logo.png\": \"cache-c\", \"zzz\": \"cache-c\"}\n    for key, server in expected.items():\n        got = ring.get_node(key)\n        assert got == server, f\"get_node({key!r}): expected {server}, got {got}\"\n\n\ndef test_hashes_above_the_last_position_wrap_around():\n    ring = ring_of(3, \"cache-a\", \"cache-b\", \"cache-c\")\n    assert ring.get_node(\"key-10\") == \"cache-c\" and ring.get_node(\"key-41\") == \"cache-c\", \"wrap-around\"\n\n\ndef test_removing_a_server_moves_only_its_keys():\n    ring = ring_of(100, \"cache-a\", \"cache-b\", \"cache-c\")\n    before = [ring.get_node(f\"key-{i}\") for i in range(10_000)]\n    ring.remove_node(\"cache-b\")\n    for i in range(10_000):\n        now = ring.get_node(f\"key-{i}\")\n        if before[i] != \"cache-b\":\n            assert now == before[i], f\"key-{i} moved from {before[i]} to {now}\"\n        else:\n            assert now != \"cache-b\", f\"key-{i} is still on the removed server\"\n    ring.add_node(\"cache-b\")\n    assert [ring.get_node(f\"key-{i}\") for i in range(10_000)] == before, \"re-adding should restore the mapping\"\n\n\ndef test_adding_a_server_moves_keys_only_to_it():\n    ring = ring_of(100, \"cache-a\", \"cache-b\")\n    before = [ring.get_node(f\"key-{i}\") for i in range(10_000)]\n    ring.add_node(\"cache-c\")\n    moved = 0\n    for i in range(10_000):\n        now = ring.get_node(f\"key-{i}\")\n        if now != before[i]:\n            assert now == \"cache-c\", f\"key-{i} moved to {now}, not to the new server\"\n            moved += 1\n    assert 2000 < moved < 5000, f\"moved {moved} keys\"\n\n\ndef test_adding_twice_and_removing_missing_change_nothing():\n    ring = ring_of(50, \"x\", \"y\")\n    before = [ring.get_node(f\"k{i}\") for i in range(1000)]\n    ring.add_node(\"x\")\n    ring.remove_node(\"nope\")\n    assert [ring.get_node(f\"k{i}\") for i in range(1000)] == before\n\n\ndef test_virtual_nodes_balance_the_load():\n    ring = ring_of(150, \"a\", \"b\", \"c\", \"d\")\n    counts = {\"a\": 0, \"b\": 0, \"c\": 0, \"d\": 0}\n    for i in range(20_000):\n        counts[ring.get_node(f\"key-{i}\")] += 1\n    assert all(3000 < c < 7000 for c in counts.values()), f\"unbalanced: {counts}\"\n\n\ndef test_performance_100_servers_50k_lookups():\n    ring = HashRing(200)\n    for i in range(100):\n        ring.add_node(f\"node-{i}\")\n    counts = {}\n    for i in range(50_000):\n        server = ring.get_node(f\"item:{i}\")\n        counts[server] = counts.get(server, 0) + 1\n    assert len(counts) == 100, f\"{len(counts)} servers used\"\n    assert counts[\"node-7\"] == 492 and counts[\"node-42\"] == 511, f\"node-7: {counts['node-7']}, node-42: {counts['node-42']}\"\n    assert all(300 < c < 700 for c in counts.values()), \"load out of range\"\n"},{"lang":"csharp","runner":"judge0","starter":"using System;\nusing System.Collections.Generic;\nusing System.Text;\n\npublic class HashRing\n{\n    /// <summary>FNV-1a over UTF-8 bytes + MurmurHash3 finalizer. Ready to use.</summary>\n    public static uint Hash32(string s)\n    {\n        unchecked\n        {\n            uint h = 2166136261;\n            foreach (byte b in Encoding.UTF8.GetBytes(s)) h = (h ^ b) * 16777619;\n            h ^= h >> 16;\n            h *= 0x85ebca6b;\n            h ^= h >> 13;\n            h *= 0xc2b2ae35;\n            h ^= h >> 16;\n            return h;\n        }\n    }\n\n    /// <param name=\"replicas\">virtual nodes per server: \"name#0\" ... \"name#(replicas-1)\"</param>\n    public HashRing(int replicas)\n    {\n        // TODO\n    }\n\n    public void AddNode(string name)\n    {\n        throw new NotImplementedException();\n    }\n\n    public void RemoveNode(string name)\n    {\n        throw new NotImplementedException();\n    }\n\n    /// <summary>Server of the first virtual node with position &gt;= Hash32(key) (wrapping around); null for an empty ring.</summary>\n    public string GetNode(string key)\n    {\n        throw new NotImplementedException();\n    }\n}\n","testCount":9},{"lang":"java","runner":"judge0","starter":"import java.nio.charset.StandardCharsets;\nimport java.util.*;\n\nclass HashRing {\n    /** FNV-1a over UTF-8 bytes + MurmurHash3 finalizer; unsigned 32-bit value in a long. Ready to use. */\n    static long hash32(String s) {\n        long h = 2166136261L;\n        for (byte b : s.getBytes(StandardCharsets.UTF_8)) h = ((h ^ (b & 0xff)) * 16777619L) & 0xFFFFFFFFL;\n        h ^= h >>> 16;\n        h = (h * 0x85ebca6bL) & 0xFFFFFFFFL;\n        h ^= h >>> 13;\n        h = (h * 0xc2b2ae35L) & 0xFFFFFFFFL;\n        h ^= h >>> 16;\n        return h;\n    }\n\n    /** replicas = virtual nodes per server: \"name#0\" ... \"name#(replicas-1)\". */\n    HashRing(int replicas) {\n        // TODO\n    }\n\n    void addNode(String name) {\n        throw new UnsupportedOperationException(\"Not implemented\");\n    }\n\n    void removeNode(String name) {\n        throw new UnsupportedOperationException(\"Not implemented\");\n    }\n\n    /** Server of the first virtual node with position >= hash32(key) (wrapping around); null for an empty ring. */\n    String getNode(String key) {\n        throw new UnsupportedOperationException(\"Not implemented\");\n    }\n}\n","testCount":9},{"lang":"go","runner":"judge0","starter":"package main\n\n// Hash32 is FNV-1a over the UTF-8 bytes of s plus the MurmurHash3 finalizer. Ready to use.\nfunc Hash32(s string) uint32 {\n\th := uint32(2166136261)\n\tfor i := 0; i < len(s); i++ {\n\t\th = (h ^ uint32(s[i])) * 16777619\n\t}\n\th ^= h >> 16\n\th *= 0x85ebca6b\n\th ^= h >> 13\n\th *= 0xc2b2ae35\n\th ^= h >> 16\n\treturn h\n}\n\ntype HashRing struct {\n\t// TODO\n}\n\n// NewHashRing creates an empty ring; replicas = virtual nodes per server (\"name#0\" ... \"name#(replicas-1)\").\nfunc NewHashRing(replicas int) *HashRing {\n\treturn &HashRing{}\n}\n\nfunc (r *HashRing) AddNode(name string) {\n\tpanic(\"not implemented\")\n}\n\nfunc (r *HashRing) RemoveNode(name string) {\n\tpanic(\"not implemented\")\n}\n\n// GetNode returns the server of the first virtual node with position >= Hash32(key) (wrapping around);\n// \"\" for an empty ring.\nfunc (r *HashRing) GetNode(key string) string {\n\tpanic(\"not implemented\")\n}\n","testCount":9}],"questionCount":null,"xp":40,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:53.583Z","requestedLang":"en","statement":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"A cache cluster has a few servers. Naive "},{"type":"text","text":"hash(key) % serverCount","marks":[{"type":"code"}]},{"type":"text","text":" moves almost "},{"type":"text","text":"all","marks":[{"type":"bold"}]},{"type":"text","text":" keys when one server is added – the cache is suddenly empty and the database gets an avalanche of queries. "},{"type":"text","text":"Consistent hashing","marks":[{"type":"bold"}]},{"type":"text","text":" (Dynamo, Cassandra, Memcached, load balancers) moves only the keys that have to move."}]},{"type":"heading","attrs":{"level":2,"id":"task"},"content":[{"type":"text","text":"Task"}]},{"type":"paragraph","content":[{"type":"text","text":"A class "},{"type":"text","text":"HashRing(replicas)","marks":[{"type":"code"}]},{"type":"text","text":":"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"every server "},{"type":"text","text":"name","marks":[{"type":"code"}]},{"type":"text","text":" has "},{"type":"text","text":"replicas","marks":[{"type":"code"}]},{"type":"text","text":" "},{"type":"text","text":"virtual nodes","marks":[{"type":"bold"}]},{"type":"text","text":" labelled "},{"type":"text","text":"name#0","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"name#1","marks":[{"type":"code"}]},{"type":"text","text":", …, "},{"type":"text","text":"name#(replicas-1)","marks":[{"type":"code"}]},{"type":"text","text":"; a node's position on the ring is "},{"type":"text","text":"hash32(label)","marks":[{"type":"code"}]},{"type":"text","text":" (a number in "},{"type":"text","text":"0 … 2³² − 1","marks":[{"type":"code"}]},{"type":"text","text":"),"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"addNode(name)","marks":[{"type":"code"}]},{"type":"text","text":" adds a server (adding an existing one changes nothing), "},{"type":"text","text":"removeNode(name)","marks":[{"type":"code"}]},{"type":"text","text":" removes it (removing a missing one changes nothing),"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"getNode(key)","marks":[{"type":"code"}]},{"type":"text","text":" returns the server of the first virtual node "},{"type":"text","text":"clockwise","marks":[{"type":"bold"}]},{"type":"text","text":" from "},{"type":"text","text":"hash32(key)","marks":[{"type":"code"}]},{"type":"text","text":": the one with the smallest position "},{"type":"text","text":"≥ hash32(key)","marks":[{"type":"code"}]},{"type":"text","text":", or, if there is none, the first node of the ring (wrap-around); for equal positions the smaller label wins; an empty ring → "},{"type":"text","text":"null","marks":[{"type":"code"}]},{"type":"text","text":" / "},{"type":"text","text":"None","marks":[{"type":"code"}]},{"type":"text","text":" / "},{"type":"text","text":"\"\"","marks":[{"type":"code"}]},{"type":"text","text":" (Go)."}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"The "},{"type":"text","text":"hash32","marks":[{"type":"code"}]},{"type":"text","text":" function (FNV-1a over UTF-8 bytes with a final bit mix) is ready in the starter code – no need to change it."}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Language"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"API"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"JS/TS"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"hash32(s)","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"new HashRing(replicas)","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"addNode","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"removeNode","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"getNode","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Python"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"hash32(s)","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"HashRing(replicas)","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"add_node","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"remove_node","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"get_node","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"C#"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"HashRing.Hash32(s)","marks":[{"type":"code"}]},{"type":"text","text":" ("},{"type":"text","text":"uint","marks":[{"type":"code"}]},{"type":"text","text":"), "},{"type":"text","text":"new HashRing(replicas)","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"AddNode","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"RemoveNode","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"GetNode","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Java"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"HashRing.hash32(s)","marks":[{"type":"code"}]},{"type":"text","text":" ("},{"type":"text","text":"long","marks":[{"type":"code"}]},{"type":"text","text":"), "},{"type":"text","text":"new HashRing(replicas)","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"addNode","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"removeNode","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"getNode","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Go"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Hash32(s)","marks":[{"type":"code"}]},{"type":"text","text":" ("},{"type":"text","text":"uint32","marks":[{"type":"code"}]},{"type":"text","text":"), "},{"type":"text","text":"NewHashRing(replicas)","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"AddNode","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"RemoveNode","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"GetNode","marks":[{"type":"code"}]}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"example"},"content":[{"type":"text","text":"Example"}]},{"type":"paragraph","content":[{"type":"text","text":"Servers "},{"type":"text","text":"cache-a","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"cache-b","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"cache-c","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"replicas = 3","marks":[{"type":"code"}]},{"type":"text","text":". Virtual nodes sorted by position:"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Position"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Label"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"776,460,556"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"cache-c#0","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"1,369,040,872"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"cache-a#1","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"1,682,050,073"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"cache-b#2","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"…"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"…"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"4,200,630,493"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"cache-b#0","marks":[{"type":"code"}]}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"hash32(\"user:1\") = 1,763,983,599","marks":[{"type":"code"}]},{"type":"text","text":" → the first node not smaller is "},{"type":"text","text":"cache-b#1","marks":[{"type":"code"}]},{"type":"text","text":" (1,901,845,678) → "},{"type":"text","text":"cache-b","marks":[{"type":"code"}]},{"type":"text","text":". "},{"type":"text","text":"hash32(\"key-10\") = 4,216,627,689","marks":[{"type":"code"}]},{"type":"text","text":" is larger than every position → wrap-around to "},{"type":"text","text":"cache-c#0","marks":[{"type":"code"}]},{"type":"text","text":" → "},{"type":"text","text":"cache-c","marks":[{"type":"code"}]},{"type":"text","text":"."}]},{"type":"heading","attrs":{"level":2,"id":"constraints"},"content":[{"type":"text","text":"Constraints"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Up to 100 servers, "},{"type":"text","text":"1 ≤ replicas ≤ 200","marks":[{"type":"code"}]},{"type":"text","text":", up to 50,000 "},{"type":"text","text":"getNode","marks":[{"type":"code"}]},{"type":"text","text":" calls per test."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"expected-complexity"},"content":[{"type":"text","text":"Expected complexity"}]},{"type":"paragraph","content":[{"type":"text","text":"getNode","marks":[{"type":"code"}]},{"type":"text","text":": "},{"type":"text","text":"O(log(N · R))","marks":[{"type":"bold"}]},{"type":"text","text":" for "},{"type":"text","text":"N","marks":[{"type":"code"}]},{"type":"text","text":" servers and "},{"type":"text","text":"R","marks":[{"type":"code"}]},{"type":"text","text":" replicas. "},{"type":"text","text":"addNode","marks":[{"type":"code"}]},{"type":"text","text":" / "},{"type":"text","text":"removeNode","marks":[{"type":"code"}]},{"type":"text","text":": "},{"type":"text","text":"O(N · R · log(N · R))","marks":[{"type":"bold"}]},{"type":"text","text":" (rebuilding the sorted array) or better with a tree structure."}]}]},"hints":[],"hintsCount":3,"quiz":null,"solutionNotes":null,"unlocked":false,"external":[],"articles":[],"topicsInfo":[],"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"capabilities":{"judge0":false,"aiReview":false},"createdAt":"2026-11-27T08:22:53.585Z","updatedAt":"2026-11-27T08:22:53.585Z"}