MLOpsModel Deployment & CI/CD Automation

How do you make a production ML inference result cache resilient to outages without causing cascading inference failures?

Question 144 of 164 · Updated

On this page

Why cache resilience is an inference reliability problem#

A prediction-result cache can reduce GPU work and improve latency, but it also becomes a dependency in the request path. If that dependency slows down, becomes unavailable, loses its data, or returns errors, an inference service can fail even while its model servers are healthy. Worse, a cache outage can remove the protection that was keeping the GPU fleet within capacity. Requests that previously completed as cheap cache hits suddenly become expensive model executions.

The goal is not to make the cache impossible to fail. The goal is to define safe behavior for cache degradation, protect inference capacity, recover without a traffic avalanche, and prove that cache failure cannot silently violate prediction correctness.

This lesson follows Question 143, which focused on whether a cached prediction is valid: complete cache keys, model and feature versions, tenant boundaries, TTL, invalidation, and result correctness. This lesson focuses on operating the cache dependency under failure: timeout budgets, circuit breakers, bounded bypass, capacity reserves, cold-cache recovery, multi-zone behavior, and failure testing. It also differs from Question 128's general inference fallback policies by concentrating on the cache-to-inference load transition.

1. Map the cache dependency and its failure modes#

Start by drawing the real request path. A common online inference path is:

  • API gateway authenticates and validates the caller.
  • Inference service resolves model, preprocessing, feature, and policy versions.
  • Cache client performs a network read.
  • A valid hit returns the cached prediction.
  • A miss invokes feature retrieval and model execution.
  • Successful eligible output is written to the cache.
  • The response and required audit or billing records are completed.

For each cache operation, identify its failure modes:

  • Connection failure: cache node, network path, DNS, TLS, or connection pool is unavailable.
  • Latency degradation: cache responds, but slowly enough to consume the request's deadline.
  • Partial cluster failure: some shards or replicas are healthy while others are unavailable.
  • Eviction or memory pressure: entries disappear faster than expected, causing miss rates to rise.
  • Cold start or failover: a replacement node or region has little or no warm data.
  • Stale or malformed value: cache returns data that fails schema, version, freshness, or integrity validation.
  • Write failure: inference succeeds but cache population fails.
  • Control-plane failure: scaling, failover, configuration, or routing changes do not complete correctly.
  • Traffic correlation: cache errors or mass expiration affect many keys and callers at the same time.

Classify the cache as an optimization dependency only if the service can safely execute without it under a controlled load budget. If the cache stores the only durable copy of a prediction or operation state, it is not merely a cache and must not be treated as disposable. Durable idempotency state and business records belong in an appropriate persistent store, not solely in an evictable result cache.

2. Define fail-open and fail-closed behavior per prediction class#

“Fail open” means a cache read or write failure does not automatically fail the API request; the service may continue through the normal inference path. “Fail closed” means the service rejects or defers the request rather than bypassing the cache.

Neither is universally correct.

  • Low-risk, recomputable predictions: fail open may be appropriate if the inference fleet has reserved capacity for cache bypass.
  • High-volume recommendations or ranking: fail open without a concurrency budget can overwhelm GPU workers. Prefer controlled bypass, queueing, or partial service.
  • High-risk decisions with strict freshness: never substitute an old cached result simply because the cache is unhealthy. Recompute from authoritative inputs if capacity and freshness permit; otherwise reject or defer safely.
  • Workloads where the cache is required for privacy isolation or policy enforcement: do not bypass a missing security control. Authorization and tenant checks must remain enforced independently of cache availability.
  • Side-effecting decisions: a cache hit or miss must not duplicate downstream actions. Keep operation idempotency and durable side-effect records separate from cache state.

Document a decision matrix for each endpoint: whether cache read failure permits inference, whether write failure is tolerable, whether stale values are ever allowed, the maximum bypass rate, and what response is returned when that budget is exhausted.

A cache outage should not turn into “all requests go directly to the GPU.” It should turn into a deliberately bounded degraded mode.

3. Put strict timeout budgets around cache operations#

A cache is usually expected to be faster than inference. Do not let a slow cache consume the entire API deadline.

