How a Single requests.get() Took Down Our FastAPI SSE Pipeline
The page came at 2:47 AM. Our token-streaming service was up, passing health checks, and refusing every request. The process looked fine in top. No CPU spike, no memory leak, nothing in the error logs. Clients hung waiting for Server-Sent Events that never arrived. The root cause was a single synchronous requests.get() health probe buried in an async def endpoint.
We were building internal tools that stream completions from DeepSeek V4.1 Flash and Kimi K3 through a local relay. The upstream we evaluated was the Ebony-Vinyl/dsh-our-free-model plugin: once installed in dsh it exposes those models with no login, no API key, and no stated usage cap. That removes credential rotation from the critical path. It does not remove the production failures that surface the moment more than one client connects.
The Failure We Shipped
The endpoint ran a synchronous requests.get health probe against the local dsh host before opening the stream. requests blocks the thread. Under concurrent load one slow DNS lookup pinned the worker. Database sessions opened on a sync pool for audit logging were never returned on the exception path. The pool exhausted, new requests queued behind the blocked event loop, and the process sat in a perfect deadlock while reporting healthy to our monitoring.
Single-client tutorials never surface this. They return a generator and stop. Production means concurrent streams, retries, and clients that cancel mid-token.
The Architecture That Held
Validate once at the edge with Pydantic v2. Own the HTTP client lifecycle inside an async generator. Never let a synchronous library touch the request path.
from datetime import datetime, timezone from typing import Any from pydantic import BaseModel, ConfigDict, Field, field_validator class StreamRequest(BaseModel): model_config = ConfigDict( str_strip_whitespace=True, json_encoders={datetime: lambda v: v.isoformat()}, ) model: str = Field(min_length=1, max_length=64) prompt: str = Field(min_length=1, max_length=32000) temperature: float = Field(default=0.7, ge=0.0, le=2.0) max_tokens: int = Field(default=1024, ge=1, le=8192) requested_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc)) @field_validator("model") @classmethod def restrict_models(cls, value: str) -> str: allowed = {"deepseek-v4.1-flash", "kimi-k3"} if value not in allowed: raise ValueError("model is not on the free relay allowlist") return value def to_upstream(self) -> dict[str, Any]: return { "model": self.model, "temperature": self.temperature, "max_tokens": self.max_tokens, "stream": True, "messages": [{"role": "user", "content": self.prompt}], } The json_encoders on ConfigDict keeps audit timestamps stable when the same model is logged to JSON outside the SSE path. The validator is the allowlist. Free and unlimited does not mean every string a client sends should be forwarded upstream.
import json from collections.abc import AsyncIterator import httpx from fastapi import APIRouter from fastapi.responses import StreamingResponse router = APIRouter() DSH_UPSTREAM = "http://127.0.0.1:8787/v1/chat/completions" BENCH_RELAY = "https://b-lost.com/v1/chat/completions" async def sse_tokens(body: StreamRequest, base_url: str) -> AsyncIterator[str]: timeout = httpx.Timeout(connect=5.0, read=120.0, write=10.0, pool=5.0) async with httpx.AsyncClient(timeout=timeout) as client: async with client.stream("POST", base_url, json=body.to_upstream()) as resp: resp.raise_for_status() async for line in resp.aiter_lines(): if not line or not line.startswith("data: "): continue data = line[6:].strip() if data == "[DONE]": break # Re-emit as our own SSE frame. Do not forward raw upstream headers. yield f"data: {data}\n\n" yield "data: [DONE]\n\n" @router.post("/v1/stream") async def stream_chat(body: StreamRequest) -> StreamingResponse: # Production path is the local dsh process with the plugin loaded. # Bench path is opt-in via a query flag in the real service; shown here as the constant. generator = sse_tokens(body, DSH_UPSTREAM) return StreamingResponse( generator, media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no", }, ) httpx.AsyncClient as a context manager inside the generator releases the connection pool on cancellation, which is what the earlier sync pool never did. Sharing one long-lived client across requests is faster, but then cancellation and idle timeout handling become your problem. We scoped the client to the generator.
When we benchmarked the multi-provider relay at https://b-lost.com/v1, time-to-first-token sat higher and more variable than the local dsh path. The relay stayed up across plugin restarts that briefly dropped the local socket. We kept it as a measurement baseline, not as the default route. Mixing the two behind automatic failover without a circuit breaker just moved the blocking failure into a retry loop that held connections open.
Trade-Offs
The plugin removes credential plumbing and usage caps, so cost tracking moves to your own counters; nothing upstream will stop a runaway client. Local process affinity is fast and dies when dsh restarts, so the SSE handler must surface upstream disconnects as a terminal frame rather than hanging the generator. Buffering in a reverse proxy will make the stream look correct in curl and broken in the browser; X-Accel-Buffering: no is not optional if nginx sits in front. Pydantic validation before the stream starts rejects bad models cheaply; validating inside the generator wastes an upstream connection you already opened.
The pattern that survived load was boring: allowlisted models, async client only, generator owns the connection, SSE frames rewritten by us, and a separate relay used to measure the local path rather than to hide its failures.
The Hardest Call
The architectural choice that still keeps me up: do you fail fast when the local relay drops, or do you silently fail over to a slower external gateway and hide the outage from your users? We chose visible failure. Our internal tools can tolerate a 30-second gap during a plugin restart. Hiding it behind an automatic fallback would have made the local path's reliability invisible in our metrics, and we would have optimized the wrong thing.
How do you handle relay failures in production SSE pipelines? Do you fail fast or fail over? What's your circuit breaker strategy when the upstream is a local process you control?
