Skip to content

fix(router): keep the prompt caching affinity pin alive as long as the prefix's cache_control ttl - #46084

Merged
mateo-berri merged 15 commits into
mainfrom
litellm_prompt_cache_pin_ttl_from_cache_control
Oct 15, 2026
Merged

mateo-berri merged 15 commits into
mainfrom
litellm_prompt_cache_pin_ttl_from_cache_control

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Prompt-caching affinity pinned a prefix to its deployment for a fixed 300 s
  • A prefix marked cache_control: {"type": "ephemeral", "ttl": "1h"} lost its deployment after 5 minutes
  • The next request then went to another deployment and paid a cold cache for an hour-long prefix

How it solves it:

  • A "ttl": "1h" breakpoint in the cacheable prefix now pins for 3600 s, anything else for 300 s
  • The 1h pin applies only when the 1h ttl reaches a deployment that supports it
    • On Bedrock it uses the same check that decides whether Bedrock gets the 1h ttl, so an application inference profile ARN keeps a 5 minute pin
    • Elsewhere it needs a positive cache_creation_input_token_cost_above_1hr on the model's cost-map entry
  • Every pin write sets the pin's lifetime again, in memory as Redis already did
    • In a group that mixes 1h and 5m deployments, the deployment that served the prefix last decides how long the pin lasts
    • The in-memory cache rebuilds its expiry heap once it holds more than twice the cache's capacity, so rewriting pins cannot grow the heap without limit
    • Writes to the in-memory cache take a lock, so a heap rebuild in one thread cannot drop an expiry entry another thread just added
    • Once the expiry heap is empty, a full in-memory cache drops its oldest entries that have no usable expiry (a NaN ttl), so they cannot grow it past its capacity
  • Message-level and content-block breakpoints both count
  • Pins get their own cache with 10,000 in-memory slots
    • Pins no longer share the router's 200-slot cache with router state
    • The memory debug routes (/memory-usage-in-mem-cache, /memory-usage-in-mem-cache-items, /debug/memory/summary and /debug/memory/details) count the pin cache next to the router's cache
  • Builds on the idea in feat(prompt-caching): match affinity TTL to cache control TTL, and catch system/tools cache blocks #40776 by @nuernber, which targeted the older pin layout

Decision: 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 because 5m and 1h are 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 lifetime

For 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_control and /v1/messages system breakpoints still never reach the pin key or its lifetime, the same as before this PR, and LIT-9460 covers that

User 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

  1. They send POST https://litellm-domain/v1/chat/completions with the system block marked {"type": "ephemeral", "ttl": "1h"} and get x-litellm-model-id: dd1bce74... with cache_creation_input_tokens 5871
  2. Every identical request in the next 5 minutes comes back from the same x-litellm-model-id with cache_read_input_tokens 5871, about $0.0007 each
  3. After 12 quiet minutes, most identical requests come back from x-litellm-model-id: 0d5e0504..., and the first ones there pay a fresh cache_creation_input_tokens 5871, about $0.026 each, while the first deployment's cache still has 48 minutes to live
  4. https://litellm-domain/ui/?page=logs shows the same prompt billed at the cache-write price again every time a quiet gap passes 5 minutes

After: the same requests stay on the deployment that holds the cache for the whole hour, so every one of them reads from it

  1. They send POST https://litellm-domain/v1/chat/completions with the system block marked {"type": "ephemeral", "ttl": "1h"} and get x-litellm-model-id: dd1bce74... with cache_creation_input_tokens 5871
  2. Every identical request in the next 5 minutes comes back from the same x-litellm-model-id with cache_read_input_tokens 5871, about $0.0007 each
  3. After 12 quiet minutes, every identical request still comes back from x-litellm-model-id: dd1bce74... with cache_read_input_tokens 5871 and cache_creation_input_tokens 0
  4. Only after an hour of quiet, when that cache has expired on the provider side anyway, can a request land on the other deployment and write a new one

Relevant issues

Fixes #28427

Linear ticket

Resolves LIT-9459

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. 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
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to 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-5 on two AWS accounts share the model name claude-sonnet with optional_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: dd1bce74 is account A and 0d5e0504 is account B. The after leg's proxies set LITELLM_MODE=PRODUCTION so 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 load

general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
router_settings:
  optional_pre_call_checks: ["prompt_caching"]
  redis_host: 127.0.0.1
  redis_port: <redis port>