Set separate budgets for:

  • Connection establishment and pool acquisition.
  • Cache read.
  • Optional stale-value or replica lookup.
  • Cache write after inference.
  • Any failover or retry attempt.

For example, suppose the endpoint has a 500 ms end-to-end deadline. Authentication, feature resolution, model execution, and response serialization need 420 ms at the target percentile. A cache read budget might be 5 ms and a cache write budget 5 ms, leaving margin for network variation. These are illustrative values; derive actual budgets from measured latency and the endpoint's SLO.

Use the remaining request deadline, not a fixed timeout that can exceed it. If the cache call times out, stop waiting and follow the endpoint's defined degraded-mode policy. Do not retry a cache request repeatedly within a short inference deadline. A second cache attempt may cost more than it can save.

Use bounded connection pools and concurrency limits. An unbounded queue of requests waiting for cache connections can consume application threads and memory even when the cache itself is healthy. Monitor pool wait time separately from cache server latency.

4. Use a circuit breaker with a bounded recovery probe#

A circuit breaker prevents a struggling cache from receiving the full request load while it is unhealthy.

A practical state machine has three states:

  • Closed: normal cache reads and writes are allowed. Track consecutive failures or a rolling failure/latency window.
  • Open: cache calls are skipped for a cooldown period. Requests follow the endpoint's bounded bypass policy rather than waiting for a known-unhealthy dependency.
  • Half-open: allow a small number of probe calls. If they succeed consistently, close the breaker; if they fail, reopen it with a cooldown.

Important implementation details:

  • Use separate breakers for cache reads and writes if their failure impact differs. A write outage should not necessarily disable successful reads.
  • Consider per-shard or per-endpoint breakers when a cluster has independent failure domains. A single global breaker can disable healthy shards because one shard is unhealthy.
  • Use rolling windows and minimum sample counts. One isolated timeout should not trip a fleet-wide breaker.
  • Add jitter to cooldown and probe timing so every application replica does not probe simultaneously.
  • Limit half-open probes. A recovering cache should not receive a full traffic surge from every client at once.
  • Ensure breaker state is observable and its thresholds are configuration-controlled, reviewed, and tested.

A breaker is not a substitute for admission control. It protects the cache from repeated calls; it does not protect the GPU fleet from the traffic that bypasses it.

5. Bound cache-bypass traffic before it reaches model workers#

This is the most important protection against cascading inference failure.

Suppose an endpoint normally receives 8,000 requests per second. The cache hit rate is 75%, so 2,000 requests per second reach inference. If the cache fails, the miss path could suddenly receive all 8,000 requests per second: a 4x increase.

If the model fleet can safely execute only 2,500 requests per second, sending all 8,000 requests through it creates queues, deadline misses, retries, and further overload.

Use several controls together:

  • Bypass token bucket: allocate a maximum rate of cache-bypass requests. Tokens refill at a rate aligned with safe inference capacity.
  • Concurrency bulkhead: cap concurrent cache-miss inference independently from normal traffic.
  • Admission control: reject or defer excess requests before expensive feature retrieval and model execution.
  • Priority classes: preserve capacity for critical tenants or high-value operations, using explicit fairness rules rather than allowing one tenant to consume all bypass tokens.
  • Queue limits: keep waiting work bounded by both queue depth and remaining deadline. Drop expired work rather than building an unbounded backlog.
  • Autoscaling with limits: scale workers when safe, but do not assume new GPU capacity will arrive quickly enough to absorb an immediate cache outage.
  • Load shedding: return a clear retryable response or controlled degraded result only where the API contract allows it.

Keep a reserved cache-bypass capacity budget even during normal operation. If the entire GPU fleet is already saturated by cache misses at peak traffic, the cache has become a hidden single point of failure.

6. Use stale data only under an explicit freshness contract#

Some systems use a soft TTL and hard TTL:

  • Before the soft TTL, an entry is considered fresh.
  • Between soft and hard TTL, the entry is stale but may be served under an approved degraded-mode policy while refresh is attempted.
  • After hard TTL, the entry must not be served.

This can improve availability for workloads where bounded staleness is acceptable. It is not a universal fallback.

For an illustrative recommendation endpoint, an entry might have a 30-second soft TTL and a 120-second hard TTL. If the cache refresh path fails at 45 seconds, the service may serve the old recommendation only if the product owner has explicitly accepted that freshness window. A payment authorization or current inventory decision may not permit this at all.

