KV-Cache Eviction Metrics Link Memory Use to Costs | Hokstad Consulting

KV-Cache Eviction Metrics Link Memory Use to Costs

KV-Cache Eviction Metrics Link Memory Use to Costs

A smaller KV cache does not always mean a cheaper agent task. Test cache policies at 25%, 50%, 75% and 100% of the usable KV budget, then compare £ per successful task against a high-retention baseline - not memory use alone.

The decision comes down to three checks:

  • Cost: Link cache hits, evictions, recomputation and transfers to task costs, including failed attempts and retries. State whether GBP figures include VAT.
  • Performance: Track GPU memory, successful tasks per second and p95/p99 latency under matched workloads.
  • Quality: Keep reusable-prefix eviction separate from active-context pruning, which can remove information a task still needs.

Retain, transfer or recompute state according to measured cost and latency. Roll out a policy only when testing shows lower task costs without worse completion rates, latency or quality.

::: @figure KV-Cache Eviction: From Memory Savings to Task Cost{KV-Cache Eviction: From Memory Savings to Task Cost} :::

KV Cache Offloading for AI Agents: Cutting SSD Stalls to Under 10%

Metrics that link cache use to cost

Track cache, request and task metrics using the same IDs. Cache metrics only matter when they explain task cost. Follow each task cohort until completion or timeout, including retries and tool calls. Don’t drop unfinished work when a monitoring window ends.

Use a 15-minute monitoring window and compare like-for-like workloads, hardware, models, cache tiers and routing rules. Report warm-up separately from steady-state. Read the table from top to bottom: cache signals explain request slowdowns, while request signals show whether task cost increases.

Cache hits, evictions and GPU memory pressure

Token-weighted prefix-cache hit rate means eligible prefill tokens reused without recomputation divided by all eligible prefill tokens seen. Define eligibility before measuring it. Include only prefixes the system can legally and technically reuse. Exclude generated tokens, cache-bypassing requests and dynamic sections that cannot be reused.

Report request-weighted hits separately. A cache miss does not always mean an eviction: distinguish cold misses, prefix mismatches, expiry misses, policy-driven evictions and capacity-driven evictions.

The table moves from cache behaviour through request impact to task cost.

Metric Level and source Calculation or measurement Cost implication Warning signs
Token-weighted prefix-cache hit rate Request; lookup counters Reused eligible tokens ÷ eligible prefill tokens Prefill compute avoided Request hits rise but token hits fall
Cold-miss rate Request; lookup reason codes Cold-missed eligible tokens ÷ eligible prefill tokens First-use compute, not eviction overhead Cold starts mistaken for cache churn
Eviction rate Cache; block events Evicted blocks ÷ (eligible blocks resident at window start + eligible admissions) Possible restoration work Increasing evictions followed by recomputation
KV utilisation and reusable capacity Cache; allocator Occupied KV bytes ÷ allocated KV bytes; record reusable bytes separately Capacity available for useful work High allocation mistaken for useful occupancy
Block lifetime, idle time and reuse gap Cache; block timestamps Admission-to-removal; last-access-to-eviction; time between accesses Cost of retaining versus restoring state Blocks requested soon after eviction
Tier hits, transfer volume, transfer time and blocking stalls Cache/request; tier and transfer logs Tokens served from each tier ÷ tokens requested from that tier; bytes moved; transfer elapsed time; time blocked waiting for state Compute avoided versus transfer and waiting costs More tier hits but longer stalls; interconnect saturation
Recomputation tokens and GPU time Request; token traces and GPU profiling Repeated tokens and GPU milliseconds attributable to eviction Avoidable compute cost Growth despite stable workload
Preemption rate Request; scheduler Requests preempted ÷ requests scheduled Interruption and waiting costs Repeated interruptions and longer queues
Queue time, TTFT, per-token latency and end-to-end latency Request; serving timestamps Report p50, p95 and p99 Longer resource occupancy Stable median but worsening tails
Completed requests/s and successful tasks/s Request/task; completion logs Completed requests or successful tasks per second Useful work per unit of capacity Request throughput increases while task throughput falls
Completion rate and quality Task; outcome checks Successful tasks ÷ submitted tasks; agreed quality score Failed work and retry costs More retries or rejected outputs
Cost per successful task Task; billing and workflow ledger Attributable cohort cost ÷ accepted completions Spend per accepted result Lower memory use but higher task cost