model_list:
  - model_name: claude-sonnet
    litellm_params:
      model: bedrock/us.anthropic.claude-sonnet-5-5
      aws_access_key_id: os.environ/AWS_A_ID
      aws_secret_access_key: os.environ/AWS_A_SECRET
      aws_region_name: us-east-1
  - model_name: claude-sonnet
    litellm_params:
      model: bedrock/us.anthropic.claude-sonnet-5-5
      aws_access_key_id: os.environ/AWS_B_ID
      aws_secret_access_key: os.environ/AWS_B_SECRET
      aws_region_name: us-east-1

Each 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/completions and /v1/responses and on the first user block for /v1/messages

import json
import sys
from pathlib import Path

out = Path(sys.argv[1])
nonce = sys.argv[2]
subjects = ("data retention", "incident response", "vendor access", "key rotation", "audit logging", "change review",
            "backup restore", "network egress", "secrets storage", "on-call handoff", "model evaluation", "cost review")
verbs = ("must document", "shall review", "will escalate", "should verify", "is required to approve", "may delegate")
one_hour = {"type": "ephemeral", "ttl": "1h"}
question = "Reply with the single word ok."


def document(kind: str) -> str:
    clauses = (
        f"Clause {i + 1}. The {subjects[i % len(subjects)]} owner {verbs[i % len(verbs)]} every change that touches "
        f"tenant {i * 7 % 97} within {i % 9 + 2} business days, keeps a signed record of who reviewed it, notes the "
        f"ticket number {1000 + i * 13}, and confirms that the rollback plan for region {i % 5 + 1} was tested "
        f"against a staging copy before the change window opened on day {i % 28 + 1}."
        for i in range(60)
    )
    return f"Policy reference {nonce}-{kind}. You answer questions about the operations policy below.\n\n" + "\n".join(clauses)


chat = {
    "model": "claude-sonnet",
    "max_tokens": 5,
    "messages": [
        {"role": "system", "content": [{"type": "text", "text": document("chat"), "cache_control": one_hour}]},
        {"role": "user", "content": question},
    ],
}
messages = {
    "model": "claude-sonnet",
    "max_tokens": 5,
    "messages": [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": document("messages"), "cache_control": one_hour},
                {"type": "text", "text": question},
            ],
        }
    ],
}
responses = {
    "model": "claude-sonnet",
    "max_output_tokens": 16,
    "input": [
        {"role": "system", "content": [{"type": "input_text", "text": document("responses"), "cache_control": one_hour}]},
        {"role": "user", "content": question},
    ],
}
(out / "body_chat.json").write_text(json.dumps(chat))
(out / "body_messages.json").write_text(json.dumps(messages))
(out / "body_responses.json").write_text(json.dumps(responses))

Then each leg booted the proxies and ran this driver on all three endpoints at once, with $PA and $PB the two proxy ports, $out the 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 ports

typeset -A route_of=(chat /v1/chat/completions messages /v1/messages responses /v1/responses)
req() {
  local label=$1 ep=$2 port=$3 f=$out/transcript/${1}_${2}
  local route=$route_of[$ep]
  local ts=$(date -u +%H:%M:%S)
  curl -s -D $f.headers -o $f.body --max-time 240 -X POST http://127.0.0.1:$port$route \
    -H "Authorization: Bearer $(<$out/.mk)" -H 'Content-Type: application/json' --data @$out/body_$ep.json
  local st=$(head -1 $f.headers | tr -d '\r')
  local mid=$(grep -i '^x-litellm-model-id:' $f.headers | awk '{print $2}' | tr -d '\r')
  local cost=$(grep -i '^x-litellm-response-cost:' $f.headers | awk '{print $2}' | tr -d '\r')
  local cc cr usage
  if [[ $ep == responses ]]; then
    cc=$(jq -r '.usage.input_tokens_details.cache_write_tokens // .usage.input_tokens_details.cache_creation_tokens // "None"' $f.body 2>/dev/null)
    cr=$(jq -r '.usage.input_tokens_details.cached_tokens // 0' $f.body 2>/dev/null)
  else
    cc=$(jq -r '.usage.cache_creation_input_tokens // 0' $f.body 2>/dev/null)
    cr=$(jq -r '.usage.cache_read_input_tokens // 0' $f.body 2>/dev/null)
  fi
  usage=$(jq -c -S '.usage' $f.body 2>/dev/null)
  {
    echo "\$ curl -s -D ${label}_${ep}.headers -o ${label}_${ep}.body --max-time 240 -X POST http://127.0.0.1:$port$route -H \"Authorization: Bearer \$LITELLM_MASTER_KEY\" -H 'Content-Type: application/json' --data @body_$ep.json"
    echo $st
    echo "x-litellm-model-id: $mid"
    echo "x-litellm-response-cost: $cost"
    echo "usage: $usage"
  } > $f.txt
  echo "$ts ${label} $ep port=$port model_id=${mid[1,8]} cache_creation=$cc cache_read=$cr cost=$cost status=${st[10,12]}" >> $out/rows_$ep.txt
}
sleep_until() { local now=$(date +%s); (( $1 > now )) && sleep $(( $1 - now )); return 0 }
run_ep() {
  local ep=$1 t0=$(date +%s)
  req 01_t0 $ep $PA
  sleep_until $((t0 + 30)); req 02_within5min $ep $PB
  sleep_until $((t0 + 60)); req 03_within5min $ep $PA
  sleep_until $((t0 + 90)); req 04_within5min $ep $PB
  echo "WITHIN5 $ep $(date -u +%H:%M:%S)" >> $out/ports.txt
  sleep_until $((t0 + 705))
  for i in {1..8}; do
    req $(printf %02d $((4 + i)))_after12min_concurrent $ep $(( i % 2 ? PA : PB )) &
  done
  wait
  for i in {1..3}; do
    sleep 10; req $(printf %02d $((12 + i)))_after12min_sequential $ep $(( i % 2 ? PA : PB ))
  done
}
(run_ep chat) & e1=$!
(run_ep messages) & e2=$!
(run_ep responses) & e3=$!
wait $e1 $e2 $e3

