- Home
- Skills
- APIs & Backend
- LLM Stream & SSE Surgeon
Works with the AI Agents you already use
LLM Stream & SSE Surgeon
by Badung
Diagnose and fix LLM streaming bugs including ghost token burn, proxy buffering, and broken UTF-8 encoding.
$3.99
LLM Stream & SSE Surgeon
Example session with this skill installed
Our Next.js chat endpoint is burning tokens on OpenAI even after people close the tab, and the stream stalls for 10 seconds behind our Nginx proxy.
- Read your context and instructions
- Compiled the llm stream
I have analyzed your streaming lifecycle and identified two primary issues: GHOST_BURN and PROXY_BUFFERING. Your current implementation lacks AbortSignal propagation and requisite anti-buffering headers.
Streaming Reliability Patch
import OpenAI from "openai";
const openai = new OpenAI();
export async function POST(req: Request) {
const { messages } = await req.json();
const abortController = new AbortController();
// Fix: GHOST_BURN - Propagate client disconnect
const onAbort = () => abortController.abort();
req.signal.addEventListener("abort", onAbort, { once: true });
const encoder = new TextEncoder();
const stream = new ReadableStream({
async start(controller) {
try {
const completion = await openai.chat.completions.create(
{ model: "gpt-4o", messages, stream: true },
{ signal: abortController.signal }
);
for await (const chunk of completion) {
if (abortController.signal.aborted) break;
const delta = chunk.choices[0]?.delta?.content ?? "";
if (delta) {
controller.enqueue(
encoder.encode(`data: ${JSON.stringify({ delta })}\n\n`)
);
}
}
} catch (err) {
if (!abortController.signal.aborted) {
controller.enqueue(encoder.encode(`event: error\ndata: {"message": "Stream failed"}\n\n`));
}
} finally {
req.signal.removeEventListener("abort", onAbort);
controller.close();
}
},
cancel() {
abortController.abort();
},
});
return new Response(stream, {
headers: {
"Content-Type": "text/event-stream; charset=utf-8",
"Cache-Control": "no-cache, no-transform",
"X-Accel-Buffering": "no", // Fix: PROXY_BUFFERING
},
});
}
Next steps
- Apply the headers to your Nginx config if the
X-Accel-Bufferingheader is ignored:proxy_buffering off;. - Deploy the patch and verify with
curl -N -X POST [URL] -d '{"messages":[{"role":"user","content":"Hi"}]}'. - Monitor your OpenAI dashboard to confirm
Usagestops immediately upon client disconnect.
Connects securely to your tools. The creator never sees your data.
About this skill
LLM streaming failure in production often goes undetected until you see a massive bill for tokens nobody received or a UI that stalls behind a proxy. Standard HTTP handlers are not designed for the long-lived, stateful connections required by Server-Sent Events (SSE).
What it does
- Diagnose Ghost Token Burn identifies where servers keep generating and billing for tokens after a user has closed their browser tab.
- Fix Proxy Buffering configures headers for Nginx, Cloudflare, and ALBs to prevent Stall-Until-Complete behavior.
- Repair Framing Splits provides stateful UTF-8 decoding and line-buffering logic to prevent garbled multibyte text and dropped JSON frames.
- Prevent Idle Drops implements bounded keepalive heartbeats to keep sockets open during long reasoning pauses or tool calls.
- Error Recovery ensures mid-stream exceptions emit explicit error frames instead of silent 200 OK truncations.
How it works
- Trace the lifecycle by mapping the data flow from the Client through the Proxy/Edge to the Route Handler and Upstream LLM SDK.
- Classify the failure into the 5-Class Diagnostic Taxonomy to isolate the root cause.
- Execute bounded patches using provided patterns for
AbortControllerpropagation, anti-buffering headers, and stateful stream readers. - Verify with CLI using specific
curl -Nand abort commands to confirm the fix in your local or staging environment.
Frameworks & tools
Node.js, Next.js App Router, Python, FastAPI, and common LLM SDKs like OpenAI and Anthropic. Works with proxies including Nginx, Cloudflare, and AWS Application Load Balancers.
Why this beats prompting it yourself
Most LLMs suggest simple fetch loops that fail under real-world network conditions or proxy configurations. This skill provides the low-level boilerplate for stateful UTF-8 decoding and signal propagation that standard boilerplate code usually omits.
Use cases
- Stop expensive token billing for abandoned requests when users navigate away mid-answer.
- Fix garbled characters in non-English streams caused by naive chunk splitting.
- Debug why AI responses work locally but arrive as a single burst in production.
- Implement reliable error handling for Rate Limit or Context Limit errors that occur after headers are flushed.
Known limitations
Does not include runtime metrics or telemetry dashboards. Verification requires manual execution of curl commands against the target environment.
How to use
- 1
Connect your agent to the Agensi MCP
Copy the prompt and paste it into Claude, ChatGPT, Cursor or any agent that supports MCP. It sets up the connection for you. Manual setup
- 2
Sign in to Agensi
Your agent shows a sign-in link. Sign in and click Allow.
- 3
Ask for what you need
Your agent loads this skill and uses it on your task. It always asks before buying a skill.
Reviews
No reviews yet
Be one of the first to try it. Every listed skill goes through the trust checks below.
Security scanned
Checked by our 8-point scan before listing
Fresh listing
Recently published to Agensi
Money-back guarantee
Doesn't do what its page promises? You get your money back.
Trust & safety
Security scan
Security scan passed 11 days ago
Requires
Nothing to install.
Permissions
What's inside
Frequently Asked Questions
New in APIs & Backend
Find more skills like this on the Claude Skills Marketplace, the Codex Skills Marketplace and the Gemini Skills Marketplace, or browse Claude Skills for APIs & Backend.