mediumAI Engineering

How does streaming work in LLM APIs and why does it matter for UX?

1.1k views
01

Understand the problem

SSE token streams, time-to-first-token, and rendering partial responses safely.

streamingsselatencyux
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Read the code

Streaming with cancellation propagated
export async function POST(req: Request) {
  const abort = new AbortController();
  req.signal.addEventListener("abort", () => abort.abort());   // user left → stop paying

  const stream = await client.messages.create(
    { model, max_tokens: 1024, stream: true, messages: await req.json() },
    { signal: abort.signal },
  );

  return new Response(new ReadableStream({
    async start(controller) {
      for await (const event of stream) {
        if (event.type === "content_block_delta")
          controller.enqueue(sse(event.delta.text));           // relay, never accumulate
      }
      controller.close();
    },
  }), { headers: { "Content-Type": "text/event-stream", "X-Accel-Buffering": "no" } });
}
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.