Each row is the time (UTC), the label, the endpoint, the proxy port, the x-litellm-model-id prefix, the cache write and read tokens from usage, x-litellm-response-cost, and the HTTP status. A request after the gap moved when its model id differs from its 01_t0 request, and a fresh cache write costs ~36x a cache read

Before (f101347, the merge base)

Proxies on ports A=57299 and B=42045, Redis on 60129

Before on /v1/chat/completions

21:59:07 01_t0 chat port=57299 model_id=0d5e0504 cache_creation=5873 cache_read=0 cost=0.0259204 status=200
21:59:37 02_within5min chat port=42045 model_id=0d5e0504 cache_creation=0 cache_read=5873 cost=0.00072523 status=200
22:00:07 03_within5min chat port=57299 model_id=0d5e0504 cache_creation=0 cache_read=5873 cost=0.00072523 status=200
22:00:37 04_within5min chat port=42045 model_id=0d5e0504 cache_creation=0 cache_read=5873 cost=0.00072523 status=200
22:10:52 05_after12min_concurrent chat port=57299 model_id=0d5e0504 cache_creation=0 cache_read=5873 cost=0.00072523 status=200
22:10:52 06_after12min_concurrent chat port=42045 model_id=0d5e0504 cache_creation=0 cache_read=5873 cost=0.00072523 status=200
22:10:52 07_after12min_concurrent chat port=57299 model_id=0d5e0504 cache_creation=0 cache_read=5873 cost=0.00072523 status=200
22:10:52 08_after12min_concurrent chat port=42045 model_id=dd1bce74 cache_creation=5873 cache_read=0 cost=0.0259204 status=200
22:10:52 09_after12min_concurrent chat port=57299 model_id=0d5e0504 cache_creation=0 cache_read=5873 cost=0.00072523 status=200
22:10:52 10_after12min_concurrent chat port=42045 model_id=dd1bce74 cache_creation=5873 cache_read=0 cost=0.0259204 status=200
22:10:52 11_after12min_concurrent chat port=57299 model_id=0d5e0504 cache_creation=0 cache_read=5873 cost=0.00072523 status=200
22:10:52 12_after12min_concurrent chat port=42045 model_id=dd1bce74 cache_creation=5873 cache_read=0 cost=0.0259204 status=200
22:11:05 13_after12min_sequential chat port=57299 model_id=0d5e0504 cache_creation=0 cache_read=5873 cost=0.00072523 status=200
22:11:16 14_after12min_sequential chat port=42045 model_id=0d5e0504 cache_creation=0 cache_read=5873 cost=0.00072523 status=200
22:11:27 15_after12min_sequential chat port=57299 model_id=0d5e0504 cache_creation=0 cache_read=5873 cost=0.00072523 status=200

Before on /v1/messages

