MLOpsModel Deployment & CI/CD Automation

How do you size and scale a distributed prediction-result cache to control eviction, hot-key pressure, and cost in production ML inference?

Question 145 of 164 · Updated

On this page

Short answer#

Treat a prediction-result cache as a separately engineered serving tier with its own workload model, capacity budget, scaling signals, and failure limits. Size it from the *working set and access distribution*, not just total key count or average memory. Measure value bytes plus per-key, allocator, replication, connection, and operational overhead; leave headroom for skew, resharding, failover, and traffic bursts. Choose eviction behavior based on reuse patterns, detect hot keys and shard imbalance, and scale before eviction churn degrades the hit rate. Keep cache misses safe: the inference service must remain bounded when cache performance deteriorates.

This question follows Q143, which focused on cache correctness (freshness, key construction, tenant isolation), and Q144, which focused on surviving cache outages without cascading inference failures. Q145 addresses a different problem: how to engineer the *normal operating capacity and distribution* of a healthy cache fleet so that memory pressure, uneven load, and cost do not quietly destroy its value. It is also distinct from Q126, which plans model-serving compute capacity rather than cache storage and cache-node throughput.

1. Understand the workload before choosing a cache size#

A cache is useful when a meaningful portion of requests repeat within the useful lifetime of a result. Start by collecting:

  • Request rate by endpoint, tenant, model version, and traffic class.
  • Cacheable request fraction and observed hit ratio, not just theoretical duplicate rate.
  • Unique cache keys created per minute and the rate at which keys are revisited.
  • Value-size distribution: median, p95, p99, and maximum serialized result size.
  • Key popularity distribution: whether a small number of keys dominate reads or traffic is nearly uniform.
  • TTL distribution and actual time between first write and last read.
  • Read/write operations per second, network bytes, connection count, and command latency.
  • Per-shard memory, CPU, network, evictions, and request distribution.

Do not use one global average to size every workload. A recommendation model with a small result payload and repeated product IDs has a different working set from a fraud model whose feature vector and decision context create high-cardinality keys. A generative endpoint may produce large outputs and low repeat rates, making caching uneconomic even when the cache itself is fast.

Segment the workload by cache namespace or policy where practical. A noisy tenant or one endpoint should not consume the entire memory budget or dominate eviction decisions for unrelated traffic. This is an operational isolation concern; it does not replace the tenant-safe key construction and authorization controls described in Q143.

2. Estimate the working set and memory budget#

A first-order estimate is:

Resident memory ≈ resident key count × (average serialized value bytes + average key bytes + per-entry overhead)

Then add memory that is not represented by the raw payload estimate:

  • Redis/object metadata, allocator fragmentation, hash-table structures, expiration metadata, and internal buffers.
  • Replication overhead and memory reserved for client output buffers and connections.
  • Temporary memory during large writes, serialization, resharding, snapshots, or failover.
  • Safety headroom for traffic spikes and skewed shards.

Beginner-friendly numerical example#

Assume an inference endpoint receives 2,000 requests per second. Over the relevant 15-minute reuse window, the measured working set contains 600,000 distinct keys. Each entry averages:

  • Serialized prediction: 1.5 KB.
  • Key and namespace metadata: 0.2 KB.
  • Estimated in-memory object and allocator overhead: 0.8 KB.

Estimated memory per entry is 2.5 KB. The raw working-set estimate is:

600,000 × 2.5 KB = 1,500,000 KB, approximately 1.43 GiB.

That is not a safe cluster size. Suppose measured replication, buffers, fragmentation, and operational reserve add 40% to the required budget. The planning estimate becomes about 2.0 GiB. If the team chooses to operate at no more than 70% of usable data memory during normal peak traffic, provision roughly 2.9 GiB of usable cache capacity (2.0 / 0.70), then account separately for provider-specific replica and node constraints.

These figures are illustrative. Replace the overhead percentage and target utilization with measurements from the chosen engine and deployment topology. Measure actual memory per representative key by loading a realistic sample and inspecting memory usage; do not assume JSON payload size equals resident memory.

Model TTL and churn#