Record allocated, occupied and reusable capacity separately. Reserved memory may not be occupied, and occupied blocks may not be reusable by another request. Keep GPU-resident hits separate from host-memory and storage hits. Block lifetime, idle-before-eviction and reuse-gap measurements help identify blocks removed too soon.[3] Break down results by model, tenant, workflow, prefix length, tier, hardware, load and policy.

Recomputation, transfers and request delays

Attribute extra prefill tokens and recomputation GPU time to the eviction that caused them. Ordinary uncached prefill is baseline work, not eviction overhead.

Measure transfer duration separately from blocking time: transfers may overlap computation. Using the latency measures above, compare requests involving hits, cold misses, capacity-driven evictions, tier restores and recomputation. Also track GPU compute and memory-bandwidth utilisation, CPU utilisation, storage I/O and interconnect load. Include energy only where reliable telemetry exists.[1][2]

Calculate cost per successful agent task

Allocate cohort cost across accepted completions using the same deadline and quality threshold. Charge the cohort for failed attempts, retries, timeouts and abandoned runs. Include compute, storage, transfers, orchestration, billable calls and resource occupancy while waiting.

For the same service, use either bundled charges or allocated resource cost - not both. Deduplicate call records by call_id. If there are no successful completions, the metric is undefined, not £0.

Report GBP cost, completion rate and quality together. Label internal allocated-cost reductions separately from invoice savings or provisioned-capacity savings. Use the same cohort throughout so cache events connect to completed work, rather than faster eviction alone.

KV-cache retention and eviction trade-offs

When to retain, evict, transfer or recompute

Retain state when its likely reuse saves more per successful task than the capacity it takes up costs. Longer contexts cost more to recompute, while higher concurrency makes GPU memory more costly to hold. Protect active requests first, then move or discard inactive state. Use native block management: restoration requires compatible tensor layouts and scheduler support, and eviction must respect block reference counts.[4][5][8]

To choose the cheapest policy, weigh reuse probability, restoration cost and latency against cost per successful task.

Policy GPU memory Hit rates Recomputation Transfer overhead Latency Throughput Complexity Best cost conditions
Retain on GPU Highest residency Highest for retained state Minimal None Best on hits Can suffer under memory pressure Low–medium Frequent reuse; strict response targets
Evict and discard Frees selected blocks Lost for discarded state Required on reuse None Later misses are expensive May admit more requests, but adds future prefill work Low Cold state with little expected reuse
Transfer to another tier Frees GPU space Preserves potential tier hits Avoided after successful restoration Write-out and restore Slower than GPU hits Helps concurrency unless transfers become a bottleneck High Likely reuse; restoration costs less than recomputation
Recompute on demand Low persistent residency No retained hit Required None Depends on available GPU compute Uses compute when requests return Low Short contexts, slow storage or unsupported restoration

Use lower-tier storage only when the recomputation it avoids costs more than storage, write-out and restoration combined, reducing cost per successful task. Restoration must also meet the latency target. Measure transfers in both directions, including contention. Asynchronous transfers can overlap computation only where supported. Set promotion-size and transfer-concurrency limits so returning sessions do not overwhelm the transfer path.[4][9]

These policies have different effects: prefix eviction preserves the option to reuse context, while active-context pruning can remove information a live task still needs.

Prefix eviction versus active-context pruning

Prefix eviction is reversible; active-context pruning removes information the model can no longer use. Restoring or recomputing an evicted prefix preserves full-context computation. Discarding active tokens does not. Assess their quality and cost separately.[5]