21:59:07 01_t0 messages port=57299 model_id=dd1bce74 cache_creation=5874 cache_read=0 cost=0.0259204 status=200
21:59:37 02_within5min messages port=42045 model_id=dd1bce74 cache_creation=0 cache_read=5874 cost=0.00072094 status=200
22:00:07 03_within5min messages port=57299 model_id=dd1bce74 cache_creation=0 cache_read=5874 cost=0.00072094 status=200
22:00:37 04_within5min messages port=42045 model_id=dd1bce74 cache_creation=0 cache_read=5874 cost=0.00072094 status=200
22:10:52 05_after12min_concurrent messages port=57299 model_id=0d5e0504 cache_creation=5874 cache_read=0 cost=0.0259204 status=200
22:10:52 06_after12min_concurrent messages port=42045 model_id=0d5e0504 cache_creation=5874 cache_read=0 cost=0.0259204 status=200
22:10:52 07_after12min_concurrent messages port=57299 model_id=0d5e0504 cache_creation=5874 cache_read=0 cost=0.0259204 status=200
22:10:52 08_after12min_concurrent messages port=42045 model_id=0d5e0504 cache_creation=5874 cache_read=0 cost=0.0259204 status=200
22:10:52 09_after12min_concurrent messages port=57299 model_id=0d5e0504 cache_creation=5874 cache_read=0 cost=0.0259204 status=200
22:10:52 10_after12min_concurrent messages port=42045 model_id=dd1bce74 cache_creation=0 cache_read=5874 cost=0.00072094 status=200
22:10:52 11_after12min_concurrent messages port=57299 model_id=0d5e0504 cache_creation=5874 cache_read=0 cost=0.0259204 status=200
22:10:52 12_after12min_concurrent messages port=42045 model_id=0d5e0504 cache_creation=5874 cache_read=0 cost=0.0259204 status=200
22:11:04 13_after12min_sequential messages port=57299 model_id=0d5e0504 cache_creation=0 cache_read=5874 cost=0.00072094 status=200
22:11:15 14_after12min_sequential messages port=42045 model_id=0d5e0504 cache_creation=0 cache_read=5874 cost=0.00072094 status=200
22:11:27 15_after12min_sequential messages port=57299 model_id=0d5e0504 cache_creation=0 cache_read=5874 cost=0.00072094 status=200

Raw output of the request labeled 08_after12min_concurrent on /v1/chat/completions, which moved to account A and paid a fresh 1h cache write

$ curl -s -D 08_after12min_concurrent_chat.headers -o 08_after12min_concurrent_chat.body --max-time 240 -X POST http://127.0.0.1:42045/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' --data @body_chat.json
HTTP/1.1 200 OK
x-litellm-model-id: dd1bce741dfce8efe79ec47a29f7dbf026304da419106dd3528cc5735d2ec038
x-litellm-response-cost: 0.0259204
usage: {"cache_creation_input_tokens":5873,"cache_read_input_tokens":0,"completion_tokens":4,"completion_tokens_details":{"reasoning_tokens":0,"text_tokens":4},"prompt_tokens":5889,"prompt_tokens_details":{"cache_creation_token_details":{"ephemeral_1h_input_tokens":5873,"ephemeral_5m_input_tokens":0},"cache_creation_tokens":5873,"cache_write_tokens":5873,"cached_tokens":0,"text_tokens":16},"total_tokens":5893}

