BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / LLM inference and serving33 of 36 in topic

805. Route requests to replicas with a consistent hash ring

MediumLLM inference and serving Pro

Why it matters Prefix-aware LLM routers and distributed KV caches use consistent hashing so scaling a fleet does not cold-start every cache.

When a model server is added or removed, plain hash(key) % n remaps almost every key, which wipes out every replica's prompt cache. A consistent hash ring moves only about 1/n of the keys.

Write ring_route(nodes, keys, vnodes). Hash a string with h(s) = int(hashlib.md5(s.encode()).hexdigest(), 16). Put vnodes points on the ring for each node at h(f"{node}#{v}") for v = 0..vnodes-1. A key goes to the node owning the first point with hash >= h(key), wrapping around to the smallest point if none. Ties between points cannot happen with md5 for these inputs.
Return a dict key -> node.

Functiondef ring_route(nodes, keys, vnodes)

Example 1

Input: ring_route(['A', 'B'], ['x', 'y', 'z'], 3)

Output: {'x': 'B', 'y': 'B', 'z': 'B'}

Example 2

Input: nodes = ['gpu0'], keys = ['a', 'b'], vnodes = 1

Output: {'a': 'gpu0', 'b': 'gpu0'}

Constraints

  • Python 3 standard library. Code runs in your browser.
  • Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1

Build a sorted list of (hash, node) for all virtual nodes.

Hint 2

Use bisect to find the first point at or after the key's hash.

Hint 3

Wrap with modulo when the key hashes past the last point.

Common mistakes
  • Using hash(key) % n, which remaps most keys when n changes.
  • Forgetting the wrap-around, which raises an IndexError.
Understand the idea

Nodes and keys are hashed onto the same circle. A key belongs to the next node point clockwise. Adding a node only steals keys that land just before its points; every other key keeps its owner. Virtual nodes spread each server over many points so load evens out.

Worked example

with a single node every key maps to it.

sort node points; owner = first point >= h(key), wrapping to index 0
Topics
LLM inference and serving
Similar questions
  • Generate one token at a time with a KV cacheMedium
  • Allocate KV cache memory in pages, like vLLMMedium
  • Verify a draft model's guesses in speculative decodingMedium
  • Is decoding memory-bound? A roofline estimateMedium
All LLM inference and serving problems
Report
805 / 903
Python 3solution.pyPython idle
1
2
3
4
5
import bisect, hashlib
def ring_route(nodes, keys, vnodes):
# your code here
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS