Back to all posts
·7 min read

Streaming LLM responses: SSE in ASP.NET Core, cancellation and error handling in React

Waiting for a long answer from a language model means, from the user's point of view, staring at an empty screen. Nothing appears for a few seconds, sometimes longer, until the model has produced the whole response. Yet the model already generates text piece by piece. Forwarding those pieces to the screen as they arrive does not change the total time, but it shortens the perceived wait considerably and lets users see early on whether the answer is heading in the right direction.

Streaming looks simple at first: the server writes chunks, the client reads them. In practice, the real work lies in cancellation, proxy buffering, dropped connections, error reporting and persisting the finished response. In this post I look at serving a stream from ASP.NET Core over Server-Sent Events (SSE) and consuming it reliably in React.

Why SSE?

There are several ways to push data continuously from server to client: WebSocket, SignalR, long-running HTTP responses and SSE. An LLM response is a one-way stream: the client sends a request, the server returns a series of chunks, and the stream ends. For this scenario, SSE is usually sufficient and the simplest option.

SSE is an ordinary HTTP response. The content type is text/event-stream, and the body consists of events separated by blank lines. Each event can contain event: and data: lines. Because it is plain HTTP, your existing authentication, authorization, rate limiting and logging keep working as they are. The connection management and scaling complexity that WebSocket brings is better reserved for cases where you truly need bidirectional communication.

The browser's built-in EventSource only supports GET requests and cannot send custom headers. Since chat requests usually send the message history in a POST body, reading the response body with fetch on the client is the more flexible route.

Server side: writing events

Your model provider's SDK typically yields chunks through something like IAsyncEnumerable. In the example below I abstract this behind an IChatModel interface. The endpoint writes each chunk as an SSE event and sends it immediately:

app.MapPost("/api/chat/stream", async (
    ChatRequest request,
    IChatModel model,
    HttpContext http,
    CancellationToken ct) =>
{
    http.Response.ContentType = "text/event-stream";
    http.Response.Headers.CacheControl = "no-cache";
    http.Response.Headers["X-Accel-Buffering"] = "no";

    await foreach (var chunk in model.StreamAsync(request.Messages, ct))
    {
        var json = JsonSerializer.Serialize(new { text = chunk });
        await http.Response.WriteAsync($"event: delta\ndata: {json}\n\n", ct);
        await http.Response.Body.FlushAsync(ct);
    }

    await http.Response.WriteAsync("event: done\ndata: {}\n\n", ct);
});

A few details matter here. Encoding the chunk as JSON instead of writing the raw text into the data: line prevents line breaks inside the text from breaking the event format. Calling FlushAsync after every write ensures the data is sent without piling up on the server. Finally, sending an explicit done event lets the client distinguish between "the stream ended normally" and "the connection dropped".

Intermediaries and buffering

Locally, streaming works fine, but in production the response suddenly arrives in one piece. The most common cause is a layer in between buffering the response. Reverse proxies, load balancers and compression middleware may collect the response and send it in bulk for performance reasons.

To prevent this, there are a few things to check. With Nginx-based proxies, the X-Accel-Buffering: no header or disabling buffering for the relevant location helps. If the response compression middleware compresses text/event-stream, it may hold chunks back; excluding this content type from compression is the safer choice. The idle timeout of load balancers matters too: if the model thinks for a long time without producing any chunk, the connection may be closed. Sending a comment line starting with a colon (: ping) at regular intervals keeps the connection alive, and the client ignores these lines.

These settings need to be verified in the real deployment chain, not just locally. A simple check is to call the endpoint with curl -N and see whether the chunks arrive over time or all at once.

Client side: reading the stream

In React, we can send the request with fetch and read the response body piece by piece with a reader. A chunk arriving from the network may not contain a complete event, or it may contain several. That is why incoming data has to be accumulated in a buffer and split on blank lines:

async function streamChat(
  messages: Message[],
  onDelta: (text: string) => void,
  signal: AbortSignal,
): Promise<"done" | "interrupted"> {
  const res = await fetch("/api/chat/stream", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ messages }),
    signal,
  });
  if (!res.ok || !res.body) throw new Error(`HTTP ${res.status}`);

  const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
  let buffer = "";

  while (true) {
    const { value, done } = await reader.read();
    if (done) return "interrupted";
    buffer += value;

    let index: number;
    while ((index = buffer.indexOf("\n\n")) >= 0) {
      const raw = buffer.slice(0, index);
      buffer = buffer.slice(index + 2);
      const event = /^event: (.*)$/m.exec(raw)?.[1];
      const data = /^data: (.*)$/m.exec(raw)?.[1];
      if (event === "delta" && data) onDelta(JSON.parse(data).text);
      if (event === "done") return "done";
      if (event === "error" && data) throw new Error(JSON.parse(data).message);
    }
  }
}

TextDecoderStream correctly handles multi-byte characters split across chunks; this matters for text containing non-ASCII characters or emoji. Because the function returns interrupted when the stream ends without a done event, the UI can mark the answer as "incomplete".

Updating React state on every chunk can cause unnecessary re-renders with very fast streams. Accumulating chunks in a ref and flushing them into state once per frame with requestAnimationFrame is a simple and effective way to keep the screen smooth.

Cancellation: from the user to the model

When the user presses "Stop" or leaves the page, it is not enough for the UI to stop updating. If the model call keeps running in the background, it wastes money and keeps server resources busy. Cancellation has to propagate through the entire chain.

On the client, you create an AbortController and pass its signal to fetch; when the component unmounts or the user stops, abort() is called. The browser closes the connection. On the ASP.NET Core side, this means the request's CancellationToken (HttpContext.RequestAborted) fires. In the example above, the same token is passed both to StreamAsync and to the write calls, so the model request is cancelled as well.

It is also important not to log cancellation as an error. An OperationCanceledException here is a deliberate user action; counting it toward the error rate makes monitoring dashboards meaningless. Tracking it as a separate counter is also a useful signal for seeing how often users cut answers short.

Reporting errors inside the stream

Once the stream has started, the HTTP status code can no longer be changed; when the first byte is sent, the 200 has already gone out. If the model provider returns an error mid-stream or you hit a content filter, you can only inform the client through an event within the stream.

So it is good practice to wrap the streaming loop in a try/catch, write an event: error event on unexpected failures and then close the stream. The event's payload should not contain the internal error message, but a short description that can be shown to the user and, if you like, a correlation ID. Errors that occur before the stream begins (validation, authorization, quota) should be returned as normal HTTP error responses; this makes it easier to handle the two cases separately on the client.

Persisting the finished response

In applications that keep chat history, the answer needs to be stored in the database. Rather than writing each chunk individually during the stream, it is simpler to accumulate the chunks on the server and save them once when the stream ends. Two cases need to be distinguished: if the stream completed normally, the answer can be stored as "completed"; if it ended through cancellation or an error, the part generated so far can be stored as "incomplete".

On cancellation, the request token will already have fired, so you must not use the same token for the save operation; otherwise the save is cancelled too. Using a separate, short timeout token for the save solves this. Recording usage information such as token counts at this point also makes cost tracking independent of streaming behavior.

When testing the stream, it helps to think of the same distinctions as scenarios: normal completion, user cancellation, an error mid-stream and the connection dropping without a done event. Once the model interface is abstracted, you can easily produce these scenarios with a fake IChatModel, without needing a real model.

Streaming is one of the most visible parts of LLM-based interfaces, but whether it works well depends largely on invisible details: settings that disable buffering, cancellation that propagates end to end, errors reported within the stream and responses saved consistently. When you design these pieces from the start, users see a fast interface, and you keep cost, errors and incomplete answers under control.