After (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

01:24:51 01_t0 chat port=35123 model_id=dd1bce74 cache_creation=5874 cache_read=0 cost=0.025924799999999998 status=200
01:25:21 02_within5min chat port=37719 model_id=dd1bce74 cache_creation=0 cache_read=5874 cost=0.00072534 status=200
01:25:51 03_within5min chat port=35123 model_id=dd1bce74 cache_creation=0 cache_read=5874 cost=0.00072534 status=200
01:26:21 04_within5min chat port=37719 model_id=dd1bce74 cache_creation=0 cache_read=5874 cost=0.00072534 status=200
01:36:36 05_after12min_concurrent chat port=35123 model_id=dd1bce74 cache_creation=0 cache_read=5874 cost=0.00072534 status=200
01:36:36 06_after12min_concurrent chat port=37719 model_id=dd1bce74 cache_creation=0 cache_read=5874 cost=0.00072534 status=200
01:36:36 07_after12min_concurrent chat port=35123 model_id=dd1bce74 cache_creation=0 cache_read=5874 cost=0.00072534 status=200
01:36:36 08_after12min_concurrent chat port=37719 model_id=dd1bce74 cache_creation=0 cache_read=5874 cost=0.00072534 status=200
01:36:36 09_after12min_concurrent chat port=35123 model_id=dd1bce74 cache_creation=0 cache_read=5874 cost=0.00072534 status=200
01:36:36 10_after12min_concurrent chat port=37719 model_id=dd1bce74 cache_creation=0 cache_read=5874 cost=0.00072534 status=200
01:36:36 11_after12min_concurrent chat port=35123 model_id=dd1bce74 cache_creation=0 cache_read=5874 cost=0.00072534 status=200
01:36:36 12_after12min_concurrent chat port=37719 model_id=dd1bce74 cache_creation=0 cache_read=5874 cost=0.00072534 status=200
01:36:47 13_after12min_sequential chat port=35123 model_id=dd1bce74 cache_creation=0 cache_read=5874 cost=0.00072534 status=200
01:36:58 14_after12min_sequential chat port=37719 model_id=dd1bce74 cache_creation=0 cache_read=5874 cost=0.00072534 status=200
01:37:09 15_after12min_sequential chat port=35123 model_id=dd1bce74 cache_creation=0 cache_read=5874 cost=0.00072534 status=200

After on /v1/messages

01:24:51 01_t0 messages port=35123 model_id=dd1bce74 cache_creation=5875 cache_read=0 cost=0.0259248 status=200
01:25:21 02_within5min messages port=37719 model_id=dd1bce74 cache_creation=0 cache_read=5875 cost=0.00072105 status=200
01:25:51 03_within5min messages port=35123 model_id=dd1bce74 cache_creation=0 cache_read=5875 cost=0.00072105 status=200
01:26:21 04_within5min messages port=37719 model_id=dd1bce74 cache_creation=0 cache_read=5875 cost=0.00072105 status=200
01:36:36 05_after12min_concurrent messages port=35123 model_id=dd1bce74 cache_creation=0 cache_read=5875 cost=0.00072105 status=200
01:36:36 06_after12min_concurrent messages port=37719 model_id=dd1bce74 cache_creation=0 cache_read=5875 cost=0.00072105 status=200
01:36:36 07_after12min_concurrent messages port=35123 model_id=dd1bce74 cache_creation=0 cache_read=5875 cost=0.00072105 status=200
01:36:36 08_after12min_concurrent messages port=37719 model_id=dd1bce74 cache_creation=0 cache_read=5875 cost=0.00072105 status=200
01:36:36 09_after12min_concurrent messages port=35123 model_id=dd1bce74 cache_creation=0 cache_read=5875 cost=0.00072105 status=200
01:36:36 10_after12min_concurrent messages port=37719 model_id=dd1bce74 cache_creation=0 cache_read=5875 cost=0.00072105 status=200
01:36:36 11_after12min_concurrent messages port=35123 model_id=dd1bce74 cache_creation=0 cache_read=5875 cost=0.00072105 status=200
01:36:36 12_after12min_concurrent messages port=37719 model_id=dd1bce74 cache_creation=0 cache_read=5875 cost=0.00072105 status=200
01:36:48 13_after12min_sequential messages port=35123 model_id=dd1bce74 cache_creation=0 cache_read=5875 cost=0.00072105 status=200
01:36:59 14_after12min_sequential messages port=37719 model_id=dd1bce74 cache_creation=0 cache_read=5875 cost=0.00072105 status=200
01:37:10 15_after12min_sequential messages port=35123 model_id=dd1bce74 cache_creation=0 cache_read=5875 cost=0.00072105 status=200

/v1/responses ran the same schedule on both legs and spread across both deployments on both, since it never writes a pin

Raw output of the request labeled 10_after12min_concurrent on /v1/chat/completions, which stayed on account A and read its cache

$ curl -s -D 10_after12min_concurrent_chat.headers -o 10_after12min_concurrent_chat.body --max-time 240 -X POST http://127.0.0.1:37719/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' --data @body_chat.json
HTTP/1.1 200 OK
x-litellm-model-id: dd1bce741dfce8efe79ec47a29f7dbf026304da419106dd3528cc5735d2ec038
x-litellm-response-cost: 0.00072534
usage: {"cache_creation_input_tokens":0,"cache_read_input_tokens":5874,"completion_tokens":4,"completion_tokens_details":{"reasoning_tokens":0,"text_tokens":4},"prompt_tokens":5890,"prompt_tokens_details":{"cache_creation_tokens":0,"cache_write_tokens":0,"cached_tokens":5874,"text_tokens":16},"total_tokens":5894}

Reading: on the before leg, 3 of the 11 requests after the gap on /v1/chat/completions left the deployment holding the prefix and all 3 paid a fresh $0.0259 cache write, while on /v1/messages 10 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

Endpoint Before moved Before new writes After moved After new writes
/v1/chat/completions 3 of 11 3 0 of 11 0
/v1/messages 10 of 11 7 0 of 11 0

The 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's model swapped for an application inference profile ARN copied from us.anthropic.claude-sonnet-5-5, one per account, and model_info.base_model: bedrock/us.anthropic.claude-sonnet-5-5. Deployment ids: e1193ed4 is account A and 7c923541 is 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

Endpoint Base moved Base new writes Tip moved Tip new writes
/v1/chat/completions 5 of 11 8 2 of 11 8

Reading: 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/messages showed the same pattern on both legs

ARN base on /v1/chat/completions
21:59:04 01_t0 chat port=40507 model_id=7c923541 cache_creation=5876 cache_read=0 cost=0.016238199999999998 status=200
21:59:34 02_within5min chat port=54899 model_id=7c923541 cache_creation=0 cache_read=5876 cost=0.00072556 status=200
22:00:04 03_within5min chat port=40507 model_id=7c923541 cache_creation=0 cache_read=5876 cost=0.00072556 status=200
22:00:34 04_within5min chat port=54899 model_id=7c923541 cache_creation=0 cache_read=5876 cost=0.00072556 status=200
22:10:49 05_after12min_concurrent chat port=40507 model_id=7c923541 cache_creation=5876 cache_read=0 cost=0.016238199999999998 status=200
22:10:49 06_after12min_concurrent chat port=54899 model_id=7c923541 cache_creation=5876 cache_read=0 cost=0.016238199999999998 status=200
22:10:49 07_after12min_concurrent chat port=40507 model_id=e1193ed4 cache_creation=5876 cache_read=0 cost=0.016238199999999998 status=200
22:10:49 08_after12min_concurrent chat port=54899 model_id=e1193ed4 cache_creation=5876 cache_read=0 cost=0.016238199999999998 status=200
22:10:49 09_after12min_concurrent chat port=40507 model_id=e1193ed4 cache_creation=5876 cache_read=0 cost=0.016238199999999998 status=200
22:10:49 10_after12min_concurrent chat port=54899 model_id=7c923541 cache_creation=5876 cache_read=0 cost=0.016238199999999998 status=200
22:10:49 11_after12min_concurrent chat port=40507 model_id=7c923541 cache_creation=5876 cache_read=0 cost=0.016238199999999998 status=200
22:10:49 12_after12min_concurrent chat port=54899 model_id=7c923541 cache_creation=5876 cache_read=0 cost=0.016238199999999998 status=200
22:11:01 13_after12min_sequential chat port=40507 model_id=e1193ed4 cache_creation=0 cache_read=5876 cost=0.00072556 status=200
22:11:13 14_after12min_sequential chat port=54899 model_id=7c923541 cache_creation=0 cache_read=5876 cost=0.00072556 status=200
22:11:25 15_after12min_sequential chat port=40507 model_id=e1193ed4 cache_creation=0 cache_read=5876 cost=0.00072556 status=200
ARN tip on /v1/chat/completions
01:24:51 01_t0 chat port=34851 model_id=e1193ed4 cache_creation=5874 cache_read=0 cost=0.0162327 status=200
01:25:21 02_within5min chat port=45319 model_id=e1193ed4 cache_creation=0 cache_read=5874 cost=0.00072534 status=200
01:25:51 03_within5min chat port=34851 model_id=e1193ed4 cache_creation=0 cache_read=5874 cost=0.00072534 status=200
01:26:21 04_within5min chat port=45319 model_id=e1193ed4 cache_creation=0 cache_read=5874 cost=0.00072534 status=200
01:36:36 05_after12min_concurrent chat port=34851 model_id=e1193ed4 cache_creation=5874 cache_read=0 cost=0.0162327 status=200
01:36:36 06_after12min_concurrent chat port=45319 model_id=e1193ed4 cache_creation=5874 cache_read=0 cost=0.0162327 status=200
01:36:36 07_after12min_concurrent chat port=34851 model_id=e1193ed4 cache_creation=5874 cache_read=0 cost=0.0162327 status=200
01:36:36 08_after12min_concurrent chat port=45319 model_id=e1193ed4 cache_creation=5874 cache_read=0 cost=0.0162327 status=200
01:36:36 09_after12min_concurrent chat port=34851 model_id=e1193ed4 cache_creation=5874 cache_read=0 cost=0.0162327 status=200
01:36:36 10_after12min_concurrent chat port=45319 model_id=e1193ed4 cache_creation=5874 cache_read=0 cost=0.0162327 status=200
01:36:36 11_after12min_concurrent chat port=34851 model_id=7c923541 cache_creation=5874 cache_read=0 cost=0.0162327 status=200
01:36:36 12_after12min_concurrent chat port=45319 model_id=e1193ed4 cache_creation=5874 cache_read=0 cost=0.0162327 status=200
01:36:47 13_after12min_sequential chat port=34851 model_id=e1193ed4 cache_creation=0 cache_read=5874 cost=0.00072534 status=200
01:36:58 14_after12min_sequential chat port=45319 model_id=e1193ed4 cache_creation=0 cache_read=5874 cost=0.00072534 status=200
01:37:09 15_after12min_sequential chat port=34851 model_id=7c923541 cache_creation=0 cache_read=5874 cost=0.00072534 status=200

The 1h side off Bedrock was checked with one SDK request per model through its own prompt_caching router at eb396f9, each with a 1h breakpoint on a ~10k token system block. All of the cache write landed in ephemeral_1h_input_tokens on 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 write

The 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_support covers it

Observations from the run, next to the fix but not part of it:

  • /v1/responses never pins on either leg, left alone here
  • The 1h Bedrock cache stayed warm past 12 minutes
  • Each before-leg cache write cost ~36x a read
  • A second router in one process gets no pins, same on the merge base
  • Databricks dropped its own 1h cache on 2 of 3 runs

Audit 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

Rows Cells Base Head
A1-A7, P1-P10, H1-H3 pin ttl per surface and SDK 15 red green
F1-F11, S1-S5, E1-E7 providers, bad input, failover, bursts 13 red green
C1-C4, X1-X2 Redis config and chaos 5 red green
D1-D8 the four memory debug routes count pins 8 red green
M1 key cache heap rebuild, 8 slots green green
U1, U2, UX1 response cache, unusable ttls 13 red green
L1 live Anthropic claude-opus-5-5, chat, 1h block 298 s pin 3598 s pin
L2 live Bedrock us.anthropic.claude-sonnet-5-5, /v1/messages, 1h block 298 s pin 3598 s pin

No row failed. The new cells send 220 requests with a NaN or unusable cache ttl to the local response cache on chat, /v1/messages and /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 request

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • Tool and /v1/messages system breakpoints still get a 5 minute pin, or none
    • Same as the merge base. The pin key cannot see them yet, and LIT-9460 changes both pin keys to fix it

Low

  • /debug/memory/details blocks the event loop about 1 s per call, and once a concurrent chat failed with a SystemError
    • Same on the merge base, since the route calls gc.get_objects() on the event loop, and the fix is tracked as a follow-up
  • Rewriting 1h pins lets the expiry heap grow to twice the slots, about 2.7 MB at 10,000 pins, before a rebuild
    • A rebuild pauses the event loop 13 to 28 ms about once per 10,000 to 20,000 rewrites, and avoiding it needs a different expiry structure, which is more risk than the pause
  • Past 10,000 live pins per worker, the soonest-expiring pins are dropped first, fresh 5 minute pins included
    • The merge base kept pins in the router's shared 200-slot cache, and Redis serves dropped pins back when it is configured
  • Off Bedrock, models without a 1h price keep the 5 minute pin, which only unit tests cover
    • Every Claude model both QA accounts can call has a 1h price, and the older Bedrock ones answer Legacy or end of life
  • Gemini context caches accept any ttl, but their pins stay at 5 minutes
    • Same as the merge base, since no Gemini cost-map entry carries the 1h field
  • /v1/responses requests never get a pin, so their 1h prefix can still move between deployments
    • Same on the merge base, since the pin is only written for chat completions and /v1/messages calls, so it is a separate fix
  • Writes to one in-memory cache now take a lock, so 8 threads writing the same cache ran 5 to 6 times slower in a synthetic stress
    • The proxy at concurrency 12 showed no change, and the lock is what stops the heap race, so a finer lock is more risk than this cost
  • A caller who sends a NaN, 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 worker
    • Same on the merge base, which also stopped caching after a NaN flood, and limiting the ttl a caller can set is a separate fix

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR
  • 62c8450 passes /live-pr-risk
  • eb396f9 passes /live-pr-risk
  • 45534e3 passes /live-pr-risk

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_control TTL: 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). PromptCachingDeploymentCheck and PromptCachingCache use that store; flush_cache clears it too. Proxy memory debug routes now report prompt_caching_pin_cache separately from LLM response cache.