Apply these controls:

  • Record source model digest, feature snapshot, policy version, creation time, and freshness metadata with every entry.
  • Validate tenant scope and authorization on every request, including stale reads.
  • Never serve an entry beyond the hard freshness limit.
  • Never serve stale data across a model or policy version boundary unless that exact compatibility has been reviewed.
  • Do not silently convert a cache error into permission to serve a stale high-risk decision.
  • Measure stale response rate and age; alert on the hard-limit boundary and any unexpected stale use.

The cache's stale mode must preserve the same correctness constraints as the normal cache-hit path described in Question 143.

7. Design cache topology and failover around failure domains#

A distributed cache can improve availability, but replicas and multi-zone deployments introduce their own consistency and recovery trade-offs.

  • Place cache nodes across independent availability zones when the platform supports it.
  • Understand whether replication is synchronous or asynchronous, and what data may be lost during failover.
  • Treat replicas as read sources only when their replication lag is within the endpoint's freshness budget.
  • Avoid sending all traffic to one replica after a primary failure. Use bounded failover and health-aware routing.
  • Use consistent hashing or managed sharding so adding nodes does not remap the entire key space unnecessarily.
  • Set client-side connection and command timeouts so a failed node does not stall requests while topology changes.
  • Test what happens when one shard, one zone, or the whole cache fleet disappears.

Do not assume replication makes a cache durable. Result-cache entries should be recomputable, and cache recovery should not depend on perfect preservation of every entry. Durable operation state, audit evidence, and business outcomes must live in durable stores with their own recovery guarantees.

8. Recover from a cold cache without creating a second outage#

After a cache restart, failover, reshard, or flush, the hit rate may fall sharply. This is a cold-cache event. If every miss becomes a GPU call, recovery can be worse than the original outage.

Use a staged recovery plan:

  • Keep cache bypass rate limits active while the cache warms.
  • Prioritize prewarming for high-frequency, safe-to-cache keys and model releases.
  • Use representative production distributions, not synthetic values that create unrealistic key patterns.
  • Spread refreshes over time with jitter.
  • Apply per-tenant and per-model warmup budgets.
  • Allow normal traffic to populate cold entries gradually.
  • Increase bypass capacity only after cache latency, hit rate, and inference utilization stabilize.
  • Keep a kill switch for cache writes if population traffic competes with production reads or model execution.

Avoid warming every historical key. Large warmups can consume network, CPU, memory, and GPU resources while populating entries that will never be read.

For model rollout, warm the new model namespace with a limited set of high-value inputs only after the model is ready and its cache identity is pinned. Do not mix old-model entries into a new release just to improve its initial hit rate.

9. Numerical example: cache failure and safe bypass#

Assume:

  • Incoming request rate: 8,000 requests/second.
  • Normal cache hit rate: 75%.
  • Normal inference capacity: 2,500 requests/second at the target latency.
  • Cache read latency: 2 ms at P95.
  • Average model execution: 35 ms.

During normal operation:

  • Cache hits: 8,000 × 75% = 6,000 requests/second.
  • Inference misses: 8,000 − 6,000 = 2,000 requests/second.
  • The model fleet has 500 requests/second of spare capacity.

Now the cache becomes unavailable:

  • Naive fail-open sends 8,000 requests/second to inference.
  • The fleet can execute only 2,500 requests/second.
  • Excess offered load is 8,000 − 2,500 = 5,500 requests/second.
  • Queues grow, deadlines expire, clients retry, and the retry traffic can make overload worse.

A controlled bypass policy caps inference at 2,200 requests/second, leaving 300 requests/second of headroom for critical traffic and operational variance:

  • Admit 2,200 requests/second to inference.
  • Reject or defer up to 5,800 requests/second according to the API's priority and retry contract.
  • Keep the queue bounded; do not hold thousands of requests until their deadlines have already expired.

When the cache recovers, begin with a small number of health probes and gradually restore cache reads. Do not instantly admit all waiting requests or remove the bypass token limit. This protects the recovering cache and GPU fleet from a synchronized surge.

