Course
AI · Module 03: Structured Outputs & Reliable PipelinesTutorial 9 of 21
AI Course·~1.5 hrs

3.3 Streaming (SSE), Retries, Rate Limits & Truncation Handling

Turn fragile localhost LLM prototypes into resilient 99.95%-uptime backend services: master Server-Sent Events (SSE) streaming, TTFT vs TPOT latency math, jittered 429/529 retries, provider fallbacks, and truncation recovery.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

1. Why Streaming (SSE) Changes Everything for Perceived Speed

Suppose a detailed code explanation generates 600 output tokens at 60 tokens/sec:

  • Without Streaming (stream=False): The user stares at a frozen spinner for 10.5 full seconds (0.5s Prefill + 10.0s Decode) — half your users think the tab crashed and hit Refresh!
  • With Streaming (stream=True over Server-Sent Events SSE): The very first word appears on screen in 0.45 seconds (TTFT), and text flows faster than human reading speed (~4 words/sec vs ~45 words/sec generated)!

The Two Latency Metrics Every AI Engineer Tracks

TEXT
Total End-to-End Latency = TTFT + (Output Tokens × TPOT)
  • TTFT (Time To First Token): Network RTT + Queueing + Prefill across Input Tokens. Reduce TTFT by shrinking prompts, activating KV Prompt Caching, or picking a Flash/Mini model.
  • TPOT / ITL (Time Per Output Token / Inter-Token Latency): Milliseconds per decoded token (~8 ms – 25 ms). Reduce total decode wait by streaming to UI and cutting verbose output schemas!

Why SSE (text/event-stream) Beats WebSockets for LLM Streaming

LLM generation is request → unidirectional token stream (client sends 1 JSON POST; server pushes data: {...}\n\n chunks over standard HTTP/2). Unlike WebSockets, Server-Sent Events (SSE) work seamlessly through standard corporate proxies, CDNs, Next.js Route Handlers, and FastAPI StreamingResponse with zero sticky-connection headaches! (Reserve WebSockets/WebRTC strictly for bidirectional real-time voice audio.)


2. Production Resilience: Transient Errors, 429 Rate Limits & Jittered Backoff

Cloud GPU clusters run near 95% utilization. At scale, your backend will encounter transient HTTP errors every single day:

HTTP StatusMeaningRetryable?Correct Engineering Action
400 / 422Invalid JSON schema, context length exceeded, bad param❌ NEVERFix payload / trim context; retrying wastes time
401 / 403Invalid/revoked API key or org permission❌ NEVERPage on-call immediately; fail fast
429Rate Limit (RPM or TPM quota hit)✅ YESHonor Retry-After header OR Exponential Backoff + Jitter
500 / 502 / 503 / 529GPU node crash / Anthropic 529 Overloaded✅ YESRetry 2× with jitter, then fail over to secondary model/provider!

Why "Full Jitter" Prevents Thundering Herds

If 200 concurrent worker tasks hit a 429 at 12:00:00.000 and all sleep for an exact deterministic 2.000s, all 200 slam the API again simultaneously at 12:00:02.000 and fail again! Always add random jitter:

PYTHON
sleep_seconds = min(max_cap, random.uniform(0, base_delay * (2 ** attempt)))

3. Wire-Level Trace: Resilient Streaming + Mid-Stream Truncation Guard

What happens if a stream disconnects at token #180, or hits max_output_tokens mid-JSON? Click Next to trace a production-hardened streaming + fallback lifecycle:

Tracing SSE Streaming, 529 Failover & Finish-Reason Validation
Interactive LLM Pipeline Tracer · Step 1 of 3 (1. Primary Provider Returns 529 Overloaded Before First Token)
Wire Telemetry:latency=210mscost=$0.00000
1→try:
2→ stream = primary_client.stream(model="claude-sonnet-4...", max_tokens=1024)
3→except (RateLimitError, Overloaded529Error):
4 stream = backup_client.stream(model="gpt-4o", max_output_tokens=1024)
5for delta in stream: yield sse_event("token", delta)
6if stream.finish_reason == "length": yield sse_event("warning", "TRUNCATED")
Pre-Stream Fault DetectedHTTP 529 OVERLOADED
Primary GPU cluster saturated -> Caught cleanly BEFORE sending HTTP 200 headers to browser!
What's Happening: Crucial detail: once you start streaming tokens to the user, switching models mid-sentence is jarring. Catch pre-first-token 429/529s and fail over transparently!

4. Production SDK Code: SSE Streaming + Jittered Retry & Truncation Checks

Good news: the official openai, anthropic, and google-genai Python/TS SDKs already include 2 built-in jittered retries on 429 and 5xx by default (max_retries=2)! Here is how to stream cleanly and guard against truncation across every stack:

SDK:
from openai import OpenAI, APIConnectionError, RateLimitError, APIStatusError

# Official SDK automatically retries 429 & 5xx with exponential backoff + jitter!
client = OpenAI(max_retries=3, timeout=30.0)

def stream_explanation(prompt: str) -> str:
  chunks: list[str] = []
  with client.responses.stream(
      model="gpt-4o-mini",
      input=prompt,
      max_output_tokens=800,
  ) as stream:
      for event in stream:
          if event.type == "response.output_text.delta":
              print(event.delta, end="", flush=True)
              chunks.append(event.delta)

      final = stream.get_final_response()
      if final.status == "incomplete":
          raise RuntimeError(f"Output truncated: {final.incomplete_details}")
  return "".join(chunks)

5. What Breaks in Production (War Stories)

  1. Not Propagating AbortController (req.signal) on User Stop/Disconnect: When a user clicks "Stop generating" or navigates away after 1 second, if your Next.js/FastAPI server doesn't forward the abort signal to the upstream LLM stream, you keep paying for the remaining 1,500 generated output tokens for nobody! Always pass signal: req.signal!
  2. Reverse Proxy Buffering Killing SSE (Nginx / Compression): Deploying SSE behind Nginx or middleware compression often buffers 4 KB chunks — so your "streaming" UI freezes for 6 seconds and dumps paragraphs in bursts! Set Cache-Control: no-cache, no-transform and X-Accel-Buffering: no.
  3. Retrying Non-Idempotent Tool Loops Blindly: Wrapping an entire multi-step agent loop (including charge_card() or send_slack_alert()) inside a naive retry decorator causes duplicate side effects when step 4 hits a 429! Retry only the stateless LLM inference call, and attach idempotency_keys to every external write tool.

Module 3.3 Mastery Check — Streaming, Retries & Resilience

Q1.Which two factors govern total perceived response time in a streaming LLM UI (`TTFT` and `TPOT`)?
Q2.Why MUST retry logic on `429 Too Many Requests` include random jitter alongside exponential backoff?
Q3.Why should your Next.js / FastAPI streaming route forward the client's `AbortSignal` (`req.signal`) to the upstream LLM SDK call?
Q4.Which HTTP error code should NEVER be retried automatically with the exact same request payload?

Keep Exploring: Related Lessons & Tools

All Courses →