Policy Memory reduction Applicable hit rates Recomputation risk Quality risk Policy overhead Long-running agent suitability
Prefix eviction with LRU Frees selected cached blocks Prefix-cache hits Recomputes an evicted prefix on the next matching request Low if the prefix is recomputed exactly Low to medium Strong for repeated system prompts and stable documents
Sliding-window retention High and predictable Preserves only tokens inside the active window Low for the retained window; high if old context must be rebuilt Medium unless the model was designed for the window Low to medium Good for streaming or agents that mostly need recent context
Sliding window plus attention sinks High Preserves initial sink tokens and recent tokens, not arbitrary prefixes Low for retained state Lower than naïve eviction in many long-context settings, but model-dependent Medium Useful for long-running streams where initial stabilising tokens matter
Attention-score retention Variable; can retain selected high-value tokens Depends on whether selected tokens match future needs Medium if discarded evidence must be reconstructed Medium to high because scores can be short-sighted or unstable High Experimental unless validated on the agent’s tasks
Static post-prefill eviction Predictable after prompt processing Can preserve selected reusable blocks Low if the complete prefix remains available elsewhere; otherwise high Low for exact eviction; potentially high if it prunes active attention state Low to medium Suitable for repeatable workflows with known prompt structure
Dynamic decoding-time eviction Potentially very high during sustained generation Changes as the request evolves Variable High unless validated for the model and task High Suitable only when long-horizon quality and recovery behaviour are measured

Static and dynamic describe when eviction happens, not whether it preserves computation. Attention sinks can stabilise recent-token windows, but they do not preserve every earlier instruction or tool result.[6][7] A native sliding-window model is designed or trained for restricted attention. Applying the same window to a full-attention model removes information it may expect to retain.

For agents that revisit earlier commitments, test for forgotten constraints, incorrect tool calls and failures of factual recall before pruning active state. Start with exact retention and supported offloading. Consider approximate pruning only when task-level savings hold up after those quality checks.

Benchmark cost per successful agent task

Set a controlled baseline

Start by measuring cost per successful task to establish a baseline.[10] Use the same task cohort and success threshold defined above. Before changing the cache, define success: a correct task outcome, policy compliance, escalation when required and latency within the agreed limit. A generated answer alone does not count.

Match production proportions for short and long conversations, tool calls, retries and escalation requests. Set completion, quality and latency thresholds before testing.

Record the current policy and usable KV budget after reserving memory for model weights, activations, framework overhead, batching and safety headroom. Keep model version, quantisation, prompt templates, context-length mix, output-length mix, concurrency, arrival rate, hardware, software stack and sampling settings fixed.

Test at 25%, 50%, 75% and 100% of the usable KV budget. Repeat cold- and warm-cache runs separately. Report median and p95/p99 latency, plus variation by tenant and workflow. Keep fixed-load comparisons separate from saturation tests.

Link cache events to task results

Once the baseline is fixed, trace every cost-bearing event to the same task ID. Use that ID across every model call, tool call and retry.

Log cache hits and misses, evictions, preemptions, block lifetimes, cache residency location, recomputed tokens and recomputation time. Also record transfer bytes and duration, queue time, time to first token, inter-token latency, total latency and outcome quality.

Record GPU-resident hits, offloaded hits and recomputed misses separately: each has different latency and resource costs.[11] Every event must map to the same accepted-completion cost ledger, with shared-prefix costs allocated consistently.

Convert GPU-seconds, host-memory occupancy, storage traffic and network transfer into GBP at the relevant rates. Count recomputation only once, but include failed attempts and retries in total task cost.

Compare costs, latency and quality

Report total GPU memory separately from the usable KV budget. Define hit rate as hits divided by eligible reuse lookups. Define eviction rate as block evictions divided by block allocations over the same interval. Use £ per successful task as the main comparison.

Policy KV budget Peak GPU memory Hit rate Eviction rate Recomputation time p95 task latency Completion rate Quality £ per successful task
Current baseline 100% Measured Hits / lookups Evictions / allocations GPU-seconds Seconds Valid completions / tasks Same evaluator Total cost / successes
Moderate eviction 75% Measured Hits / lookups Evictions / allocations GPU-seconds Seconds Valid completions / tasks Same evaluator Total cost / successes
Tighter eviction 50% Measured Hits / lookups Evictions / allocations GPU-seconds Seconds Valid completions / tasks Same evaluator Total cost / successes

