Routing AI Workflows with Prompt Cache Reuse in Mind
Design model routing around workflow cost, cache eligibility, and safe handoffs. Includes TypeScript switching policy, Python usage accounting, failover controls, and production metrics.
On this page
A model router makes a decision about the next request. The bill belongs to the whole workflow.
That difference matters when an agent repeatedly sends a large reference bundle, tool definitions, and growing history. A cheaper model can be a good choice for one isolated call while increasing the cost of completing the job. Moving to it may require processing that context again, transforming provider-specific messages, or repeating a step that the new model handles less reliably.
I would make cache reuse part of the routing estimate, while keeping capability, authorization, and deadlines ahead of it.
This article uses a hypothetical catalog-reconciliation agent. It compares supplier records with a retailer's product catalog, proposes corrections, and produces a review report. The examples are architectural sketches, with no claim of measured savings.
Define the unit that should keep its route
The entire conversation is often too coarse a routing unit. A catalog job may have several distinct stages:
- extract product attributes from supplier documents;
- reconcile those attributes against existing records;
- explain proposed changes to a reviewer.
Those stages do not necessarily need the same model or the same context. Extraction might need document capabilities. Reconciliation might need a larger tool contract. The final report can operate on a compact, validated change set.
Inside a stage, repeated requests often share substantial context. Between stages, a deliberate handoff can reduce the information sent to the next model.
I would therefore persist a route per stage, with an explicit continuation contract. The reconciliation stage can retain its chosen profile while a separate, narrow classifier runs elsewhere. Cheap supporting calls do not need the entire reconciliation transcript.
This extends the model-routing policy: first decide which profiles can do the job; then compare the operational cost of continuing on each one.
The earlier prompt-prefix design covers arranging stable and changing context. This article focuses on the routing decision that determines where that context is processed.
Treat cache eligibility as evidence, not ownership
A stable application prefix does not prove that a provider currently holds a usable cache entry.
Reuse depends on factors such as the model, account or workspace scope, processing region, request representation, cache boundaries, retention, and provider routing. The exact rules belong in a provider adapter rather than one universal configuration flag.
Current documentation illustrates why that adapter matters. Claude's prompt-caching guide describes automatic caching and explicit block controls, exact prefix matching, and scope-dependent isolation. OpenAI's guide describes model-dependent controls, lifetimes, routing, and accounting. Gemini's caching documentation describes implicit caching and API/model compatibility.
Do not hard-code a rule such as “one provider only supports automatic caching” or assume a cache-control field works for every model behind an adapter. These interfaces evolve.
A route change also does not necessarily erase the original cache. Returning to an earlier profile could reuse a compatible entry if it remains available. Conversely, staying on the same model can still miss after expiry, prefix changes, or provider routing.
The conservative planning rule is to estimate a target as cold unless there is relevant evidence of reuse. Even then, carry a miss scenario. The application observes reported usage after execution; it does not own the provider's internal cache state.
Compare continuation cost in one unit
A route estimate should include the remaining work, rather than only the price of the next input token.
For each eligible profile, estimate:
- uncached input processing;
- cache creation and reads where that provider bills them separately;
- output generation;
- expected retries and additional tool steps;
- context conversion or compaction needed at the handoff;
- other applicable charges.
Keep latency as an independent constraint. Do not add milliseconds to dollars through an unexplained weighting constant.
Imagine these invented planning estimates for the remainder of a stage:
| Choice | Estimated continuation cost |
|---|---|
| Retain the current profile | $0.18 |
| Move to another profile, excluding transition work | $0.07 |
| Transition work for that move | $0.16 |
| Total after moving | $0.23 |
These numbers are illustrative, not provider prices or benchmark results. They show why the smaller per-call price is insufficient evidence for switching.
Run the same comparison under different remaining-length and cache-hit assumptions. A short final exchange and a long continuation can produce different answers. If the uncertainty is larger than the supposed saving, retaining the eligible current route is often the simpler decision.
Add a switching margin after eligibility checks
A small amount of hysteresis prevents the route from oscillating when cost estimates change slightly between turns. The margin expresses how much estimated saving is required to justify a discretionary transition.
It must never keep an incompatible, unauthorized, or unhealthy profile active.
The TypeScript sketch below separates those decisions. Each continuationUsd estimate already includes the cost of getting onto that profile from the current stage:
type RouteEstimate = { id: string; authorized: boolean; capabilityPassed: boolean; qualityPassed: boolean; healthy: boolean; coldP95Ms: number; continuationUsd: number;};type RouteDecision = { id: string; reason: "initial" | "required-change" | "continuity" | "estimated-saving";};function chooseRoute( estimates: RouteEstimate[], currentId: string | undefined, remainingMs: number, switchMarginUsd: number,): RouteDecision { if ( !Number.isFinite(remainingMs) || remainingMs <= 0 || !Number.isFinite(switchMarginUsd) || switchMarginUsd < 0 ) { throw new Error("invalid-routing-policy"); } if (new Set(estimates.map(e => e.id)).size !== estimates.length) { throw new Error("duplicate-profile-id"); } const eligible = estimates.filter(e => e.authorized && e.capabilityPassed && e.qualityPassed && e.healthy && Number.isFinite(e.coldP95Ms) && e.coldP95Ms >= 0 && e.coldP95Ms <= remainingMs && Number.isFinite(e.continuationUsd) && e.continuationUsd >= 0 ).sort((a, b) => a.continuationUsd - b.continuationUsd || a.id.localeCompare(b.id) ); const best = eligible[0]; if (!best) throw new Error("no-eligible-profile"); const current = eligible.find(e => e.id === currentId); if (current && current.continuationUsd <= best.continuationUsd + switchMarginUsd) { return { id: current.id, reason: "continuity" }; } return { id: best.id, reason: currentId === undefined ? "initial" : current === undefined ? "required-change" : "estimated-saving", };}The flags must come from trusted policy and evaluation systems, not the model's self-reported confidence. Validate transport inputs before calling this function.
The latency field represents the estimated cold-path duration for the bounded decision unit. A percentile estimate is not a deadline guarantee. Enforce a hard runtime deadline separately, including tool execution and cancellation.
Persist the decision together with stage ID, profile version, policy version, context version, and a structured reason. If multiple workers can change the route, use a transaction or compare-and-swap against the stage version. An in-memory variable does not coordinate two workers recovering the same job.
Normalize usage before calculating cost
Provider usage fields can overlap. Some report total input with cached input as a subset; others expose separate input, cache-write, and cache-read counters. Summing them indiscriminately can double-count tokens.
Normalize into disjoint categories at the adapter boundary, preserving the original response for reconciliation. Never interpret an absent usage field as confirmed zero usage; record it as unknown.
A Python cost function can consume that normalized representation:
from dataclasses import dataclassfrom math import isfinite@dataclass(frozen=True)class Usage: fresh_input: int cache_write: int cache_read: int output: int@dataclass(frozen=True)class Rates: fresh_input: float cache_write: float cache_read: float output: floatdef token_cost_usd(usage: Usage, rates: Rates) -> float: # Rates are USD per million tokens, selected for this request. counts = ( usage.fresh_input, usage.cache_write, usage.cache_read, usage.output, ) prices = ( rates.fresh_input, rates.cache_write, rates.cache_read, rates.output, ) if any(type(n) is not int or n < 0 for n in counts): raise ValueError("Normalized token counts must be nonnegative integers") if any(not isfinite(p) or p < 0 for p in prices): raise ValueError("Rates must be finite and nonnegative") cost = sum(n * p for n, p in zip(counts, prices)) / 1_000_000 if not isfinite(cost): raise ValueError("Cost overflow") return costThis covers token charges under already-selected rates. The adapter must handle tiers, platform modifiers, reasoning-token accounting, storage charges, and non-token fees where applicable. It should not apply one global rate table to every request.
Cost estimates and settled usage are separate records. Reconcile them to learn whether the router systematically underestimates a particular profile, stage, or fallback path.
Switch at a durable handoff
A discretionary change is easiest to reason about after a completed tool boundary. Store a portable checkpoint containing the objective, authoritative resource versions, pending decisions, completed operation IDs, and artifact references.
Avoid forwarding a vendor-specific transcript unchanged to another provider. Tool-call identities, message formats, retained reasoning blocks, and structured-output support can differ. A provider adapter must validate the new request; a versioned handoff artifact defines what the next stage actually needs.
An emergency failover may occur without a clean boundary. In that case, distinguish completed work, failed work, and unknown outcomes. A model timeout does not establish that an external side effect failed. Reconcile the effect before another model proposes a retry. The idempotency pattern remains necessary.

