Repository navigation
fix(router): keep the prompt caching affinity pin alive as long as the prefix's cache_control ttl - #46084
Conversation
…e prefix's cache_control ttl A prefix marked cache_control ttl 1h lost its pinned deployment after the fixed 300 s, so the next request went to another deployment and paid a cold cache. The pin TTL now follows the longest ephemeral breakpoint in the cacheable prefix, tools included: 3600 s for a 1h breakpoint and 300 s otherwise.
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
Merging this PR will not alter performance
|
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
…lared ttl Pins now live in a DualCache of their own instead of the router's 200-slot in-memory tier, so an hour-long pin no longer evicts cooldowns and rate windows. The pin lifetime follows any <n>s|m|h cache_control ttl, floored at 300 s, not only the literal "1h".
…he pins with the router cache Compute the cache_control ttl scan through offload_token_count beside the prefix hash, clear the dedicated pin cache in Router.flush_cache, and point the order-fallback and priority-group pin tests at the pin cache they read
|
@litereview code-review |
✅ code-review5/5 · Ready for human reviewScope: full · Full PR review. Completed · Some checks not run. No correctness findings. Checks and execution details
View review · Reviewed |
PR overviewThe PR adjusts router prompt-caching affinity so that a prefix's routing pin remains active for the duration of its cache_control TTL, with changes to in-memory cache handling. Two issues have been addressed, but one cache-capacity bypass remains open. When in-memory response caching is enabled, an authenticated caller can submit distinct prompts with a NaN cache TTL to retain responses beyond the configured limit, causing unbounded worker memory growth and potential service disruption. Open issues (1)
Fixed/addressed: 2 · PR risk: 6/10 |
…t 1h, and give pins 10k in-memory slots
|
@litereview code-review |
Bedrock deployments now decide the 1h pin with is_claude_4_5_on_bedrock, the same check that decides whether the 1h ttl reaches Bedrock, so an application inference profile ARN keeps a 5 minute pin whatever its base_model prices
|
@litereview code-review |
|
@litereview code-review |
…pin_ttl_from_cache_control
…sitive 1h price In a group mixing 1h and 5m deployments the in-memory pin kept the lifetime of its first write, so a 5m deployment could hold an hour-long pin. Each write now clears the in-memory entry first, matching Redis. The Bedrock gate uses supports_bedrock_prompt_cache_ttl after #46058, and a zero 1h price no longer counts as 1h support.
|
@litereview code-review |
…etime Cover every surface the pin lifetime touches: chat and /v1/messages through both SDKs, the responses bridge, response-cache hits, each provider family's 1h gate, malformed and duplicated ttl values, rewrites of one prefix, mixed and cross-group routing, concurrency, every Redis attach path, the in-memory slot pressure without Redis reads, a Redis outage and a killed worker
…pins in the memory debug routes
|
@litereview code-review |
… and the bounded expiration heap
…ot lose another thread's expiry entry
|
@litereview code-review |
|
|
||
| # Step 2: Evict if cache is still full | ||
| while len(self.cache_dict) >= self.max_size_in_memory: | ||
| while self.expiration_heap and len(self.cache_dict) >= self.max_size_in_memory: |
There was a problem hiding this comment.
Medium: Malformed TTLs bypass the cache capacity limit
With in-memory response caching enabled, an authenticated caller can send distinct prompts with "cache": {"ttl": "NaN"} to grow the worker's cache without bound: Cache._add_cache_logic() forwards that TTL unchanged, eviction discards its NaN heap record without removing the response, and this new condition then skips capacity enforcement. An isolated reproduction using the cache-write methods with a 200-entry limit retained 600 responses at HEAD versus 200 in the parent.
Validate TTLs as finite numbers before mutating the cache, and preserve the capacity bound when the expiry heap is empty.
There was a problem hiding this comment.
Fixed in 45534e3. Eviction now drops the oldest untracked entries once the expiry heap is empty, so NaN TTL writes stay within capacity
…pin_ttl_from_cache_control # Conflicts: # litellm/constants.py # tests/unit/test_router/test_router.py
|
@litereview code-review |
|
bugbot run |
|
Automatic reviews are disabled for this repository. |
|
@litereview code-review |
|
@litereview code-review |
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 9f7c1db. Configure here.
|
@litellm-stampbot |
litellm-stampbot: risk lowApproved at Rules (
Judge (gpt-6-luna): low, probability of high 0.64 (high at or above 0.90)
Pushes do not re-run this check. Comment |
kerry-berri
left a comment
There was a problem hiding this comment.
Low risk by rule and by judgement at 9f7c1db
Resolves the conflicts with #46084: the write side now passes both the request tools and honors_one_hour_ttl to async_add_model_id, and the success-event fixture carries custom_llm_provider and model_map_information, which _honors_one_hour_cache_ttl reads
TLDR
Problem this solves:
cache_control: {"type": "ephemeral", "ttl": "1h"}lost its deployment after 5 minutesHow it solves it:
"ttl": "1h"breakpoint in the cacheable prefix now pins for 3600 s, anything else for 300 scache_creation_input_token_cost_above_1hron the model's cost-map entryNaNttl), so they cannot grow it past its capacity/memory-usage-in-mem-cache,/memory-usage-in-mem-cache-items,/debug/memory/summaryand/debug/memory/details) count the pin cache next to the router's cacheDecision: the pin follows the longest breakpoint, not the last one. A 1h system block followed by 5m turn breakpoints keeps that deployment's cache partially warm for the full hour, and Anthropic requires 1h breakpoints to come before 5m ones, so the last breakpoint would under-count. Only the literal
"1h"extends the pin because5mand1hare the only values Anthropic accepts, on its own API and on Bedrock and Vertex. Parsing any duration (2h,3600s) was rejected since Bedrock drops those values and caches for 5 minutes, so the pin would outlive the cache, and an unbounded value would set an unbounded Redis TTL. Always pinning for an hour was rejected because a 5m prefix is cold after 5 minutes and a stale pin would skew routing for nothing. Pinning for 1h only when every breakpoint is 1h, as LIT-9459 and #40776 proposed, was rejected for the same reason as the last breakpoint: after 5 minutes the 5m turns are cold, but the 1h block is still warm on that deployment, so moving would throw that part away too. A router setting was not added because nothing asked for one and the request already carries the lifetimeFor the in-memory cache, once the expiry heap is empty, entries with no usable expiry are dropped in the order they were first written, since they have no expiry to rank them by. Dropping them before entries that have an expiry was rejected, because finding them means scanning every key on each write to a full cache, and they only come from a malformed ttl or a race
Not changed here: tool
cache_controland/v1/messagessystembreakpoints still never reach the pin key or its lifetime, the same as before this PR, and LIT-9460 covers thatUser Flow
Before: a developer whose agent runs one model name across two Bedrock deployments of Claude Sonnet marks its 5,870-token system prompt with
cache_control: {"type": "ephemeral", "ttl": "1h"}, and once a quiet gap passes 5 minutes the gateway sends their requests to the other deployment and pays a full cache write again{"type": "ephemeral", "ttl": "1h"}and getx-litellm-model-id: dd1bce74...withcache_creation_input_tokens5871x-litellm-model-idwithcache_read_input_tokens5871, about $0.0007 eachx-litellm-model-id: 0d5e0504..., and the first ones there pay a freshcache_creation_input_tokens5871, about $0.026 each, while the first deployment's cache still has 48 minutes to liveAfter: the same requests stay on the deployment that holds the cache for the whole hour, so every one of them reads from it
{"type": "ephemeral", "ttl": "1h"}and getx-litellm-model-id: dd1bce74...withcache_creation_input_tokens5871x-litellm-model-idwithcache_read_input_tokens5871, about $0.0007 eachx-litellm-model-id: dd1bce74...withcache_read_input_tokens5871 andcache_creation_input_tokens0Relevant issues
Fixes #28427
Linear ticket
Resolves LIT-9459
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*,make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more@greptileaito re-request a review after pushing changes)Delays in PR merge?
If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).
Screenshots / Proof of Fix
Last updated: 9f7c1db. QA and /live-pr-risk ran on 45534e3, the last commit with a product diff
Both legs drove the same client through the same steps with the same setup, differing only in the commit the proxies booted from. The before leg ran at f101347 (the merge base) from 21:59 UTC on 2026-10-14 and the after leg at 45534e3 from 01:24 UTC on 2026-10-15. Two Bedrock deployments of
us.anthropic.claude-sonnet-5-5on two AWS accounts share the model nameclaude-sonnetwithoptional_pre_call_checks: ["prompt_caching"]. Each leg ran two proxy processes, each--num_workers 2, sharing one Redis of its own, and the client alternated requests between the two proxy ports, so a pin written through one process had to be read back through the other. Deployment ids:dd1bce74is account A and0d5e0504is account B. The after leg's proxies setLITELLM_MODE=PRODUCTIONso they skipped the head worktree's.env(the merge-base tree has none), and they had a longer worker boot timeout because this box was under heavy loadEach leg built its request bodies with this script, passing a per-leg nonce so the two legs never shared a pin or a Bedrock cache. The ~5,870-token policy document is the cached prefix, marked
{"type": "ephemeral", "ttl": "1h"}on the system block for/v1/chat/completionsand/v1/responsesand on the first user block for/v1/messagesThen each leg booted the proxies and ran this driver on all three endpoints at once, with
$PAand$PBthe two proxy ports,$outthe leg's directory, and the master key in$out/.mk. Request 01 goes at t=0, 02 to 04 every 30 s, 05 to 12 concurrently after a quiet gap of 615 s, and 13 to 15 sequentially 10 s apart, alternating portsEach row is the time (UTC), the label, the endpoint, the proxy port, the
x-litellm-model-idprefix, the cache write and read tokens fromusage,x-litellm-response-cost, and the HTTP status. A request after the gap moved when its model id differs from its01_t0request, and a fresh cache write costs ~36x a cache readBefore (f101347, the merge base)
Proxies on ports A=57299 and B=42045, Redis on 60129
Before on /v1/chat/completions
Before on /v1/messages
Raw output of the request labeled
08_after12min_concurrenton/v1/chat/completions, which moved to account A and paid a fresh 1h cache writeAfter (45534e3)
Proxies on ports A=35123 and B=37719, Redis on 39265. Request 01 landed on account A on both endpoints
After on /v1/chat/completions
After on /v1/messages
/v1/responsesran the same schedule on both legs and spread across both deployments on both, since it never writes a pinRaw output of the request labeled
10_after12min_concurrenton/v1/chat/completions, which stayed on account A and read its cacheReading: on the before leg, 3 of the 11 requests after the gap on
/v1/chat/completionsleft the deployment holding the prefix and all 3 paid a fresh $0.0259 cache write, while on/v1/messages10 of 11 moved and 7 paid a fresh write. The deployment they left still had its 1h cache warm, since the requests that stayed read it 12 minutes later, so every move was wasted. On the after leg all 11 requests after the gap stayed on the first deployment on both endpoints, through both proxy processes, each reading the cache at ~$0.000725/v1/chat/completions/v1/messagesThe 5 minute side on Bedrock, an application inference profile ARN
Bedrock forwards the 1h ttl only when its own check matches the request model, and an application inference profile ARN never matches, even with a 1h-capable
base_model. The ARN legs reran the same driver with each deployment'smodelswapped for an application inference profile ARN copied fromus.anthropic.claude-sonnet-5-5, one per account, andmodel_info.base_model: bedrock/us.anthropic.claude-sonnet-5-5. Deployment ids:e1193ed4is account A and7c923541is account B. The base leg ran at f101347 from 21:59 UTC on 2026-10-14 and the tip leg at 45534e3 from 01:24 UTC on 2026-10-15/v1/chat/completionsReading: on both legs the requests inside 5 minutes stayed on the deployment that wrote the prefix and read its cache. After 12 minutes the cache was gone on both accounts, so all 8 concurrent requests paid fresh writes at $0.0162 (the 5 minute write price) instead of the $0.0259 a 1h write costs on the plain profile, and the 3 sequential requests read those writes. So Bedrock cached the ARN prefix for 5 minutes only, and the tip's 5 minute pin let traffic spread the same way the merge base did, instead of holding it for an hour on a cold deployment.
/v1/messagesshowed the same pattern on both legsARN base on /v1/chat/completions
ARN tip on /v1/chat/completions
The 1h side off Bedrock was checked with one SDK request per model through its own
prompt_cachingrouter at eb396f9, each with a 1h breakpoint on a ~10k token system block. All of the cache write landed inephemeral_1h_input_tokenson Vertex AI (claude-sonnet-5,claude-haiku-4-5), Azure AI (claude-sonnet-4-6) and Bedrock Mantle (claude-haiku-4-5), and Databricks (databricks-claude-opus-5-5, which reports no 5m/1h split) read all 12,234 cached tokens back 330 s after writing them on one of three runs. On the other two it wrote them again, which is Databricks' own cache, since that router has only one deployment to send to. Every one of those models carries the 1h price the gate reads, and each router held its pin with 3,581 s left 20 s after the writeThe 5 minute side off Bedrock (a model whose cost-map entry has no 1h price) still has no live leg, since every Claude model both QA accounts can call has one and the older Bedrock ones answer Legacy or end of life.
test_one_hour_pin_follows_the_deployments_one_hour_cache_supportcovers itObservations from the run, next to the fix but not part of it:
/v1/responsesnever pins on either leg, left alone hereAudit round 4 (past the 3-round cap: product commit 45534e3 fixed a review finding after round 3)
The audit ran round 3's cells again at 45534e3 and added 13 cells for the eviction fix in 9f7c1db, once on the merge base f101347 and twice on the head, with its own Postgres, Redis and scripted upstream per leg. Of the 79 test cells, the base leg failed 54 and passed 25, and both head runs passed all 79
claude-opus-5-5, chat, 1h blockus.anthropic.claude-sonnet-5-5, /v1/messages, 1h blockNo row failed. The new cells send 220 requests with a
NaNor unusable cache ttl to the local response cache on chat,/v1/messagesand/v1/responses, each streamed and not, and on embeddings, then a burst of all seven shapes at once. On the merge base the cache stops at 200 entries and caches nothing after that, and at the head it keeps the newest 200 and caches the next requestType
🐛 Bug Fix
Caveats (if any)
Medium
/v1/messagessystembreakpoints still get a 5 minute pin, or noneLow
/debug/memory/detailsblocks the event loop about 1 s per call, and once a concurrent chat failed with aSystemErrorgc.get_objects()on the event loop, and the fix is tracked as a follow-up/v1/responsesrequests never get a pin, so their 1h prefix can still move between deployments/v1/messagescalls, so it is a separate fixNaN, non-numeric or very long cache ttl keeps those response-cache entries ahead of entries with a normal ttl, so a flood of them leaves the rest about one slot per workerNaNflood, and limiting the ttl a caller can set is a separate fixFinal Attestation
Note
Medium Risk
Changes deployment affinity for 1h prompt caches and tightens in-memory cache eviction under concurrency; routing and cache behavior are user-visible but heavily tested.
Overview
Prompt-caching affinity pins now track
cache_controlTTL: a literal"1h"ephemeral breakpoint can pin a prefix for 3600s (when the serving deployment supports 1h caching), otherwise pins stay at 300s. Pin writes refresh lifetime from the longest breakpoint in the cacheable prefix, and mixed model groups take the TTL from whichever deployment served last.Pins move off the shared router cache into a dedicated
prompt_caching_pin_cache(10,000 in-memory slots, Redis-attached like other router caches).PromptCachingDeploymentCheckandPromptCachingCacheuse that store;flush_cacheclears it too. Proxy memory debug routes now reportprompt_caching_pin_cacheseparately from LLM response cache.InMemoryCachegains a write lock aroundset_cache/flush_cache, compacts the expiration heap when it exceeds 2× capacity, and when the heap is empty evicts oldest keys with no usable expiry (e.g.NaNTTL) so floods cannot grow pastmax_size_in_memoryor block new caching.Broad unit and integration coverage covers pin TTL rules, Bedrock ARN behavior, memory routes, Redis chaos, and response-cache flooding under bad TTLs.
Reviewed by Cursor Bugbot for commit 9f7c1db. Bugbot is set up for automated code reviews on this repo. Configure here.