10. Failure scenarios and debugging#

  • Cache node failure causes GPU saturation: compare cache error rate with miss-path request rate, queue depth, GPU utilization, and deadline misses. Confirm the bypass token bucket and inference bulkhead are active. Reduce admitted miss traffic and shed excess load.
  • Cache latency rises but health checks remain green: inspect P95/P99 command latency, connection-pool wait, network retransmits, shard hot spots, and slow commands. A binary health check is insufficient. Trip latency-based protection where appropriate.
  • Circuit breaker flaps between open and closed: inspect probe concurrency, cooldown, minimum sample count, and recovery jitter. Increase hysteresis and keep half-open probes small.
  • All application replicas probe simultaneously: inspect synchronized cooldown timers. Add randomized probe delays and a shared or partitioned probe budget.
  • Cache failover sends stale data: inspect replica lag, entry model and feature versions, and whether stale reads were permitted. Reject entries outside the freshness contract.
  • One shard outage disables the entire cache: inspect breaker scope and client routing. Isolate shard health and avoid a global breaker when independent partitions can continue safely.
  • Cold start overloads the GPU fleet: inspect cache warmup rate, miss rate by model version, and bypass admission. Stage warmup and cap inference misses until the hit rate recovers.
  • Cache writes fail after successful inference: ensure the prediction response can still complete when write failure is noncritical. Record write failures and let later requests recompute. Do not retry writes indefinitely.
  • Cache outage triggers client retry storm: inspect status codes, retry-after behavior, client backoff, and idempotency. Return explicit overload responses with bounded retry guidance. Do not tell clients to retry immediately.
  • Cache recovery creates a thundering herd: inspect simultaneous probes, expired hot keys, and queued refresh jobs. Add jitter, request coalescing, staged traffic restoration, and bounded refresh concurrency.

11. Monitoring and alerting#

Instrument the cache and inference service as one system. Track:

  • Cache read and write success/error rates separately.
  • Cache command P50/P95/P99 latency and client connection-pool wait.
  • Circuit breaker state, transitions, half-open probes, and open duration.
  • Cache bypass request rate, admitted and rejected bypass requests, and token-bucket exhaustion.
  • Inference concurrency, queue depth, queue wait, GPU utilization, throughput, and deadline misses.
  • Cache hit rate by endpoint, model digest, tenant tier, and cache namespace.
  • Cache memory, evictions, replication lag, shard health, connection count, and failover events.
  • Cold-cache miss rate, warmup rate, and time to recover normal hit rate.
  • Stale responses served, stale responses rejected, and age distribution.
  • Client retries, retry-after compliance, and duplicate operation rates.

Avoid using raw tenant IDs, user IDs, or input payloads as unbounded metric labels. Use approved aggregation and privacy-safe identifiers.

Create alerts for leading indicators:

  • Cache P99 latency approaches the cache timeout budget.
  • Read error rate increases while bypass traffic approaches its cap.
  • Inference queue depth grows while cache hit rate drops.
  • GPU utilization and deadline misses rise together during cache degradation.
  • Breaker remains open beyond the recovery objective.
  • Cache replica lag exceeds the maximum permitted freshness lag.
  • Warmup traffic consumes the reserved production inference capacity.

A single cache hit-rate alert is not enough. A lower hit rate can be harmless at low traffic, while a moderate hit rate can be dangerous if the miss path is near capacity.

12. Production engineering trade-offs#

  • Fail open vs fail closed: fail open preserves availability for recomputable predictions but risks overload. Fail closed protects capacity and strict correctness but reduces availability. Decide per endpoint and load budget.
  • Stale-while-revalidate vs strict freshness: stale reads can preserve availability for tolerant workloads but may violate model or business freshness. Use explicit soft and hard TTLs only where approved.
  • Global vs per-shard breakers: global breakers are simple but can disable healthy partitions. Per-shard breakers isolate faults but increase state and routing complexity.
  • Replicas vs cost and consistency: replicas improve read capacity and zone resilience but may return lagging values and add operational cost. Enforce a lag limit.
  • Prewarming vs live traffic: warmup reduces cold misses but competes for resources and can fill the cache with low-value keys. Prioritize measured hot keys and rate-limit warming.
  • Large bypass reserve vs normal efficiency: reserving capacity for cache failure can leave some GPU capacity unused in normal operation. That reserve is an availability investment; tune it from failure-mode testing and business criticality.
  • Aggressive retries vs dependency recovery: retries can mask brief faults but amplify overload. Prefer bounded attempts, deadlines, jitter, and circuit breaking.

