Works with the AI Agents you already use

    LLM Stream & SSE Surgeon

    by Badung

    1

    Diagnose and fix LLM streaming bugs including ghost token burn, proxy buffering, and broken UTF-8 encoding.

    $3.99

    Secure checkout via Stripe

    Money-back guarantee

    Converts to your local currency at checkout

    Security scanned
    LLM Stream & SSE Surgeon

    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

    1. Apply the headers to your Nginx config if the X-Accel-Buffering header is ignored: proxy_buffering off;.
    2. Deploy the patch and verify with curl -N -X POST [URL] -d '{"messages":[{"role":"user","content":"Hi"}]}'.
    3. Monitor your OpenAI dashboard to confirm Usage stops 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

    1. Trace the lifecycle by mapping the data flow from the Client through the Proxy/Edge to the Route Handler and Upstream LLM SDK.
    2. Classify the failure into the 5-Class Diagnostic Taxonomy to isolate the root cause.
    3. Execute bounded patches using provided patterns for AbortController propagation, anti-buffering headers, and stateful stream readers.
    4. Verify with CLI using specific curl -N and 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. 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. 2

      Sign in to Agensi

      Your agent shows a sign-in link. Sign in and click Allow.

    3. 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.

    Frequently Asked Questions

    This skill provides diagnostic patterns and implementation logic to resolve common streaming failures like 'ghost' token billing from abandoned requests, proxy-induced buffering (Nginx/Cloudflare), and garbled text caused by broken UTF-8 chunks.

    The skill includes implementation patterns for Node.js (including Next.js App Router) and Python (FastAPI), along with configuration templates for Nginx, Cloudflare, and AWS Application Load Balancers.

    You receive a comprehensive diagnostic taxonomy, production-ready code patterns for stateful stream handling and AbortController propagation, and a CLI-based verification protocol to test your fixes.

    Unlike basic AI suggestions, this skill provides the low-level boilerplate required for stateful UTF-8 decoding and signal propagation, ensuring your UI doesn't stall or break when handling multibyte characters across network proxies.

    Yes, the logic is designed to be provider-agnostic and works with the official SDKs for OpenAI, Anthropic, and other major providers that utilize Server-Sent Events (SSE).

    The skill focuses on implementation and debugging logic; it does not include pre-configured telemetry dashboards or real-time monitoring software.

    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.