*Flow: authorize eligible routes first; retain a healthy current route unless a different route clears the switching margin. Validate any handoff before executing and recording actual results.*
A cache hit remains an optimization inside this flow. The system must still be able to execute the cold path within its operational policy.
Availability takes precedence over cache economics
During a provider incident, preserving a warm prefix is a weak reason to remain on a failing dependency.
Remove unhealthy profiles from the eligible set. Check the fallback's region, privacy policy, output contract, tool support, context limits, and quality floor before comparing cost. If nothing eligible remains, degrade the feature or defer the work.
The provider-failover design addresses that boundary. Cache reuse influences discretionary routing; it cannot authorize a forbidden destination.
Capacity planning also needs the cold fallback scenario. If many stages move together, repeated prefix processing can increase input spend and prefill load. Bound transition concurrency, reserve budget, and measure recovery under the actual request shapes. Do not promise warm-path latency during a mass failover.
Separate cache stability from data freshness
A cached prefix can contain perfectly preserved stale information.
For catalog reconciliation, retain stable instructions and tool contracts where appropriate, but load current product versions through authorized tools. Tie observations to resource versions. Revalidate before proposing a mutation after a long pause.
Do not keep an old supplier specification or tenant policy active merely because rebuilding the prefix costs money. Freshness and authorization are product requirements; caching comes afterward.
Cross-tenant reuse needs the same care. The application decides which tenant data can enter a request. Provider account isolation does not automatically isolate every tenant sharing your account. Use approved scope boundaries and avoid placing customer-specific data into a broadly reusable prefix.
Cache fingerprints are useful diagnostics, but can still expose sensitive correlations or enable guessing when the underlying content has low entropy. Prefer keyed fingerprints where appropriate, avoid raw identifiers in keys, and restrict diagnostic access.
Measure completed work, then explain the cache contribution
I would evaluate a new routing policy on entire recorded workflows. Looking only at isolated turns misses escalation, additional tool calls, repeated failures, and context rebuilding.
Useful measurements include:
- total spend per attempted workflow, including failed attempts;
- spend per successful completion, with failure rate shown alongside it;
- time to completion and time to first useful output;
- route changes per stage and their reasons;
- reported cache-read tokens divided by total input tokens;
- cache-creation spend, separated from read spend;
- estimated versus settled continuation cost;
- quality and safety results by stage and risk class.
Aggregate token-weighted reuse from raw totals rather than averaging percentages across requests. A tiny fully cached request should not outweigh a large cold request.
Keep experiment variants from accidentally sharing warm-up effects when comparing policies. Report cold-start and steady-state results separately. For canaries, track assignment at workflow level so one job does not alternate policies halfway through.
Trace each route change with stage version, prefix fingerprint, provider profile, prediction assumptions, and actual usage. Keep high-cardinality IDs out of metric labels and private prompt content out of ordinary logs.
Failure cases I would test
Warm estimate, actual miss: the next request must remain correct and within its enforced budget policy.
Revoked profile: continuity must not retain a profile after authorization or residency requirements change.
Concurrent transitions: two workers must not overwrite each other's route decisions or dispatch the same operation.
Long pause: cache evidence and source freshness should be reassessed independently.
Partial usage: missing cache counters must produce unknown accounting, not a flattering zero-cost result.
Target already warm: the estimate should permit relevant evidence rather than treating every switch as a mandatory cold write.
Short remaining stage: transition cost should not disappear behind an assumption of unlimited future reuse.
Changed tool schema: compatibility and prefix identity must be revalidated together.
Failed discretionary switch: preserve a recoverable checkpoint and distinguish execution failure from unknown side effects.
When fewer routing decisions help
For short prompts, isolated requests, or highly variable context, cache reuse may contribute little. A straightforward per-request router can be appropriate if it meets quality and latency requirements.
For repeated work with substantial shared context, persist stage routes and compare continuation cost before making optional changes. Keep lightweight supporting calls separate and give stage handoffs explicit contracts.
The practical goal is an eligible route that completes the work reliably at an acceptable total cost. Cache reuse is one measured input to that decision.
Primary references
Provider details were checked on October 13, 2026. Exact prices, cache lifetimes, controls, and usage fields should be verified for the model and API used in a deployment.
KEEP READING
Related engineering notes
A Failover Route Is Not a Recovery Path: Proving Independence in AI Infrastructure
Two LLM providers can share the same failure domain. Build an evidence-backed recovery graph that checks cloud, networking, identity, control-plane and capacity dependencies before admitting fallback routes, then test correlated outages without weakening safety.
Read articleAn Eval Platform Sunset Can Erase Your Release Evidence: Build an Evidence-Escrow Migration Gate
When a hosted LLM evaluation platform retires, switching runners is not enough. Preserve the historical evidence, reconstruct grader semantics, validate scoring parity, and enforce a fail-closed release gate that survives the service shutdown.
Read articleWhen the Package Runs Before Your App: Quarantining AI Framework Releases
The 2026 agent-framework PyPI compromise exposed a blind spot in AI build pipelines: Python startup hooks execute before application imports. Design an artifact-quarantine gate, inspect wheels without installing them, separate credentials, and recover from suspected exposure.
Read article