Node Loss, Consistent Hashing and Cold Cache Recovery

Article · 9:00

What node loss means with no replication, consistent hashing in practice, cold cache recovery planning, warming, and designing for the absence of durable backup.

This lesson has 1 runnable example. Press Try yourself! under any of them to open it in the editor.

Start from the honest position: there is no backup and no replication, by design. When a Memcached node is lost, its data is gone. There is nothing to restore, no replica to promote and no snapshot to load. Discussions of RPO and RTO therefore work differently here: the RPO for cached data is total loss, always, and the only meaningful RTO is how long your system takes to work acceptably again with an empty cache.

That reframing is the module's point. Reliability in Memcached is not about protecting the cache - it is about your system's behaviour when the cache is not there.

Node loss, concretely. With consistent hashing, losing one node of N invalidates about 1/N of the keys. Those requests miss and read through to the source of truth, so the database sees a sudden step up in load - 20% of your cached read volume arriving at once. Whether that is survivable is a capacity question you should have answered in advance, and the answer is usually "only because of the other defences": coalescing stops the duplicate queries, jitter spreads the repopulation, and serve-stale does nothing because the stale value was on the lost node too.

Automatic failover is a client decision and it has a trap. A client with a dead_timeout will stop asking a failed node and redistribute its keys to the remaining nodes. That keeps the hit ratio up - and when the node returns, those keys exist in two places, and the stale copies on the recovered node become reachable again. The safer configuration for correctness is to leave the failed node in the ring and accept misses for its share, so no key ever lives in two places. Which you choose depends on whether a stale read is worse than a miss, and it should be a decision rather than a default.

Cold cache recovery deserves a plan, because it happens routinely: a node replacement, a restart, a configuration change, a deployment that changes the key namespace, or someone running flush_all. The techniques:

  • Warming - populate the cache before sending traffic, by replaying known-popular keys. This requires knowing what is popular, which means recording it.
  • Gradual traffic ramp - send 5% of traffic, let the cache fill, then 25%, then all. This is the most reliable approach and needs load-balancer cooperation.
  • Admission rate limiting - cap the number of concurrent cache-fill database queries so a cold cache degrades latency rather than killing the database.
  • A second cache tier - a small in-process cache in each application instance, which survives independently of Memcached and absorbs the hottest keys. This is genuinely effective and the cost is per-instance staleness.

The test that matters is simple and is the laboratory: with production-shaped load running, flush the cache and watch. Either the system degrades and recovers, or it does not. A system that cannot survive a cold cache does not have a cache - it has an undeclared dependency, and the difference only becomes visible at the worst moment.

Laboratory exercise 5 - lose a node, then lose everything.

Build a five-node pool with consistent hashing and a load test at production shape.

Lose one node. Measure the hit ratio before and after, the database query rate step, and the latency percentiles. Then bring it back and measure the recovery, including whether any stale value became visible again.

Demonstrate the redistribution trap: configure a dead_timeout so keys redistribute, write to a redistributed key, bring the node back, and show the stale value on the recovered node being served. Then configure the safer behaviour and show the trade.

Then the central experiment: flush_all under full production load. Measure the database query rate, the latency percentiles, the error rate, and the time to return to the baseline hit ratio. Do this with none of the Module 3 defences, then with all of them, and compare.

Implement and measure three recovery techniques: warming from a recorded popular-key list, a gradual traffic ramp, and admission rate limiting on cache fills.

Add a small in-process cache tier and measure its effect on the cold-cache test.

Finally, write the runbook: node replacement, cold start, and the capacity statement - how much database load an empty cache produces, and whether your database can take it.

Deliverable: the node loss measurements, the redistribution trap demonstrated both ways, the full cold cache test with and without defences, the three recovery techniques measured, the in-process tier comparison, and a runbook containing the capacity statement.

PY Example 1 195 lines
# ==================================================================
# THE HONEST POSITION FIRST.
# ==================================================================
# No backup. No replication. By design.
#
#   RPO for cached data   = TOTAL LOSS, always
#   RTO                   = how long your SYSTEM takes to work
#                           acceptably again WITH AN EMPTY CACHE
#
# Reliability here is NOT about protecting the cache. It is about
# YOUR SYSTEM'S BEHAVIOUR WHEN THE CACHE IS NOT THERE.

