Skip to content

fix(router): stop buffering /v1/messages lifecycle frames when no fallback is configured - #39574

Closed
nuernber wants to merge 9 commits into
BerriAI:mainfrom
nuernber:litellm_anthropic_messages_router_fallback_ttfb
Closed

nuernber wants to merge 9 commits into
BerriAI:mainfrom
nuernber:litellm_anthropic_messages_router_fallback_ttfb

Conversation

@nuernber

@nuernber nuernber commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • /v1/messages streams delay message_start until the model finishes thinking
  • This happens even with zero fallback deployments configured
  • A second, independent httpx bug compounds the same delay

How it solves it:

  • Skip mid-stream-fallback buffering when no fallback could ever resolve
  • Stop httpx from withholding small frames below its chunk-size threshold

User Flow

Before: a developer streaming a request through the proxy's /v1/messages endpoint sees no bytes at all for as long as the model spends thinking, even though the exact same request straight to Bedrock starts streaming in about two seconds

  1. They send POST https://<proxy-domain>/v1/messages with model set to a Bedrock adaptive-thinking model (e.g. us.anthropic.claude-sonnet-5), "thinking": {"type": "adaptive"}, "output_config": {"effort": "max"}, and "stream": true
  2. Their client's own timing log shows no data for many seconds, with only an event: ping frame arriving roughly every 15 seconds
  3. The first real event, event: message_start, does not appear until the model finishes its entire thinking pass, which for a large max_tokens ceiling can be a minute or more later
  4. Sending the identical request body directly to Bedrock, bypassing the proxy, returns event: message_start within about two seconds every time, so the developer has no way to tell in advance whether their next call through the proxy will start in two seconds or two minutes

After: the same developer sees event: message_start and event: content_block_start arrive within about two seconds, matching a direct call to Bedrock, and only the model's own thinking time accounts for any further wait before visible content

  1. They send the same POST https://<proxy-domain>/v1/messages with the same body
  2. event: message_start and event: content_block_start arrive within about two seconds
  3. event: ping keepalives may still appear while the model keeps thinking, but only after the real lifecycle events already reached the client
  4. The remaining wait for event: content_block_delta matches the model's own thinking time exactly, the same as calling Bedrock directly

Relevant issues

Fixes #39431

Linear ticket

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/test_litellm/<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

Config the proxy ran with (no fallbacks configured anywhere in the file):

model_list:
- litellm_params:
    model: us.anthropic.claude-sonnet-5
    aws_region_name: us-west-2
  model_info:
    litellm_provider: bedrock
    input_cost_per_token: 2.2e-06
    output_cost_per_token: 1.1e-05
    id: us.anthropic.claude-sonnet-5
  model_name: us.anthropic.claude-sonnet-5

Ran with AWS_BEARER_TOKEN_BEDROCK set (a short-term Bedrock API key), which rules out AWS credential resolution as a factor. Both runs use the same request body (thinking: {"type": "adaptive"}, output_config.effort: "max", max_tokens: 8000) against a live proxy hitting real Bedrock, via python ttfb_litellm_direct.py --runs 1 (MAX_TOKENS=8000)