TTL determines how long an entry remains eligible for reuse; it is not a guarantee that the entry remains resident. If 40,000 new keys are created each minute and the useful TTL is 15 minutes, the steady-state upper bound is approximately 600,000 simultaneously live keys before accounting for early eviction, invalidation, or skew. If the TTL doubles, the live working set can roughly double under a stable arrival rate.

Use the observed key creation rate and the distribution of revisit times to choose TTL. A TTL longer than the typical revisit interval may improve hit ratio but consumes memory and can increase the risk of serving outdated predictions if invalidation/versioning is weak. A TTL shorter than the revisit interval wastes compute by expiring entries before they are reused. Correctness and freshness rules remain authoritative; do not lengthen TTL merely to improve a dashboard hit ratio.

3. Choose eviction policy from access behavior#

When memory reaches its configured limit, the cache must either evict entries or reject writes. The policy determines which entries are sacrificed.

  • Approximate LRU is a reasonable starting point when recent reuse predicts future reuse and a moving hot set exists.
  • Approximate LFU can be better when a stable set of popular predictions is repeatedly requested, while one-time keys should be removed.
  • TTL-based eviction can be useful when entries have meaningful, intentionally assigned expiry priorities, but it should not be mistaken for a freshness guarantee.
  • No-eviction / reject-write behavior avoids silently removing existing entries but turns memory exhaustion into cache-write errors. This is usually not a good default for a disposable result cache unless write failures are explicitly handled and the operational objective justifies it.

For Redis, policies such as allkeys-lru, allkeys-lfu, and noeviction have materially different behavior. LRU and LFU are approximations, not perfect global rankings. Redis documentation also notes that eviction happens when writes push memory beyond the configured limit; a large write can temporarily exceed it. Validate the exact engine/version and managed-service semantics before choosing a policy. See the Redis eviction documentation.

Do not combine durable application state and disposable prediction entries in one cache namespace or instance and hope that a single eviction policy protects both. Prefer separate stores or independently managed databases where persistent state has different retention and loss semantics.

4. Detect cache thrashing rather than celebrating a single hit-rate number#

A high hit ratio can hide a small number of very expensive misses, while a low hit ratio can be expected for a workload with little reuse. Evaluate cache value using:

  • Hit ratio by endpoint, tenant cohort, model version, and key class.
  • Miss rate and miss cost: additional model execution time, accelerator-seconds, and downstream feature-store calls.
  • Eviction rate and expired-key rate over time.
  • Memory utilization and fragmentation, including per-shard values.
  • Cache p50/p95/p99 read and write latency.
  • Number of unique keys, key churn, and reuse-distance distribution.
  • Estimated compute saved versus cache infrastructure cost.

A common warning pattern is rising memory utilization, high eviction rate, falling hit ratio, and increasing inference GPU utilization. This indicates the working set may not fit, the TTL may be too long, the key space may have become too diverse, or the cache may be poorly distributed. Increasing capacity can help, but first verify that the cache is actually serving reusable results and that key cardinality has not exploded because of an accidental field in the key.

Numerical cost example#

Suppose a cache serves 10 million lookups per day at a 65% hit ratio. That produces 6.5 million hits and 3.5 million misses. If a miss triggers 80 ms of accelerator time, the cache avoids approximately 6.5 million × 0.08 = 520,000 accelerator-seconds per day, before considering queueing and feature retrieval savings.

If the hit ratio falls to 30%, only 3 million hits remain, avoiding 240,000 accelerator-seconds. The lost benefit is 280,000 accelerator-seconds per day. Compare the value of that saved compute with the additional monthly cost of memory, replicas, network, and operations. Do not scale the cache simply to maximize hit ratio; scale when the marginal saved inference cost and latency are worth more than the additional cache cost and complexity.

5. Prevent hot keys and uneven shard distribution#

A distributed cache can show healthy *aggregate* memory utilization while one shard is overloaded. Causes include:

  • A highly popular key mapping to one shard.
  • Tenant or model identifiers with skewed hash distribution.
  • A key design that concentrates many related keys into one hash slot.
  • Large values or expensive serialization concentrated in a subset of keys.
  • A small number of endpoints issuing disproportionate read or write traffic.

