Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Worked example · 20 min · revision 1

Rings in practice: cache clients and Dynamo-style stores

Work through two designs: a client-hashed memcached tier, from choosing the client's distribution to rehearsing a node ejection and capping hot spots with bounded loads, and a Dynamo-style store whose replicas follow the ring across zones.

Contentsand lesson path

What you will learn

  • Apply consistent hashing to a cache cluster or partitioned store, including replica placement on the ring.

01. The problem

An online shop runs two systems that both split keys with consistent hashing:

  • a product cache: six memcached nodes, cache-0 to cache-5, in front of the catalogue database, used by 40 app servers whose client library picks the node for each key;
  • an order store: a Dynamo-style database with nine nodes in three availability zones, keeping three copies of every order.

You will decide how the cache clients hash, rehearse what happens when a cache node is ejected and comes back, cap hot spots, and check where the store's replicas land. Every script reuses ring.py from the lab, so save them in the same ring-lab folder. Each runs in a few seconds and prints the same numbers every time.

02. Step 1: Pin down the cache client's distribution

memcached servers do not know about each other. The client library alone decides which server owns a key, so the first job is to check what your clients actually do. Defaults are not always consistent hashing:

  • libmemcached, the C library under many language bindings, defaults to MEMCACHED_DISTRIBUTION_MODULA, which is hash mod N. Setting MEMCACHED_BEHAVIOR_KETAMA switches to ketama consistent hashing with MD5.
  • The PHP Memcached extension also defaults to DISTRIBUTION_MODULA; OPT_LIBKETAMA_COMPATIBLE turns on MD5 ketama hashing that matches other libketama-based clients.
  • In Python, pymemcache's HashClient uses rendezvous hashing by default.
  • NGINX's hash $key consistent; uses ketama and is documented as compatible with a Perl client set to 160 points per server.

Then make every client build the same mapping. All of them need the same algorithm, the same server list spelled the same way (10.0.0.5:11211 and cache-5:11211 hash differently), and the same weights. A fleet that mixes languages needs compatible settings in each library, or the same key lands on different servers depending on which service wrote it. Ship server-list changes to all clients together; a rollout in which some clients hold the old list and some the new one makes them disagree about the keys that moved.

03. Step 2: Rehearse an ejection and the return

Many clients eject a server that keeps failing and try it again later. pymemcache's HashClient, for example, marks a server dead after its retries fail (retry_attempts=2 by default) and adds it back after dead_timeout, 60 seconds by default. The script below rehearses that with 160 tokens per node. It warms the cache, ejects cache-2, updates 3,000 products during the outage with cache-aside writes (update the database, then delete the cached copy on the key's current node), and re-adds cache-2, first as it was and then after flushing it.

Python 3.12 · ring-lab/cache_tier.py (needs ring.py from the lab)
"""A client-side ring over 6 cache nodes: cache-2 is ejected, then re-added."""
import random

from ring import HashRing, ModN

NODES = [f"cache-{i}" for i in range(6)]
KEYS = [f"product:{i}" for i in range(60_000)]
REST = [n for n in NODES if n != "cache-2"]
full = HashRing(NODES, vnodes=160)
without = HashRing(REST, vnodes=160)


def rehearse(flush_on_return: bool) -> tuple[int, int, int]:
    cache = {node: {} for node in NODES}  # what each cache node holds
    db = dict.fromkeys(KEYS, 1)  # version of each product in the database

    def read(ring: HashRing, key: str) -> tuple[int, bool]:
        node = cache[ring.owner(key)]
        if key in node:
            return node[key], True
        node[key] = db[key]  # cache-aside: on a miss, load from the database
        return db[key], False

    for key in KEYS:  # warm up: every product cached at version 1
        read(full, key)
    out = sum(not read(without, k)[1] for k in KEYS)  # cache-2 ejected
    for key in random.Random(7).sample(KEYS, 3_000):  # updates during the outage
        db[key] = 2
        cache[without.owner(key)].pop(key, None)  # delete the cached copy
    if flush_on_return:
        cache["cache-2"].clear()
    results = [(key, *read(full, key)) for key in KEYS]  # cache-2 is back
    stale = sum(version != db[key] for key, version, _ in results)
    misses = sum(not hit for _, _, hit in results)
    return out, stale, misses


modn = sum(ModN(NODES).owner(k) != ModN(REST).owner(k) for k in KEYS)
out, stale, misses = rehearse(flush_on_return=False)
print(f"cache-2 ejected: {out:,} of {len(KEYS):,} reads miss ({out / len(KEYS):.1%});",
      f"hash mod N would remap {modn / len(KEYS):.1%}")