Before (2ffe6a1)

  1. MAX_TOKENS=8000 LITELLM_API_KEY=<REDACTED> python ttfb_litellm_direct.py --runs 1
  2. Output:
    Run 1/1:   [  16.97s] +   36B  event: ping
    data: {"type": "ping"}
    
    Run 1/1:   [  31.97s] +   36B  event: ping
    data: {"type": "ping"}
    
    Run 1/1:   [  46.97s] +   36B  event: ping
    data: {"type": "ping"}
    
    Run 1/1:   [  61.35s] +  493B  event: message_start
    data: {"type":"message_start","message":{"model":"us.anthro...
    
    Run 1/1: time to first byte 16.904s (EXCEEDED threshold of 10.0s)
    
  3. message_start does not reach the client until 61.35s, three keepalive-ping cycles later, even though this commit already includes the httpx chunk-size fix on its own

After (8f5f42f)

  1. MAX_TOKENS=8000 LITELLM_API_KEY=<REDACTED> python ttfb_litellm_direct.py --runs 1
  2. Output:
    Run 1/1:   [   2.07s] +  493B  event: message_start
    data: {"type":"message_start","message":{"model":"us.anthro...
    
    Run 1/1:   [   2.38s] +  150B  event: content_block_start
    data: {"type": "content_block_start", "index": 0, "co...
    
    Run 1/1:   [  17.38s] +   36B  event: ping
    data: {"type": "ping"}
    
    Run 1/1:   [  32.38s] +   36B  event: ping
    data: {"type": "ping"}
    
    Run 1/1:   [  47.38s] +   36B  event: ping
    data: {"type": "ping"}
    
    Run 1/1:   [  62.38s] +   36B  event: ping
    data: {"type": "ping"}
    
    Run 1/1:   [  63.52s] +  131B  event: content_block_delta
    data: {"type": "content_block_delta", "index": 0, "de...
    
    Run 1/1: time to first byte 2.071s (OK)
    
  3. message_start and content_block_start both reach the client within about two seconds. event: ping still appears afterward while the model keeps thinking, and content_block_delta still doesn't land until 63.52s, but that wait now matches Bedrock's own thinking time (confirmed separately against Bedrock directly, bypassing the proxy) rather than the proxy withholding data it already has

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • fix(router): forward lifecycle frames immediately when no fallbacks configured #39566 already proposes a fix for the same issue with the same two-part diagnosis (router buffering plus httpx chunk_size). Its router-side gate reuses _refusal_fallback_available, which does not check context_window_fallbacks, and forwards lifecycle frames live without marking the stream as having generated content. For a router configured with only context_window_fallbacks, that combination lets a later context-window error still attempt a fallback and append a second message_start onto a stream that already delivered one live, reintroducing the double-lifecycle problem the buffering exists to prevent. This PR's gate (_has_any_configured_fallback) checks all four fallback categories and skips the buffering path entirely rather than partially, so that gap doesn't apply here

Low

  • This PR bundles two fixes rather than one: the httpx chunk_size removal (97da25fc) and the router mid-stream-fallback gate (1b2cbb55, 8f5f42fa). Tested in isolation, the router fix alone gets message_start out fast but leaves content_block_start stuck, since httpx's fixed 1024-byte chunking can split a frame across its boundary independent of the router-level issue - both are needed together for every lifecycle frame to forward live
  • The analogous /chat/completions mid-stream-fallback iterator (_acompletion_streaming_iterator) was not audited for the same unconditional-buffering gap; this PR only touches the anthropic_messages path

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

The Bedrock invoke /v1/messages reader passed chunk_size=1024 to
httpx.Response.aiter_bytes. httpx's ByteChunker is an accumulator, not a
cap: below the threshold it returns nothing at all. A message_start frame
is roughly 500-700 bytes, so it sat in httpx's buffer until enough further
upstream bytes arrived. During a reasoning phase nothing else arrives, so
the preamble was released only once the first content block showed up,
tens of seconds later, past the client's first-byte watchdog.

Dropping chunk_size lets each transport read through as it lands. The
event-stream decoder already emits on botocore event boundaries, so
framing is unaffected.

The /chat/completions invoke path was never affected: it passes
stream_chunk_size, which defaults to None.
…onfigured

Router._aanthropic_messages_streaming_iterator buffers message_start,
content_block_start, and pings until the first content_block_delta arrives, so a
mid-stream provider error can retry against a fallback deployment before any
lifecycle frame commits the client to the current attempt. That buffering ran
unconditionally, with no check for whether the router has any fallback
deployment to retry against in the first place.

For adaptive-thinking Bedrock models, the first content_block_delta doesn't
arrive until the model's entire thinking pass finishes, which can take well
over a minute. With no fallback configured, the buffering held message_start
and content_block_start hostage for that whole window even though the
provider answered in about two seconds, purely because there was nothing to
protect against.

Add Router._has_any_configured_fallback to check whether any fallback
(general, context-window, content-policy, or a catch-all default) could
resolve for the requested model group, and skip the buffering entirely when
it can't: forward the source stream live instead. When a fallback is
configured, behavior is unchanged.
Rewrite _has_any_configured_fallback's loop as a generator expression:
basedpyright rejects a Final-annotated variable assigned inside a for-loop
body (reportGeneralTypeIssues), and ruff format reflows the result.
@codspeed

codspeed Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing nuernber:litellm_anthropic_messages_router_fallback_ttfb (53cacd8) with litellm_internal_staging (35d1d40)

Open in CodSpeed

@greptile-apps

greptile-apps Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR forwards Bedrock Anthropic lifecycle frames without HTTP chunk thresholds and bypasses Router buffering when fallback recovery is disabled or unavailable

  • Removes fixed-size httpx response chunking from the Bedrock Messages adapter
  • Adds fallback-presence checks covering configured, order-based, and weighted recovery
  • Adds streaming latency, cleanup, and fallback regression tests

Confidence Score: 3/5

The PR is not yet safe to merge because fallback matching and weighted-failover viability can still preserve unnecessary lifecycle buffering

Special fallback entries can arm buffering even when their retry branches cannot resolve them, while weighted failover still arms buffering based on configured deployment count rather than currently usable alternatives

Files Needing Attention: litellm/router.py

Important Files Changed

Filename Overview
litellm/router.py Adds no-fallback live forwarding and recovery detection, but special-fallback matching diverges from retry resolution and weighted viability remains incomplete
litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py Removes httpx fixed-size byte chunking so complete Bedrock event frames can be decoded immediately
tests/router_unit_tests/test_router_anthropic_messages_fallback.py Adds focused coverage for configured fallback categories, stripped names, request lists, order levels, and weighted failover
tests/test_litellm/llms/bedrock/messages/invoke_transformations/test_anthropic_claude3_transformation.py Adds a byte-faithful regression test proving message_start arrives before the next upstream event
tests/test_litellm/test_router.py Adds no-fallback forwarding, upstream cleanup, and configured-fallback buffering coverage

Reviews (4): Last reviewed commit: "fix(router): respect disable_fallbacks a..." | Re-trigger Greptile

Comment thread litellm/router.py Resolved
Comment thread litellm/router.py Resolved
Comment thread litellm/router.py Resolved
@veria-ai

veria-ai Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

All previously flagged issues have been addressed. No open security concerns remain on this pull request.

Security review

No open security issues remain on this pull request.

Fixed/addressed: 1 · PR risk: 0/10

@codecov

codecov Bot commented Sep 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 77.55102% with 11 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/router.py 74.41% 11 Missing ⚠️

📢 Thoughts on this report? Let us know!

Close the upstream stream on client disconnect in the no-fallback live-forward
path, matching the buffered path's shielded aclose_if_supported cleanup.
Fix _has_any_configured_fallback to match what a real retry would resolve:
a stripped model-group key and a client-supplied non-standard fallbacks list
both arm a retry but were reported as "nothing configured" before this fix.
@nuernber

nuernber commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai

Comment thread litellm/router.py Resolved
…he fallback gate

_has_any_configured_fallback only checked fallbacks/context_window_fallbacks/
content_policy_fallbacks, missing two retry paths the same dispatcher runs
unconditionally: order-based fallback across deployments at different `order`
levels, and enable_weighted_failover's intra-group re-pick. Either could
still retry a mid-stream error after lifecycle frames were forwarded live,
appending a second message_start onto an already-committed stream.
@nuernber

nuernber commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai

Comment thread litellm/router.py Resolved
Comment thread litellm/router.py Resolved
…ability

Addresses two PR review comments:

1. When disable_fallbacks=True is set on a streaming Anthropic Messages
   request, skip the buffer-until-content path even if fallbacks are
   configured. The request explicitly opted out of recovery, so
   withholding lifecycle frames provides no benefit and only adds latency.

2. When enable_weighted_failover is enabled, only report a recovery path
   if the routing strategy is simple-shuffle AND there are multiple
   deployments available. Weighted failover cannot select an alternative
   deployment for single-deployment groups or non-simple-shuffle
   strategies, so the unconditional return was incorrectly triggering
   buffering with no actual fallback protection.

Both issues caused Anthropic lifecycle frames (message_start,
content_block_start) to be buffered until visible content arrived,
preserving the adaptive-thinking delay this PR is intended to remove.
@nuernber

nuernber commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai

Comment thread litellm/router.py Resolved
Context-window and content-policy chains resolve through
_get_fallback_model_group_for_lookup_groups at retry time, which matches an exact
model-group key only and raises the original exception on a miss. The gate checked
all three lists with the permissive generic resolver, so a wildcard or stripped-name
special chain armed buffer-until-content for a retry that could never run, paying the
lifecycle delay for nothing.

Resolve each list the way the dispatcher does, and fix the weighted-failover test's
stale single-deployment group now that the gate checks re-pick viability.
@nuernber
nuernber requested a review from a team September 8, 2026 16:39
…itellm_anthropic_messages_router_fallback_ttfb

# Conflicts:
#	litellm/router.py
…lper

The buffering gate copied async_function_with_fallbacks' order-scan, so both call
sites reached into litellm.utils._get_deployment_order and the duplicate tripped the
LIT006 and reportPrivateUsage ceilings. Put the scan next to the private accessor as
get_distinct_deployment_orders and call that from both, which drops 4 private reads
where the gate only needed 2 gone.

Also validate the fallback list through a TypeAdapter instead of narrowing it with
cast, and ratchet the basedpyright limits down by what this clears.
@nuernber

nuernber commented Sep 8, 2026

Copy link
Copy Markdown
Contributor Author

Ok, I think this is ready for a maintainer review... @shivamrawat1 @mateo-berri

@yuneng-berri
yuneng-berri deleted the branch BerriAI:main September 13, 2026 04:48
@yuneng-berri yuneng-berri reopened this Sep 13, 2026
@devin-ai-integration
devin-ai-integration Bot changed the base branch from litellm_internal_staging to main September 23, 2026 14:45
@github-actions

Copy link
Copy Markdown
Contributor

#39431 was fixed by #43600 on main, so this pull request is closed. Reopen it if something was missed.

@github-actions github-actions Bot closed this Sep 29, 2026
@nuernber
nuernber deleted the litellm_anthropic_messages_router_fallback_ttfb branch September 29, 2026 18:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: /v1/messages streaming delays message_start until the model's thinking pass finishes, even with no fallbacks configured

2 participants