Monitor per-shard memory, CPU, operations, network throughput, latency, and evictions. Do not rely solely on cluster-wide averages. Redis Enterprise documentation explicitly warns that individual shards can reach their memory limit and evict keys while overall database utilization is still below the configured limit. AWS ElastiCache guidance distinguishes scaling read operations (replicas), write operations (shards), and network capacity (network-optimized nodes or vertical scaling).

For read-heavy hot keys, consider a short-lived process-local L1 cache, request coalescing, or a bounded per-instance read-through cache. A five-second local cache can dramatically reduce repeated calls for an extremely popular immutable key, but only if freshness and invalidation requirements allow it. Local caches multiply memory across replicas and may return stale values until expiry, so use them only with explicit versioning or a sufficiently short bound.

For a hot key that must be read by many workers, consider controlled replication or application-level fan-out only when the cache engine and consistency requirements support it. Do not append random suffixes to a key without a design for writes, invalidation, and reading all replicas; naive key salting can create inconsistent copies and increase memory.

6. Scale the cache in the dimension that is constrained#

Use evidence to choose the scaling action:

  • Memory capacity is constrained: increase node memory or add shards, after confirming the working set is valuable and key distribution is sufficiently balanced.
  • Read throughput is constrained: add read replicas or use supported local read paths, while accounting for replica lag and the correctness tolerance of cached predictions.
  • Write throughput is constrained: add shards or improve write distribution; replicas alone do not solve primary write saturation.
  • CPU is constrained: inspect expensive commands, serialization, oversized values, connection churn, and hot keys before buying larger nodes.
  • Network is constrained: measure bytes per operation, payload size, client placement, and network throughput; more RAM alone may not help.
  • One shard is constrained: diagnose hash-slot and hot-key skew. Adding capacity to other shards will not automatically fix the hot shard.

Prefer incremental, tested scaling over waiting until the cache is near exhaustion. Resharding can consume CPU and network, move data, and temporarily affect latency. Test application behavior during resharding in staging and start the operation while there is headroom. AWS guidance recommends monitoring utilization and avoiding resharding under already high load.

For a cluster-mode deployment, plan for the possibility that key distribution is uneven and that a node failure changes available capacity. More, smaller nodes can reduce the blast radius of a single node failure, but they add coordination and operational overhead. Choose topology based on measured workload, recovery objectives, and provider limits rather than assuming more shards are always better.

7. Use admission and size controls for cache writes#

Not every inference result deserves to be cached. Apply admission rules such as:

  • Cache only endpoints and request classes with demonstrated reuse.
  • Avoid caching one-off, very large, or low-value results.
  • Enforce maximum value size and reject or bypass oversized entries.
  • Use per-tenant or per-namespace memory quotas where supported.
  • Apply write-rate limits during traffic spikes or cache warmup.
  • Prefer admission based on observed frequency or estimated reuse value when the engine or application supports it.
  • Keep cache writes asynchronous or outside the critical response path when the product contract permits it.

An admission policy can prevent a flood of unique requests from evicting a useful hot working set. For example, a batch scoring job that generates five million one-time keys should not displace interactive predictions that are repeatedly reused. The batch workload can use a separate cache namespace, lower priority, or no result cache at all.

8. Plan headroom for failover, resharding, and warmup#

Capacity planning must include degraded states, not only normal steady state.

  • Keep enough memory and CPU headroom for replica promotion, shard recovery, resharding, and sudden traffic shifts.
  • Avoid operating every shard at the same high utilization; skew and failover can concentrate load.
  • Estimate the cold-cache miss surge after restart or replacement.
  • Warm only high-value keys and rate-limit warmup so it does not compete with live inference.
  • Rehearse scaling and recovery with realistic key sizes and traffic distributions.
  • Ensure the inference fleet has an independent concurrency and queue bound so a cold cache cannot overwhelm model workers.

