---
title: "Retry LLM Streams Without Duplicate Output - API7.ai"
description: "Test LLM gateway retry and failover at the first-chunk boundary so pre-output failures can move safely while mid-stream failures stay explicit."
url: "https://api7.ai/blog/llm-streaming-retry-failover"
---

[Blog](https://api7.ai/blog)

[Products](https://api7.ai/category/products)[Technology](https://api7.ai/category/technology)[Ecosystem](https://api7.ai/category/ecosystem)[Case Study](https://api7.ai/category/usercase)[Team & Community](https://api7.ai/category/community)

Search

⌘ + K

[Blog](https://api7.ai/blog)

Technology

# Retry LLM Streams Without Duplicate Output

[![Yilia Lin](https://github.com/Yilialinn.png)](https://github.com/Yilialinn)

[Yilia Lin](https://github.com/Yilialinn)

November 23, 2026

[Technology](https://api7.ai/category/technology)

An LLM gateway can retry or fail over a stream safely only while it still owns the complete response boundary. Once a chunk has reached the caller, silently starting another model can duplicate text, tool calls, usage, and side effects. The safe default is therefore:

- **Before the first delivered chunk:** retry the same target or move to an allowed fallback.
- **After the first delivered chunk:** stop the stream with an explicit error; let the application decide whether to keep the partial answer and start a new turn.

This guide builds an acceptance test around that boundary for **AISIX OSS 1.11.0**. It also explains a configuration detail that changes the behavior: AISIX withholds the downstream `200` for first-chunk failover only when a model or routing resource explicitly configures `stream_timeout` or `timeout`. A deployment-wide timeout is a backstop; it does not opt the resource into pre-`200` peeking.

The boundary matters across gateways. LiteLLM's November 20, 2026 release fixed Responses streams that retried after output had reached the client or restarted on fallback after reasoning output. That release is evidence of the problem, not evidence for AISIX behavior; the AISIX claims below are pinned to its v1.11.0 source and end-to-end tests.

## Model the Stream as a Commit Point

Treat the first downstream chunk as a commit point:

```
request accepted
  ├─ connect fails ─────────────── retry/fail over may be safe
  ├─ first-chunk timeout ───────── retry/fail over may be safe
  ├─ error before first chunk ──── retry/fail over may be safe
  └─ first chunk delivered  ← commit point
       ├─ later timeout ────────── terminate; do not splice a backup
       ├─ provider disconnect ──── terminate; expose partial outcome
       └─ client disconnect ────── cancel and account for observed work
```

“Safe” still has limits. A provider may have received and billed a generation even if the gateway saw no chunk. A retry can therefore add cost. The claim is narrower: before output is committed, the gateway can preserve one coherent caller-visible answer. It cannot prove that the upstream performed no work.

## Configure an Explicit First-Chunk Budget

Assume `chat-primary` and `chat-backup` are direct models. Define a failover group whose primary has a resource-level `stream_timeout`:

```
{
  "display_name": "chat-primary",
  "provider": "openai",
  "model_name": "gpt-4o-mini",
  "provider_key_id": "pk-primary",
  "stream_timeout": 2500,
  "retries": 0
}
```

```
{
  "display_name": "chat-backup",
  "provider": "openai",
  "model_name": "gpt-4o-mini",
  "provider_key_id": "pk-backup",
  "stream_timeout": 5000,
  "retries": 0
}
```

```
{
  "display_name": "chat-resilient",
  "routing": {
    "strategy": "failover",
    "targets": [
      { "model": "chat-primary" },
      { "model": "chat-backup" }
    ]
  }
}
```

The exact value must come from observed time-to-first-chunk distributions for the provider and model. A budget below normal reasoning latency creates unnecessary failover and double billing. A budget far above the application's patience makes the fallback irrelevant.

In AISIX 1.11.0, an explicitly configured `stream_timeout` bounds both the wait for the first chunk and later gaps between chunks. A `timeout` can also supply the resource-level streaming budget when no dedicated `stream_timeout` exists. Setting a resource timeout to `0` opts out according to the documented precedence. Verify the effective configuration rather than assuming a deployment default has the same commit behavior.

## Disable SDK Retries During Gateway Tests

Test one retry layer at a time. If the client SDK retries while the gateway also retries, upstream call counts become ambiguous.

With the OpenAI Python SDK:

```
from openai import OpenAI

client = OpenAI(
    api_key="test-caller-key",
    base_url="http://127.0.0.1:8080/v1",
    max_retries=0,
)

stream = client.chat.completions.create(
    model="chat-resilient",
    messages=[{"role": "user", "content": "Explain the retry boundary in one paragraph."}],
    stream=True,
)

for event in stream:
    text = event.choices[0].delta.content
    if text:
        print(text, end="", flush=True)
```

Use non-production provider keys and a mock upstream for fault injection. Record the request ID, target attempts, timestamps, downstream chunks, terminal status, and usage evidence for every case.

## Run the Four Required Cases

### Case 1: Connection Failure Before Output

Make the primary refuse the connection. The backup should receive the request, and the caller should see only the backup stream.

Pass conditions:

- no primary content reaches the caller;
- exactly one coherent stream reaches the caller;
- attempt evidence shows the primary failure followed by the backup;
- the logical request ID correlates both attempts;
- usage or cost evidence does not hide the failed attempt when the provider billed it.

### Case 2: First-Chunk Timeout

Have the primary accept the connection but delay its first event beyond `stream_timeout`. Have the backup return promptly.

Pass conditions:

- the downstream `200` and body are not committed from the primary;
- the backup's first event starts the only caller-visible answer;
- the primary does not appear later in the stream;
- the timeout is classified separately from a provider `5xx`;
- the observed fallback latency stays within the application's total waiting budget.

### Case 3: Mid-Stream Stall

Have the primary emit the string `alpha` followed by a space, then stall longer than `stream_timeout`. Keep the backup healthy.

Pass conditions:

- the caller receives `alpha` plus a trailing space and then an explicit stream error or termination;
- the caller does not receive backup text appended to that partial output;
- the backup receives no request for this logical attempt;
- telemetry records a partial/failed stream rather than a success;
- the application marks the visible text as incomplete.

AISIX v1.11.0's end-to-end test asserts this exact boundary: a first chunk reaches the caller, the later read timeout surfaces as an error, and the backup remains untouched.

### Case 4: Failure After a Tool or Reasoning Event

Repeat the mid-stream case where the first event contains reasoning metadata or a tool call instead of visible text. “No text yet” does not mean “no output committed.” The caller may already have received a tool invocation or stateful event.

Pass conditions:

- any delivered event counts as crossing the commit point;
- the gateway does not restart the stream on another model;
- the application does not execute the same tool call twice;
- a new attempt, if the user requests one, has a new operation ID and idempotency policy.

## Validate the Captured Transcript

Normalize each test into JSON Lines. One row represents one downstream event or upstream attempt:

```
{"case":"first_chunk_timeout","kind":"attempt","target":"primary","outcome":"timeout","delivered":false}
{"case":"first_chunk_timeout","kind":"attempt","target":"backup","outcome":"success","delivered":true}
{"case":"first_chunk_timeout","kind":"chunk","target":"backup","sequence":1,"text":"backup answer"}
{"case":"mid_stream_stall","kind":"chunk","target":"primary","sequence":1,"text":"alpha "}
{"case":"mid_stream_stall","kind":"attempt","target":"primary","outcome":"timeout","delivered":true}
```

The following dependency-free validator rejects a case that switches targets after the first downstream chunk or produces a non-increasing chunk sequence:

```
#!/usr/bin/env python3
import json, sys
from collections import defaultdict

cases = defaultdict(list)
for line in open(sys.argv[1], encoding="utf-8"):
    if line.strip():
        row = json.loads(line)
        cases[row["case"]].append(row)

failed = False
for case, rows in sorted(cases.items()):
    case_failed = False
    committed_target = None
    last_sequence = 0
    for row in rows:
        if row["kind"] == "chunk":
            sequence = int(row["sequence"])
            if sequence <= last_sequence:
                print(f"FAIL {case}: chunk sequence {sequence} after {last_sequence}")
                case_failed = True
            last_sequence = sequence
            if committed_target is None:
                committed_target = row["target"]
            elif row["target"] != committed_target:
                print(f"FAIL {case}: switched from {committed_target} to {row['target']} after commit")
                case_failed = True
        if committed_target and row["kind"] == "attempt" and row.get("delivered"):
            if row["target"] != committed_target:
                print(f"FAIL {case}: delivered attempt from {row['target']} after {committed_target}")
                case_failed = True
    failed = failed or case_failed
    if case_failed:
        continue
    if committed_target:
        print(f"PASS {case}: committed target={committed_target}, chunks={last_sequence}")
    else:
        print(f"PASS {case}: no downstream chunk committed")

raise SystemExit(1 if failed else 0)
```

Run it with:

```
python3 validate_stream_contract.py stream-events.jsonl
```

This validator checks transcript consistency, not gateway behavior by itself. Its result is only as trustworthy as the attempt and chunk capture supplied to it.

## Decide What the Application Does After a Partial Stream

The gateway should not hide a mid-stream failure, but the application still needs a user-facing policy. Choose one:

| Policy                                     | Use when                                          | Required safeguard                                                        |
| ------------------------------------------ | ------------------------------------------------- | ------------------------------------------------------------------------- |
| Keep partial text and mark it interrupted  | Partial prose may still be useful                 | Never label it complete; offer an explicit retry                          |
| Remove partial text and start a new answer | The UI can clearly show regeneration              | Preserve the failed attempt in telemetry and avoid duplicate side effects |
| Ask the user before retrying               | Cost or side effects are material                 | Explain that a new generation may differ                                  |
| Do not retry automatically                 | Tool calls, payments, or writes may have occurred | Reconcile operation state before another attempt                          |

Do not ask a backup model to “continue” an arbitrary partial answer unless the provider contract, conversation state, tool state, and application UI all make the seam explicit. Text continuation is not equivalent to resuming the same generation.

## Account for Retries and Fallbacks

One logical request can create multiple billable attempts. Keep these dimensions separate:

- logical request count;
- upstream attempt count;
- target and provider for each attempt;
- whether any downstream event was committed;
- terminal outcome;
- provider-reported or estimated usage per attempt;
- retry/fallback reason;
- caller cancellation.

Do not sum a request-level aggregate and its underlying attempts twice. Do not call a failed pre-output attempt free merely because the caller saw no tokens.

## Production Acceptance Checklist

- Set the first-chunk budget from observed distributions for each provider/model class.
- Test connection failure, first-chunk timeout, mid-stream stall, and post-tool/reasoning failure.
- Disable client retries while validating gateway retries.
- Prove that the backup is untouched after a downstream chunk is committed.
- Correlate every upstream attempt with one logical request ID.
- Make partial output explicit in the application.
- Add idempotency and reconciliation before retrying tool calls or writes.
- Count and price every attempt, including failed attempts when usage is available.
- Re-run after changing gateway version, provider adapter, routing policy, timeout, retry budget, or SDK.

The reliable contract is not “the gateway always returns an answer.” It is “the gateway never silently combines two attempts into one apparently coherent stream.”

## Further Reading

- [AISIX OSS v1.11.0 source](https://github.com/api7/aisix/tree/v1.11.0)
- [LiteLLM v1.110.2 release notes](https://docs.litellm.ai/release_notes/v1.110.2/v1-110-2)
- [How to Differential-Test LLM Routing Changes](https://api7.ai/blog/llm-routing-differential-testing)
- [OpenAI Responses API with AISIX: A Multi-Provider Guide](https://api7.ai/blog/openai-responses-api-aisix)

Tags:

[AI Gateway](https://api7.ai/tags/ai-gateway)

[LLM](https://api7.ai/tags/llm)

[Reliability](https://api7.ai/tags/reliability)

[Testing](https://api7.ai/tags/testing)

Share article link

Share

Related Posts

[![Private LLM Gateway: Secure vLLM, SGLang, and Ollama](https://static.api7.ai/uploads/2026/09/15/4CMHboqS_private-llm-gateway.webp)](https://api7.ai/blog/private-llm-gateway)

## [Private LLM Gateway: Secure vLLM, SGLang, and Ollama](https://api7.ai/blog/private-llm-gateway)

[![AI Gateway Cost Control: Attribute Spend and Test Budgets](https://static.api7.ai/uploads/2026/10/27/d5zARKBO_cost-control-cover.webp)](https://api7.ai/blog/ai-gateway-cost-control)

## [AI Gateway Cost Control: Attribute Spend and Test Budgets](https://api7.ai/blog/ai-gateway-cost-control)

Table of Contents

- [Model the Stream as a Commit Point](#model-the-stream-as-a-commit-point)

- [Configure an Explicit First-Chunk Budget](#configure-an-explicit-first-chunk-budget)

- [Disable SDK Retries During Gateway Tests](#disable-sdk-retries-during-gateway-tests)

- [Run the Four Required Cases](#run-the-four-required-cases)

  - [Case 1: Connection Failure Before Output](#case-1-connection-failure-before-output)
  - [Case 2: First-Chunk Timeout](#case-2-first-chunk-timeout)
  - [Case 3: Mid-Stream Stall](#case-3-mid-stream-stall)
  - [Case 4: Failure After a Tool or Reasoning Event](#case-4-failure-after-a-tool-or-reasoning-event)

- [Validate the Captured Transcript](#validate-the-captured-transcript)

- [Decide What the Application Does After a Partial Stream](#decide-what-the-application-does-after-a-partial-stream)

- [Account for Retries and Fallbacks](#account-for-retries-and-fallbacks)

- [Production Acceptance Checklist](#production-acceptance-checklist)

- [Further Reading](#further-reading)

## Related Posts

[![How to Differential-Test LLM Routing Changes](https://static.api7.ai/uploads/2026/11/16/5FzNRmiG_llm-routing-differential-testing.webp)](https://api7.ai/blog/llm-routing-differential-testing)

Technology

November 16, 2026

#### [How to Differential-Test LLM Routing Changes](https://api7.ai/blog/llm-routing-differential-testing)

Build a behavior contract for an LLM gateway router, compare old and new decisions, and catch retry, fallback, streaming, and side-effect regressions.

[AI Gateway](https://api7.ai/tags/ai-gateway)

[LLM Routing](https://api7.ai/tags/llm-routing)

[Testing](https://api7.ai/tags/testing)

[![How to Evaluate an LLM Model Ensemble Before Production](https://static.api7.ai/uploads/2026/11/24/zkNU5lkf_model-ensemble-evaluation.webp)](https://api7.ai/blog/model-ensembles-panel-judge)

Technology

June 17, 2026

#### [How to Evaluate an LLM Model Ensemble Before Production](https://api7.ai/blog/model-ensembles-panel-judge)

Compare an AISIX model ensemble with a direct-model baseline using task quality, severe errors, latency, total usage, and failure-path acceptance tests.

[AISIX](https://api7.ai/tags/aisix)

[AI Gateway](https://api7.ai/tags/ai-gateway)

[LLM](https://api7.ai/tags/llm)

[![AI Gateway Configuration Changes: Validate, Reload, Verify, and Roll Back](https://static.api7.ai/uploads/2026/11/09/dGL3lHkE_ai-gateway-configuration-change-runbook-v2.webp)](https://api7.ai/blog/ai-gateway-configuration-change-runbook)

Technology

November 9, 2026

#### [AI Gateway Configuration Changes: Validate, Reload, Verify, and Roll Back](https://api7.ai/blog/ai-gateway-configuration-change-runbook)

Use a four-gate runbook to validate an AI gateway configuration, apply it safely, prove the effective state, and roll back without confusing readiness with freshness.

[AI Gateway](https://api7.ai/tags/ai-gateway)

[AISIX](https://api7.ai/tags/aisix)

[Platform Engineering](https://api7.ai/tags/platform-engineering)
