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.
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.5sPrefill +10.0sDecode) — half your users think the tab crashed and hit Refresh! - With Streaming (
stream=Trueover Server-Sent EventsSSE): The very first word appears on screen in0.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
Total End-to-End Latency = TTFT + (Output Tokens × TPOT)
TTFT(Time To First Token): Network RTT + Queueing + Prefill across Input Tokens. ReduceTTFTby 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 Status | Meaning | Retryable? | Correct Engineering Action |
|---|---|---|---|
400 / 422 | Invalid JSON schema, context length exceeded, bad param | ❌ NEVER | Fix payload / trim context; retrying wastes time |
401 / 403 | Invalid/revoked API key or org permission | ❌ NEVER | Page on-call immediately; fail fast |
429 | Rate Limit (RPM or TPM quota hit) | ✅ YES | Honor Retry-After header OR Exponential Backoff + Jitter |
500 / 502 / 503 / 529 | GPU node crash / Anthropic 529 Overloaded | ✅ YES | Retry 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:
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:
Primary GPU cluster saturated -> Caught cleanly BEFORE sending HTTP 200 headers to browser!
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:
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)
- 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 passsignal: req.signal! - 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! SetCache-Control: no-cache, no-transformandX-Accel-Buffering: no. - Retrying Non-Idempotent Tool Loops Blindly: Wrapping an entire multi-step agent loop (including
charge_card()orsend_slack_alert()) inside a naive retry decorator causes duplicate side effects when step 4 hits a429! Retry only the stateless LLM inference call, and attachidempotency_keys to every external write tool.
Module 3.3 Mastery Check — Streaming, Retries & Resilience
Keep Exploring: Related Lessons & Tools
All Courses →Convert Unix epoch seconds/milliseconds to ISO-8601 and local timezones, and bulk-generate UUID v4, time-ordered UUID v7, and sortable ULIDs.
Paste any Python, JS, Java, or C++ snippet to estimate Time & Space complexity, or enter input size N to see which algorithms pass in 1s.