Q144 covers the cache outage circuit-breaker and bounded bypass behavior. Here, the capacity-specific concern is that a cache can be technically available but so full, skewed, or slow that it behaves like a degraded dependency. Coordinate cache scaling with inference capacity planning, but do not assume extra model replicas will solve a cache hot shard.

9. Failure scenarios and debugging#

Scenario A: Hit ratio collapses after a deployment

  • Symptom: cache memory is stable, misses spike, GPU utilization rises.
  • Likely causes: cache-key version changed, serialization changed, model version was added to every key, or a rollout unintentionally invalidated the working set.
  • Debug: compare key cardinality and hit ratio by application version; sample key dimensions without exposing sensitive values; inspect deployment and invalidation events.
  • Fix: confirm whether the key dimension is required for correctness. Roll out key changes gradually, retain compatible namespaces only when safe, and prewarm a bounded high-value subset.

Scenario B: One shard evicts aggressively while cluster memory looks healthy

  • Symptom: p99 latency and evictions spike for a subset of requests; aggregate memory appears acceptable.
  • Likely causes: uneven hash distribution, hot keys, or large values concentrated in a shard.
  • Debug: inspect per-shard memory, operations, CPU, network, hot-key samples, and slot distribution.
  • Fix: address key skew, hot-key fan-in, or value-size concentration; then reshard or alter partitioning in a controlled maintenance window.

Scenario C: Cache is full but most entries are never reused

  • Symptom: high write volume and eviction rate, poor hit ratio, high cache cost.
  • Likely causes: long TTL, unbounded key dimensions, batch traffic mixed with online traffic, or caching low-reuse endpoints.
  • Debug: measure reuse distance, unique keys per minute, TTL survival, and hits by endpoint.
  • Fix: shorten TTL only where freshness permits, add admission rules, isolate batch workloads, or disable caching for low-value paths.

Scenario D: Hot key causes CPU and network saturation

  • Symptom: one key or small key family receives a disproportionate number of operations; cache latency rises even though memory is not full.
  • Likely causes: popular tenant/model configuration, shared reference prediction, or a retry loop.
  • Debug: identify key popularity with safe sampling or supported hot-key diagnostics; correlate with client and endpoint metrics.
  • Fix: add a short-lived L1 cache, coalesce concurrent reads, reduce polling, or distribute immutable read copies where correctness allows.

Scenario E: Scaling operation causes a temporary latency spike

  • Symptom: cache p99 rises during resharding; inference misses or timeouts increase.
  • Likely causes: data migration competes for CPU/network, client topology refresh is slow, or the cluster has insufficient headroom.
  • Debug: correlate resharding events with per-shard CPU, network, redirects, connection churn, and application p99.
  • Fix: perform the operation earlier at lower utilization, use a staged plan, validate client cluster discovery, and rate-limit migration where supported.

Scenario F: Cache cost rises faster than inference traffic

  • Symptom: memory and node spend increase, but avoided model executions do not.
  • Likely causes: low-value keys, excessive TTL, duplicate namespaces, oversized values, or poor eviction/admission.
  • Debug: calculate cost per useful hit and avoided accelerator-second by endpoint and tenant.
  • Fix: remove low-value cache populations, compress only if CPU trade-offs are favorable, reduce unnecessary value fields, and right-size after observing a representative traffic cycle.

10. Monitoring and alerting#

Build dashboards at both fleet and shard level. Include:

  • Hit ratio, miss rate, and hit count segmented by endpoint/model/tenant cohort.
  • Evictions per second, expirations per second, and memory used versus usable memory.
  • Per-shard memory utilization, CPU, network, ops/sec, and p95/p99 command latency.
  • Key count, key creation rate, unique-key rate, value-size percentiles, and TTL distribution.
  • Hot-key concentration and top-key operation share using privacy-safe diagnostics.
  • Cache timeout/error rate and client connection churn.
  • Inference GPU utilization, queue depth, p95/p99 latency, and cost per prediction alongside cache metrics.
  • Estimated accelerator time saved and cost per useful cache hit.

Alert on correlated symptoms rather than a universal hit-ratio threshold. For example, alert when eviction rate rises sharply *and* hit ratio falls *and* inference compute or latency increases. Alert on a single shard approaching its memory or CPU limit even when cluster averages are normal. Set thresholds from load tests and historical baselines; a 50% hit ratio may be excellent for one workload and poor for another.