InMemoryCache gains a write lock around set_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. NaN TTL) so floods cannot grow past max_size_in_memory or 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.

…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.
@devin-ai-integration

devin-ai-integration Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor Author

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@codspeed

codspeed Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

⚠️ 1 benchmark spent significant time in system calls

System calls cannot be consistently instrumented, so they are not included in the measure, which understates the real cost. Please switch to the Walltime instrument to accurately measure system calls.

Measurement and system calls

✅ 31 untouched benchmarks


Comparing litellm_prompt_cache_pin_ttl_from_cache_control (9f7c1db) with main (6c78089)1

Open in CodSpeed

Footnotes

  1. No successful run was found on main (4428c4c) during the generation of this report, so 6c78089 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@codecov

codecov Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.15385% with 3 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/router_utils/prompt_caching_cache.py 91.66% 2 Missing ⚠️
litellm/proxy/common_utils/debug_utils.py 93.75% 1 Missing ⚠️

📢 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
@mateo-berri

Copy link
Copy Markdown
Contributor

@litereview code-review

@litereview

litereview Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

✅ code-review

5/5 · Ready for human review

Scope: full · Full PR review.

Completed · Some checks not run.

No correctness findings.

Checks and execution details
  • Passed · Real testing evidence (required): Not applicable: no LLM translation changes in the scoped paths. The PR changes litellm/caching/in_memory_cache.py, litellm/constants.py, litellm/proxy/common_utils/debug_utils.py, litellm/router.py, litellm/router_utils/pre_call_checks/prompt_caching_deployment_check.py and litellm/router_utils/prompt_caching_cache.py, plus tests. None of these files is under litellm/llms/** or litellm/litellm_core_utils/prompt_templates/**. The PR imports supports_bedrock_prompt_cache_ttl but does not change it.
  • Passed · Unit tests for changed modules (optional): Ran uv sync --frozen --all-groups --all-extras and prisma generate, then uv run --frozen pytest -n 4 on tests/unit/caching/test_in_memory_cache.py, tests/unit/router_utils/test_prompt_caching_cache.py, tests/unit/router_utils/pre_call_checks/test_prompt_caching_deployment_check.py, tests/unit/proxy/common_utils/test_debug_utils.py, tests/unit/test_router_order_fallback.py and tests/unit/router_strategy/test_router_routing_groups.py. Result: 247 passed.
  • Not run · Integration tests (tests/integration/routing, tests/integration/caching) (optional): Collection failed with ModuleNotFoundError: No module named 'integration'. These tests import integration._support.client.Gateway and need a running gateway harness, which this sandbox does not have. The Real testing evidence rule does not require them, because no scoped paths changed.
  • Passed · Code inspection of pin TTL and cache changes (optional): Traced PromptCachingDeploymentCheck.async_log_success_event → _honors_one_hour_cache_ttl → PromptCachingCache.async_add_model_id → DualCache.async_set_cache with an explicit ttl. Clearing the in-memory pin before the write lets allow_ttl_override reset the TTL. Router.update_redis_cache and flush_cache now cover the new prompt_caching_pin_cache. Lock order is safe: increment_cache takes _increment_lock before _write_lock, and no path takes them in reverse. InMemoryCache subclasses call super().set_cache. Pin Redis keys are unchanged, and the debug-route response only adds keys, so I found no breaking change.

View review · Reviewed 9f7c1dbf0e90

@veria-ai

veria-ai Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

The 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

@mateo-berri

Copy link
Copy Markdown
Contributor

@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
@mateo-berri

Copy link
Copy Markdown
Contributor

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor

@litereview code-review

…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.
@mateo-berri

Copy link
Copy Markdown
Contributor

@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
@mateo-berri

Copy link
Copy Markdown
Contributor

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor

@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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
@mateo-berri

Copy link
Copy Markdown
Contributor

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@greptile-apps

greptile-apps Bot commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Automatic reviews are disabled for this repository.

@mateo-berri

Copy link
Copy Markdown
Contributor

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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.

@mateo-berri

Copy link
Copy Markdown
Contributor

@litellm-stampbot

@litellm-stampbot

Copy link
Copy Markdown

litellm-stampbot: risk low

Approved at 9f7c1db.

Rules (stampbot/risk_rules.yml):

  • low: no rule flagged it

Judge (gpt-6-luna): low, probability of high 0.64 (high at or above 0.90)

  • risk: high (probability of high 0.64)

Pushes do not re-run this check. Comment @litellm-stampbot again to re-check the new head.

@litellm-stampbot litellm-stampbot Bot added the risk:low Small, isolated, low-risk change label Oct 15, 2026

@kerry-berri kerry-berri left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low risk by rule and by judgement at 9f7c1db

@mateo-berri
mateo-berri merged commit e136e91 into main Oct 15, 2026
146 of 149 checks passed
@mateo-berri
mateo-berri deleted the litellm_prompt_cache_pin_ttl_from_cache_control branch October 15, 2026 04:10
devin-ai-integration Bot added a commit that referenced this pull request Oct 20, 2026
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk:low Small, isolated, low-risk change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Prompt caching router affinity TTL is hardcoded to 5 minutes — breaks 1-hour ephemeral cache routing

2 participants