13. Common mistakes#

  • Treating the cache as a hard dependency while calling it an optimization.
  • Allowing unlimited fail-open traffic to reach GPU workers.
  • Setting cache timeouts equal to the entire API deadline.
  • Retrying cache reads repeatedly during a cache outage.
  • Using a single global breaker for a partially healthy sharded cluster.
  • Allowing every replica to probe a recovering cache at once.
  • Assuming replicas make cache contents durable or perfectly current.
  • Serving stale results without checking model, feature, policy, tenant, and age metadata.
  • Warming the entire key space after failover.
  • Disabling admission control because the cache is expected to protect the model fleet.
  • Measuring hit rate without miss-path capacity, queue depth, and P99 latency.
  • Forgetting that write failures may be nonfatal while read failures can trigger expensive inference.
  • Returning generic 500 errors that cause clients to retry immediately.
  • Failing to test cache-disabled operation at realistic peak load.

14. CI/CD, resilience and game-day tests#

Make cache dependency behavior a release gate, not an operational afterthought.

  • Read timeout test: inject cache read latency beyond the configured budget. Verify the API stops waiting and follows the endpoint's bypass policy.
  • Write failure test: make cache writes fail after successful inference. Verify the request returns correctly when writes are optional and that failures are observable.
  • Whole-cache outage: block all cache traffic. Verify bypass rate, inference concurrency, queue depth, and rejection rates remain within defined limits.
  • Partial-shard failure: disable one shard and verify healthy shards continue if the topology supports isolation.
  • Circuit-breaker test: inject consecutive failures, verify open state, bounded half-open probes, and gradual recovery.
  • Cold-cache test: flush a test namespace or deploy an empty cache. Verify warmup and production traffic cannot exceed inference capacity.
  • Replica-lag test: introduce lag and verify entries beyond the freshness limit are rejected.
  • Stale-policy test: expire soft TTL, simulate origin failure, and verify only approved endpoints can serve stale values before hard TTL.
  • Retry-storm test: simulate clients retrying on timeout and overload responses. Verify retry budgets, backoff, and idempotency prevent amplification and duplicate side effects.
  • Deadline test: ensure cache calls, bypass admission, and queue waits consume the same end-to-end deadline budget.
  • Tenant fairness test: simulate one tenant generating high cache-miss traffic. Verify it cannot consume all bypass capacity.
  • Recovery test: restore the cache and verify gradual probe success, traffic ramp-up, and no sudden GPU or cache saturation.
  • Capacity test: run realistic peak traffic with cache disabled. Measure the maximum safe bypass rate and set the production admission budget below that value.

Run these tests in staging and controlled game days. Record expected signals, abort thresholds, owners, and rollback actions. A test is successful only when the system remains within its SLO or degrades in the documented way—not merely because the cache process restarts.

15. Operational runbook checklist#

When the cache becomes unhealthy:

  1. Confirm whether the issue is read latency, write failure, a shard, a zone, or the whole cache fleet.
  2. Check cache breaker state, connection pools, replication lag, and node memory.
  3. Confirm the inference bypass cap and bulkheads are active.
  4. Preserve capacity for critical traffic; reject or defer excess work before expensive inference.
  5. Disable unsafe stale reads and keep authorization and idempotency checks active.
  6. Stop or rate-limit cache warmup and refresh jobs if they compete with live inference.
  7. Restore cache nodes and verify health using a small, bounded probe set.
  8. Gradually increase cache traffic while watching miss rate, inference utilization, queue depth, and P99 latency.
  9. Reconcile any cache entries with invalid model or policy versions; never repopulate from untrusted or stale sources.
  10. Complete a post-incident review and add a regression test for the failure mode.

The central rule is: a cache outage must not turn a protected inference fleet into an unbounded miss-processing system. Define the cache's failure behavior, reserve and enforce inference capacity, and restore traffic gradually while preserving the freshness and security rules from Question 143.

Related questions

Explore other topics:Machine LearningRetrieval-Augmented GenerationAI Agents