11. Engineering trade-offs#

  • Bigger nodes vs more shards: bigger nodes simplify topology but can increase single-node blast radius and vertical-scaling cost; more shards increase throughput and failure isolation but add routing and operational complexity.
  • Replicas vs shards: replicas help read throughput and availability; shards add write and aggregate storage capacity. Replicas may be eventually consistent.
  • Longer TTL vs memory cost: longer TTL can increase reuse but consumes memory and can retain low-value entries longer.
  • LFU vs LRU: frequency helps stable popularity; recency adapts faster when traffic patterns shift. Both are approximations and must be validated against workload traces.
  • Local cache vs centralized cache: local cache reduces network and hot-key pressure but duplicates memory and complicates freshness.
  • Compression vs CPU: compression saves memory/network for large values but adds encode/decode CPU and latency.
  • High hit ratio vs business value: optimizing a metric is wasteful if hits save little compute or cache reads cost more than recomputation.

12. Common mistakes#

  • Sizing from serialized payload bytes while ignoring per-entry overhead, replication, fragmentation, and buffers.
  • Using aggregate memory and CPU while one shard is already saturated.
  • Assuming TTL guarantees residency or freshness.
  • Choosing LRU/LFU without measuring reuse distance and access skew.
  • Adding replicas to fix write saturation, or adding shards to fix a single hot key without changing its access pattern.
  • Caching every endpoint and every tenant equally, including one-off batch outputs.
  • Letting unbounded request dimensions create unbounded key cardinality.
  • Using hit ratio as the only success metric.
  • Resharding at peak utilization with no staging rehearsal.
  • Warming the entire keyspace and causing a self-inflicted inference surge.
  • Treating cache capacity as a substitute for the inference service's own admission control and concurrency limits.

13. CI/CD, load tests, and operational acceptance#

Treat cache configuration and key-distribution behavior as deployable infrastructure, not an undocumented manual setting. Before release:

  • Replay a representative production trace with realistic key popularity, value sizes, TTLs, and tenant mix.
  • Test the expected working set plus a burst and a high-cardinality workload.
  • Validate per-shard distribution and confirm no shard reaches its limit prematurely.
  • Compare LRU/LFU and candidate TTL/admission settings using hit ratio *and* avoided inference cost.
  • Test oversized values, write rejection, eviction behavior, client reconnects, and topology refresh.
  • Run hot-key tests and confirm local caching or request coalescing reduces backend operations without violating freshness.
  • Exercise resharding and replica failover while measuring application p99 and inference queue depth.
  • Verify alerts fire on shard-level saturation and correlated eviction/miss/compute regressions.
  • Confirm rollback restores compatible cache behavior and does not cause an uncontrolled cold-cache surge.
  • Document ownership, scaling triggers, capacity review cadence, and a runbook for skew, thrashing, and cost regressions.

A release should not pass merely because the cache cluster is reachable. It should demonstrate that the representative working set fits with measured headroom, no shard is a hidden bottleneck, the chosen eviction/admission policy retains high-value entries, and inference remains bounded when cache performance degrades.

14. Practical operating sequence#

  1. Instrument request and key distributions before provisioning.
  2. Estimate the working set from unique-key arrival rate and useful TTL.
  3. Measure actual resident bytes per key on the target engine.
  4. Add replication, allocator, buffer, skew, and recovery headroom.
  5. Load-test eviction and access policies with realistic traces.
  6. Deploy per-shard dashboards and cost-per-useful-hit reporting.
  7. Scale the constrained resource—memory, reads, writes, CPU, or network—rather than scaling blindly.
  8. Reassess after model, feature, tenant, or traffic changes.

The goal is not the largest possible cache or a perfect hit ratio. It is a predictable cache fleet that retains valuable predictions at an economically justified cost, distributes work evenly, and does not turn capacity pressure into an inference incident.

Related questions

Explore other topics:Machine LearningRetrieval-Augmented GenerationAI Agents