# ==================================================================
# CONSISTENT HASHING, and the REDISTRIBUTION TRAP.
# ==================================================================
from pymemcache.client.hash import HashClient

# OPTION A - keys REDISTRIBUTE when a node dies.
mc_redistribute = HashClient(
    [("10.0.1.5", 11211), ("10.0.1.6", 11211), ("10.0.1.7", 11211),
     ("10.0.1.8", 11211), ("10.0.1.9", 11211)],
    use_pooling=True, ignore_exc=True,
    timeout=0.2, connect_timeout=0.2,
    retry_attempts=2, retry_timeout=1,
    dead_timeout=30,          # stop asking; REDISTRIBUTE its keys
)
# Keeps the hit ratio up. AND THE TRAP:
#   t0  key K lives on node 3
#   t1  node 3 dies; K redistributes to node 4; the app WRITES a new
#       value for K to node 4
#   t2  NODE 3 COMES BACK. K now exists on BOTH, and node 3's copy
#       is STALE - and reachable again.
#   -> a STALE READ, with no error anywhere.

# OPTION B - LEAVE the failed node in the ring. Accept MISSES for its
# share. No key ever lives in two places.
mc_strict = HashClient(
    [...], ignore_exc=True, timeout=0.2,
    dead_timeout=0,           # never remove from the ring
)
#
# WHICH ONE depends on whether a STALE READ is worse than a MISS for
# your data. For a price, yes. For a product description, no. MAKE IT
# A DECISION, not a default - and demonstrate both in the lab.

# ==================================================================
# NODE LOSS, concretely.
# ==================================================================
#   5 nodes, consistent hashing, lose 1
#   -> ~20% of keys gone
#   -> those requests read through
#   -> THE DATABASE SEES A STEP UP OF 20% OF YOUR CACHED READ VOLUME,
#      ARRIVING AT ONCE
#
# Survivable? That is a CAPACITY QUESTION you should have answered in
# advance. And the answer is usually "only because of the other
# defences":
#     coalescing   stops the duplicate queries
#     jitter       spreads the repopulation
#     serve-stale  DOES NOTHING - the stale value was on the lost
#                  node too. Worth noticing: the defences are not
#                  independent.

# ==================================================================
# THE TEST THAT MATTERS. Do this.
# ==================================================================
#   1. run production-shaped load
#   2. `flush_all`
#   3. WATCH
#
# Either the system degrades and recovers, or it does not. A SYSTEM
# THAT CANNOT SURVIVE A COLD CACHE DOES NOT HAVE A CACHE - IT HAS AN
# UNDECLARED DEPENDENCY, and the difference only becomes visible at
# the worst possible moment.
#
# And it is NOT a rare event. It happens on: a node replacement, a
# restart, a configuration change, a deployment that changes the key
# namespace, an instance resize, and someone running flush_all.
#
#   echo "flush_all" | nc localhost 11211
#   -> OK
#   measure: DB query rate, p50/p95/p99, error rate, and TIME TO
#            RETURN TO BASELINE HIT RATIO
#   Run it with NONE of the Module 3 defences, then with ALL of them.

# ==================================================================
# RECOVERY TECHNIQUE 1: WARMING.
# ==================================================================
# Needs to know what is popular, which means RECORDING it.
def record_popular(sku):
    mc.incr(f"popularity:{sku}", 1) or mc.add(f"popularity:{sku}", b"1",
                                              expire=86400)
    # ... and persist the top N to durable storage periodically,
    #     because the popularity counters are in the cache too, and
    #     a flush loses them as well. That is the joke, and it is a
    #     real mistake people make.

def warm_cache(popular_skus, batch=100):
    for i in range(0, len(popular_skus), batch):
        chunk = popular_skus[i:i+batch]
        rows = db_read_products(chunk)      # ONE query per batch
        mc.set_many({f"catalogue:{ns('catalogue')}:product:{s}":
                     json.dumps(r) for s, r in rows.items()},
                    expire=jittered())
        time.sleep(0.05)                    # do not stampede yourself