Divide all allocated costs by the number of tasks that meet the agreed success criteria. Keep the resource costs of failures, timeouts and retries in the numerator. Report run-to-run variation and successful tasks per billed GPU-hour.

Freed memory counts as value only when it reduces billed capacity or increases useful output. Break results down by prefix length: a long, frequently reused prefix can matter more than many inexpensive hits. Choose the setting with the lowest £ per successful task that still meets latency, completion and quality thresholds.

Conclusion: Cut task costs without losing quality

Make the benchmarked £ per successful task the release gate for any cache policy change.

Reduce KV-cache use only when it lowers £ per successful agent task without worsening latency or quality. Count extra recomputation, delays and retries as costs - not side effects.

Match cache actions to measured signals

Set thresholds for each workload rather than using fixed memory percentages. Assess hit rate, eviction rate, recomputation time and GPU memory pressure together. Use these signals to choose a policy:

Measured signals Action
Low hit rate, high eviction rate and high recomputation time Retain more useful prefixes, increase the KV budget or reduce concurrency when eviction increases £ per successful agent task and latency.
Low hit rate, long idle time and low recomputation cost Evict rarely reused idle blocks first, especially after task completion.
High hit rate, rising GPU memory pressure and restore time shorter than recomputation time Transfer selectively, provided restore time stays within the task’s latency target.
Low hit rate, high transfer latency and low recomputation time Recompute when rebuilding costs less and still meets latency targets.
Repeated pre-emption of active requests Investigate batching, concurrency, reservations and fragmentation. Do not count these events as idle-cache evictions.

Track cost, latency and quality regressions

After benchmarking, use this checklist as a rollout gate:

  • [ ] Assign an owner for the cache policy, dashboard and rollback decision.
  • [ ] Set per-request, per-model and per-GPU budgets with safety headroom.
  • [ ] Export cache-event counters for hits, misses, evictions, transfers, restores, recomputations and eviction reasons.
  • [ ] Track prefix eviction separately from active-request pre-emption and active-context pruning.
  • [ ] Allocate costs to tasks, including failures and retries. Trigger an alert when memory use falls but cost per successful agent task rises.
  • [ ] Define rollback limits for cost, p95/p99 latency, task failures and quality before release.
  • [ ] Retest after changes to models, prompts, agent memory, routing, batching or concurrency.

Deploy only after testing

Test candidate policies under normal and stress load, using the baseline and task-linked metrics. Start with a canary or limited workload, and roll back if agreed limits are breached. Expand the rollout only when canary testing confirms lower £ per successful task with no latency or quality regression.

FAQs

Why might higher cache hit rates fail to reduce task costs?

Higher cache hit rates don’t always mean lower task costs. They don’t account for failures, retries or extra validation. If a cached response is wrong or incomplete, human review and recovery work can cost more than the memory savings.

To measure cost per successful task, divide all delivery costs - including infrastructure and correction work - by the number of accepted, high-quality tasks. This accounts for costs that token-level efficiency alone leaves out.

How do I allocate shared-cache costs fairly across agent tasks?

Attribute shared-cache costs to task or project identifiers instead of treating cache memory as pooled overhead. Link usage to the responsible user or project with project, team or environment tags, Virtual Tags or IAM principal-based attribution.

Calculate cost per completed agent task by dividing total delivery costs - including model calls, tool use, retries and human review - by the number of accepted tasks. Track cache-hit rates alongside actual costs, rather than measuring memory savings alone.

How can I distinguish eviction overhead from GPU memory pressure?

Track cache-hit ratios, latency, recomputation time and GPU memory use together. High GPU utilisation alongside a sustained queue depth can suggest memory pressure. If cache-hit ratios fall while latency and recomputation time increase, that points to eviction overhead - even when GPU usage stays steady or drops.

Calculate the cache-hit ratio by dividing cached tokens by total input tokens. Assess cost per completed task, including recomputation and retries, rather than judging memory savings alone.

Need help with your DevOps, cloud or AI plans?

Hokstad Consulting helps companies with DevOps transformation, cloud architecture and hands-on AI development — pragmatic consulting with measurable results.

Our services: DevOps on Retainer · Hosting & Cloud · AI Development & Strategy