print(f"re-added as it was:   {stale:,} stale reads, {misses:,} misses")
out, stale, misses = rehearse(flush_on_return=True)
print(f"re-added after flush: {stale:,} stale reads, {misses:,} misses")
Terminal · ring-lab/
python3 cache_tier.py
Expected output
cache-2 ejected: 11,016 of 60,000 reads miss (18.4%); hash mod N would remap 83.3%
re-added as it was:   519 stale reads, 2,481 misses
re-added after flush: 0 stale reads, 13,497 misses

While cache-2 is out, 18.4% of reads miss: its own share and nothing more, where modulo would have remapped 83.3%. The return is the dangerous part. cache-2 never restarted, so it still holds every copy it had before the outage, including old versions of keys that changed. The deletes during the outage went to the substitute nodes, so 519 products that changed come back from cache-2 with their old value. Flushing cache-2 before re-adding it removes the stale reads at the price of 13,497 misses. Other fixes are short TTLs (time to live: an expiry time on each cached value), which bound how long a stale value can live, and version numbers checked on read. Another option is to turn automatic ejection off: a failing server then just produces misses until an operator replaces it, and the server list changes only through a coordinated rollout to every client.

04. Step 3: Cap hot spots with bounded loads

Consistent hashing balances keys, not traffic. Product pages are far from equally popular, so the servers owning the bestsellers work hardest. Consistent hashing with bounded loads (Mirrokni, Thorup and Zadimoghaddam) sets a cap of c times the average load per server; a request whose home server is full walks on to the next server with room. HAProxy offers it as hash-balance-factor with hash-type consistent, counting concurrent requests, and Envoy as hash_balance_factor for both ring hash and Maglev. The script models 600 requests in flight with a skewed popularity (the key ranked r gets weight 1/r) over 200 moments. For simplicity it fixes the cap from the total of each moment, where real proxies use live counts.

Python 3.12 · ring-lab/bounded.py (needs ring.py from the lab)
"""Bounded loads: no server may hold more than c x the average requests in flight."""
import itertools
import math
import random

from ring import HashRing

SERVERS = [f"cache-{i}" for i in range(6)]
KEYS = [f"product:{i}" for i in range(60_000)]
CUM = list(itertools.accumulate(1 / rank for rank in range(1, len(KEYS) + 1)))
IN_FLIGHT = 600  # requests in progress at one moment
ring = HashRing(SERVERS, vnodes=160)


def place(c: float | None, rng: random.Random) -> tuple[int, int]:
    """Place one moment's requests; return the busiest load and how many moved."""
    cap = math.inf if c is None else math.ceil(c * IN_FLIGHT / len(SERVERS))
    load = dict.fromkeys(SERVERS, 0)
    away = 0
    for key in rng.choices(KEYS, cum_weights=CUM, k=IN_FLIGHT):  # popular keys win
        # Walk clockwise from the key; take the first server under the cap.
        server = next(s for s in ring.walk(key) if load[s] < cap)
        load[server] += 1
        away += server != ring.owner(key)
    return max(load.values()), away


average = IN_FLIGHT / len(SERVERS)
for c in (None, 1.5, 1.25):
    rng = random.Random(42)  # the same 200 moments for every setting
    busiest, away = zip(*(place(c, rng) for _ in range(200)))
    label = "no bound" if c is None else f"c = {c}"
    print(f"{label:<9} busiest server {max(busiest) / average:.2f}x the average,",
          f"{sum(away) / (200 * IN_FLIGHT):.1%} of requests served off their home")
Terminal · ring-lab/
python3 bounded.py
Expected output
no bound  busiest server 1.81x the average, 0.0% of requests served off their home
c = 1.5   busiest server 1.50x the average, 1.1% of requests served off their home
c = 1.25  busiest server 1.25x the average, 5.3% of requests served off their home

Without a bound, the busiest server reaches 1.81 times the average at the worst moment. A factor of 1.25 holds it to exactly the cap, but 5.3% of requests are served away from their home server, and on a cache each of those can be a miss, after which the value sits on two servers. The factor is a dial between even load and cache affinity; HAProxy's documentation calls 125 to 200 reasonable. Bounded loads cannot make one key cheaper, though: if a single key needs more than a server can give, spread its reads with the techniques in Surviving stampedes and hot keys.

05. Step 4: Place the store's replicas