# Warming with no throttle IS a stampede you scheduled.

# ==================================================================
# RECOVERY TECHNIQUE 2: GRADUAL TRAFFIC RAMP. The most reliable.
# ==================================================================
#   send 5%  -> cache fills, DB load modest
#   send 25% -> hit ratio climbing
#   send 100%
# Needs load-balancer cooperation (weights, or a readiness probe
# that reports "warming"). Of the three, this is the one that
# actually works at scale, because it bounds the DB load directly
# rather than hoping.

# ==================================================================
# RECOVERY TECHNIQUE 3: ADMISSION RATE LIMITING ON CACHE FILLS.
# ==================================================================
import threading
fill_semaphore = threading.Semaphore(20)    # max 20 concurrent fills

def read_rate_limited(sku):
    key = f"catalogue:{ns('catalogue')}:product:{sku}"
    cached = mc.get(key)
    if cached is not None:
        return json.loads(cached)

    if not fill_semaphore.acquire(blocking=False):
        # At the limit. DEGRADE rather than queue:
        #   return a placeholder, a stale value, or 503 with Retry-After
        return degraded_response(sku)
    try:
        row = db_read_product(sku)
        if row is not None:
            mc.set(key, json.dumps(row), expire=jittered())
        return row
    finally:
        fill_semaphore.release()
# A cold cache now DEGRADES LATENCY instead of KILLING THE DATABASE.
# That is the trade, and it is almost always the right one: a slow
# site recovers, a dead database does not.

# ==================================================================
# RECOVERY TECHNIQUE 4: A SECOND, IN-PROCESS TIER.
# ==================================================================
from functools import lru_cache
# A small per-instance cache that SURVIVES INDEPENDENTLY of
# Memcached. It absorbs the hottest keys during a cold start, and it
# is genuinely effective - often the difference between surviving a
# flush and not.
#
#   L1: in-process, 1-5 s TTL, a few thousand entries
#   L2: Memcached,  300 s TTL
#   L3: the database
#
# The cost is PER-INSTANCE STALENESS: 40 application instances means
# 40 independent copies, each up to its L1 TTL out of date, and no
# way to invalidate them. So keep the L1 TTL very short (seconds) and
# use it only for data where seconds of staleness is fine.

# ==================================================================
# THE RUNBOOK, including the CAPACITY STATEMENT.
# ==================================================================
#  NODE REPLACEMENT
#   1. check pool health; confirm the hashing scheme is CONSISTENT
#   2. decide: redistribute (hit ratio) or hold the ring (no stale
#      reads). Record which, and why.
#   3. start the replacement; it joins EMPTY
#   4. warm it, throttled
#   5. add it to the ring
#   6. watch: hit ratio, DB query rate, p99, evicted_time
#
#  COLD START
#   1. confirm the DB can take the read-through load -> THE CAPACITY
#      STATEMENT BELOW
#   2. ramp traffic: 5% -> 25% -> 100%
#   3. keep fill admission limiting ON throughout
#   4. warm from the persisted popular-key list
#
#  THE CAPACITY STATEMENT - the number the runbook exists for:
#     steady state      12,000 reads/s, 98.7% hit  ->   156 DB qps
#     one node lost (5) 12,000 reads/s, 79% hit    -> 2,520 DB qps
#     COLD CACHE        12,000 reads/s,  0% hit    -> 12,000 DB qps
#     measured DB ceiling                          -> 3,500 qps
#
#     => A COLD CACHE EXCEEDS THE DATABASE BY 3.4x. Therefore the
#        ramp and the fill limiter are NOT optional - they are
#        load-bearing parts of the architecture, and the design
#        document must say so.
#
# That calculation, for your own system, is the single most valuable
# artefact this module produces.

Open this example in the editor and change it. Nothing you type is saved.

Discussion

No questions on this topic yet. Sign in to ask the first one.