The order store follows the Dynamo design: each key's preference list is the first three distinct nodes clockwise, and the paper spreads each list across data centres. The paper also reports a lesson worth copying. Dynamo started with random tokens per node and moved to a fixed number of equal-sized partitions, with tokens assigned so that each node holds the same number. Balance improved, the membership data that each node regularly exchanges with a few random peers (gossip) shrank by about three orders of magnitude, and a partition could be moved as a single file.

Other systems land in similar places. Redis Cluster does not use a ring: it hashes each key into one of 16,384 slots (CRC16 of the key, mod 16,384) and moves whole slots between nodes. A hash tag such as {user:42} puts related keys in one slot, because most multi-key commands fail with a CROSSSLOT error when their keys sit in different slots. Cassandra 5.0 keeps a token ring with 16 virtual nodes per node by default, and its NetworkTopologyStrategy tries to place a key's replicas in different racks. ScyllaDB now distributes data in tablets by default, small ranges that a balancer moves between nodes automatically.

Placement by zone has a trap of its own. With one copy per zone, every zone holds a full copy of the data, however many nodes it has. The script compares three zones of three nodes with zones of five, two and two.

Python 3.12 · ring-lab/zones.py (needs ring.py from the lab)
"""Three replicas, one per zone, walking the ring. What if zones differ in size?"""
from collections import Counter

from ring import HashRing

KEYS = [f"order:{i}" for i in range(30_000)]


def place(layout: dict[str, int]) -> None:
    zone_of = {f"{z}{i}": z for z, size in layout.items() for i in range(size)}
    ring = HashRing(list(zone_of), vnodes=100)
    copies = Counter()
    for key in KEYS:
        zones_used = set()
        for node in ring.walk(key):  # clockwise; skip zones that have a copy
            if zone_of[node] not in zones_used:
                zones_used.add(zone_of[node])
                copies[node] += 1
                if len(zones_used) == 3:
                    break
    print(" / ".join(f"{z}: {n}" for z, n in layout.items()), "nodes")
    for zone in layout:
        held = [copies[n] / len(KEYS) for n in zone_of if zone_of[n] == zone]
        low, high = min(held), max(held)
        print(f"  {zone} nodes: each holds {low:.0%} to {high:.0%} of the keys")


place({"a": 3, "b": 3, "c": 3})
place({"a": 5, "b": 2, "c": 2})
Terminal · ring-lab/
python3 zones.py
Expected output
a: 3 / b: 3 / c: 3 nodes
  a nodes: each holds 33% to 35% of the keys
  b nodes: each holds 33% to 34% of the keys
  c nodes: each holds 31% to 37% of the keys
a: 5 / b: 2 / c: 2 nodes
  a nodes: each holds 18% to 22% of the keys
  b nodes: each holds 48% to 52% of the keys
  c nodes: each holds 45% to 55% of the keys

With equal zones, each node holds about a third of the keys, R/N as expected. With five, two and two nodes, each node in the small zones holds about half of all keys, against about a fifth in the large zone: about two and a half times the disk, memory and request load. Keep zones (or racks) the same size, or give nodes in small zones bigger machines.

06. Check your understanding

Practice check · 3 questions

Rings in production

Three questions about ejection, bounded loads and zones.

Q1. A memcached client ejects a server after failed calls and re-adds it 60 seconds later. The server only had a network blip and never restarted. During that minute the app updated some products and deleted their cached copies. What can readers see once the server is back?
Q2. HAProxy balances requests over 8 cache servers with `hash-type consistent` and `hash-balance-factor 125`. What does this setting give you, and what does it cost?
Q3. A store keeps one copy of each key in each of three zones by walking the ring and skipping zones that already hold a copy. Zones A and B have 4 nodes each; zone C has 2. Roughly what share of all keys does each zone C node hold?
Practice only: not graded, not saved, not evidence.

07. Apply it

Finish your practice report with a short operating plan for a cache tier of your choice. Name the client library and the setting that selects consistent hashing, say how server-list changes reach every client, and choose what happens when a node is ejected and returns. Rerun cache_tier.py with a TTL (give each cached value an expiry time) and report how the stale reads change. Then run zones.py with the layout of a cluster you know, or of a cloud region with three zones.

08. Review prompt

Without looking back, list what every client of a memcached pool must agree on, explain why re-adding an ejected node can serve stale data and two ways to prevent it, describe what bounded loads trade, and explain why a small zone's nodes carry more data under one-copy-per-zone placement.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check