Implementing Server-Sent Events in .NET 10 with TypedResults.ServerSentEvents and SseItem<T>: the text/event-stream format, event ids and Last-Event-ID resume, heartbeats, cancellation on disconnect, proxy buffering, and when SSE beats WebSockets or SignalR.
Server-Sent Events is one long-lived HTTP response with Content-Type: text/event-stream. The server writes id:, event: and data: lines, and the browser's EventSource parses them and reconnects automatically, sending the last id in a Last-Event-ID header. In .NET 10 it is built in: return TypedResults.ServerSentEvents(stream), where stream is an IAsyncEnumerable<SseItem<T>>. The framework sets the headers, serialises T to JSON and flushes each item. You pass the request's CancellationToken so the loop ends when the client goes away, read Last-Event-ID to replay missed events, and send heartbeats so proxies don't cut idle streams.
SSE beats WebSockets when data flows one way: it is plain HTTP, so auth, HTTP/2, proxies and logging all just work. It is the wrong tool when the client must send a lot back.
"SSE is the simplest real-time option that still feels instant. It is just an HTTP GET whose response never ends:
Content-Type: text/event-stream, and each event is a few lines,id:,event:,data:, ended by a blank line. The browser'sEventSourcehandles parsing and reconnection, and when it reconnects it sendsLast-Event-ID, so the server can resume where the client left off.Before .NET 10 you wrote the headers and the
data:lines yourself and flushed after each one. Now there isTypedResults.ServerSentEvents, which takes anIAsyncEnumerable<SseItem<T>>.SseItem<T>comes fromSystem.Net.ServerSentEventsand carries the data, an event type and an event id. I write an async iterator that yields items, mark its token parameter with[EnumeratorCancellation], and bind the endpoint'sCancellationToken, which isHttpContext.RequestAborted. When the browser tab closes, the token fires and the loop ends instead of leaking. For fan-out I keep a broadcaster that gives each subscriber its own boundedChannel<T>, so one slow client can't block the producer. On reconnect I read theLast-Event-IDheader and replay from a small ring buffer or the database.Two production details matter. First, heartbeats: proxies and load balancers close idle connections, so every 15–20 seconds I send a comment or a
pingevent. Second, buffering: nginx, IIS and the response compression middleware will hold events back unless you turn buffering off for that route. The mistake I see is people using SignalR for a one-way progress bar. SSE is less infrastructure, works over HTTP/2 and passes through ordinary auth and logging."
| SSE | WebSockets | SignalR | |
|---|---|---|---|
| Direction | Server → client | Both | Both |
| Protocol | Plain HTTP response | HTTP Upgrade, then frames | Negotiated transport plus hub protocol |
| Reconnect and resume | Built in (retry, Last-Event-ID) |
You build it | Reconnect built in, no resume |
| Data | UTF-8 text (JSON) | Text or binary | JSON or MessagePack |
| Auth | Cookies or query string (EventSource can't set headers) |
Query string or cookies | access_token query string |
| HTTP/2 | Multiplexed, no 6-connection limit | Needs RFC 8441 support | Depends on transport |
| Good for | Notifications, progress, dashboards, AI token streams | Custom protocols, games | Chat, collaboration, groups |
| Concern | What to do |
|---|---|
| Disconnects | Bind CancellationToken, use [EnumeratorCancellation] |
| Resume | Set EventId; read Last-Event-ID; replay from a buffer or store |
| Idle timeouts | Heartbeat every 15–20 s, below the shortest proxy timeout |
| Buffering | X-Accel-Buffering: no for nginx; exclude text/event-stream from compression |
| Slow clients | Per-subscriber bounded Channel with DropOldest or disconnect |
| HTTP/1.1 limit | About 6 connections per origin per browser; serve over HTTP/2 |
| Scale-out | Each instance needs the events: feed the broadcaster from Redis pub/sub or Service Bus |
For a [report generation] feature, we replaced a 1-second progress poll with an SSE endpoint. Requests to the status endpoint dropped by about [95%], progress showed within [100 ms] of each step, and the only infrastructure change was proxy_buffering off on the ingress route.
Checks that the candidate can build a correct, production-ready SSE endpoint in .NET 10 and knows when SSE is the right tool.
Green flags
TypedResults.ServerSentEvents with SseItem<T> (or knows how to write the format by hand)[EnumeratorCancellation] and RequestAbortedLast-Event-ID replayRed flags
GET /jobs/7/progress HTTP/1.1
Accept: text/event-stream
Last-Event-ID: 41 <- only on reconnect
HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache
retry: 3000
id: 42
event: progress
data: {"percent":60}
id: 43
event: progress
data: {"percent":80}
: keep-alive comment (ignored by EventSource)
Rules: lines are UTF-8, fields are id, event, data and retry, multiple data: lines are joined with newlines, and a blank line dispatches the event. A line starting with : is a comment, which makes a perfect heartbeat.
endpoint returns ServerSentEventsResult<T>
│
├─ sets Content-Type: text/event-stream, Cache-Control: no-cache
├─ disables response buffering (IHttpResponseBodyFeature.DisableBuffering)
├─ await foreach item in your IAsyncEnumerable<SseItem<T>>
│ └─ SseFormatter writes id/event/data (T serialised with System.Text.Json; strings written as-is)
│ └─ flush after each item
└─ ends when the enumerable completes or RequestAborted fires
SseItem<T> and SseFormatter live in System.Net.ServerSentEvents. .NET 9 added SseParser for consuming SSE from HttpClient, and .NET 10 added the formatter and the ASP.NET Core result.
producer (BackgroundService, Service Bus consumer)
│ Publish(evt)
▼
Broadcaster (singleton)
├─ ring buffer of last N events (for Last-Event-ID replay)
├─ subscriber 1: Channel<T> bounded(100, DropOldest) ──▶ SSE response 1
├─ subscriber 2: Channel<T> bounded(100, DropOldest) ──▶ SSE response 2
└─ ...
The producer never awaits a slow client: TryWrite into each bounded channel either succeeds or drops the oldest item. Each SSE response reads its own channel. With several instances, every instance runs its own broadcaster fed from a shared source such as Redis pub/sub.
When the browser closes the tab, Kestrel notices the connection reset and cancels HttpContext.RequestAborted. If your iterator takes [EnumeratorCancellation] CancellationToken ct and you pass it to Task.Delay and ReadAllAsync, the await throws OperationCanceledException, the iterator's finally runs (unsubscribe here), and the framework treats it as a normal end. Without the token, the loop keeps running until the next write fails, which can be minutes if events are rare.
SSE breaks silently when something in the path buffers the response: nginx proxy_buffering on (the default), IIS dynamic compression, the ASP.NET Core response compression middleware, or some API gateways. Symptoms: nothing arrives for a while, then a burst. Fix it per route, and test through the real ingress, not just Kestrel.
curl -N http://localhost:5000/jobs/7/progress to see raw events stream in.Last-Event-ID.proxy_buffering off.finally to confirm cancellation reaches it.dotnet-counters for memory and current-connections.A .NET 10 SSE endpoint with a broadcaster, resume with Last-Event-ID, heartbeats, per-user authorisation and clean cancellation.
// Program.cs (.NET 10, nullable enabled)
using System.Collections.Concurrent;
using System.Net.ServerSentEvents;
using System.Runtime.CompilerServices;
using System.Security.Claims;
using System.Threading.Channels;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication().AddCookie(); // EventSource sends cookies; it can't send headers
builder.Services.AddAuthorization();
builder.Services.AddSingleton<ProgressBroadcaster>();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/jobs/{jobId:int}/progress", (
int jobId,
ClaimsPrincipal user,
ProgressBroadcaster broadcaster,
HttpRequest request,
CancellationToken ct) => // bound to HttpContext.RequestAborted
{
// Authorise the subscription, not just the endpoint (real code checks job ownership in the database).
if (!broadcaster.CanWatch(user, jobId)) return Results.Forbid();
long? lastId = long.TryParse(request.Headers["Last-Event-ID"], out var id) ? id : null;
return TypedResults.ServerSentEvents(broadcaster.Subscribe(jobId, lastId, ct));
}).RequireAuthorization();
app.Run();
public sealed record Progress(int JobId, int Percent);
public sealed class ProgressBroadcaster
{
private static readonly TimeSpan HeartbeatInterval = TimeSpan.FromSeconds(15);
private readonly ConcurrentDictionary<Guid, (int JobId, Channel<SseItem<Progress>> Channel)> _subscribers = new();
private readonly ConcurrentQueue<(long Id, SseItem<Progress> Item)> _recent = new(); // small replay buffer
private long _nextId;
public bool CanWatch(ClaimsPrincipal user, int jobId) => user.Identity?.IsAuthenticated == true;
public void Publish(Progress p)
{
var id = Interlocked.Increment(ref _nextId);
var item = new SseItem<Progress>(p, eventType: "progress") { EventId = id.ToString() };
_recent.Enqueue((id, item));
while (_recent.Count > 500) _recent.TryDequeue(out _);
foreach (var (_, sub) in _subscribers)
if (sub.JobId == p.JobId)
sub.Channel.Writer.TryWrite(item); // never blocks the producer; DropOldest handles slow clients
}
public async IAsyncEnumerable<SseItem<Progress>> Subscribe(
int jobId, long? lastEventId, [EnumeratorCancellation] CancellationToken ct)
{
var channel = Channel.CreateBounded<SseItem<Progress>>(
new BoundedChannelOptions(100) { FullMode = BoundedChannelFullMode.DropOldest, SingleReader = true });
var key = Guid.NewGuid();
_subscribers[key] = (jobId, channel);
try
{
// Replay anything the client missed while it was disconnected.
if (lastEventId is { } last)
foreach (var (id, missed) in _recent)
if (id > last && missed.Data.JobId == jobId)
yield return missed;
while (true)
{
// One wait at a time (SingleReader): wait for data, or time out to send a heartbeat.
using var waitCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
waitCts.CancelAfter(HeartbeatInterval);
bool hasData;
try
{
hasData = await channel.Reader.WaitToReadAsync(waitCts.Token);
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
hasData = false; // heartbeat timeout, not a client disconnect
}
if (!hasData)
{
// Keeps proxies with idle timeouts from closing the stream.
yield return new SseItem<Progress>(new Progress(jobId, -1), eventType: "ping");
continue;
}
while (channel.Reader.TryRead(out var item))
yield return item;
}
}
finally
{
_subscribers.TryRemove(key, out _); // runs when the client disconnects (ct cancelled)
}
}
}
// Browser: EventSource reconnects and sends Last-Event-ID automatically; cookies go with it.
const es = new EventSource("/jobs/7/progress", { withCredentials: true });
es.addEventListener("progress", e => updateBar(JSON.parse(e.data).percent));
# Ingress or nginx: never buffer event streams
location /jobs/ {
proxy_pass http://api;
proxy_http_version 1.1;
proxy_buffering off;
proxy_read_timeout 3600s;
}
CancellationToken into the iterator. Why it is wrong: The loop keeps running after the client leaves, holding memory and subscriptions until a write eventually fails. Instead: Bind the endpoint's token and mark the iterator parameter [EnumeratorCancellation].EventId, read Last-Event-ID and replay from a buffer or store.text/event-stream from response compression. Each platform differs: nginx needs proxy_buffering off or X-Accel-Buffering: no; IIS needs dynamic compression off for the route; Azure Front Door, API Management and Application Gateway each have their own buffering and timeout settings. Test through the real path in every environment.ping event every 15–20 s.TryWrite.EventSource can't set headers, and query strings end up in proxy and server logs, which is a credential leak and a Privacy Act concern. Instead: Prefer a Secure, HttpOnly, SameSite auth cookie on the same site. Otherwise call an authenticated POST that returns a single-use stream ticket valid for about 30–60 seconds, redeem it when the stream opens, and scrub it from logs. Because the token is only checked when the stream opens, cap stream lifetime (for example close after the access token expires) so the client reconnects and re-authenticates.SSE is underrated because it looks too simple. For the very common "tell the user when something finished" feature, it gives you real-time behaviour with nothing new to operate: same auth, same logging, same load balancer, HTTP/2 multiplexing and a browser API that reconnects on its own. The parts you must own are resume (event ids and a replay source), fan-out across instances, and proxy configuration.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| SSE with in-memory broadcaster | One instance or per-instance producers | Lowest | Several instances that must all see every event, without a shared feed |
| SSE fed by Redis pub/sub or Service Bus | Multiple instances | A shared feed and replay store | Very high fan-out to public viewers (use a CDN-friendly or managed service) |
| SignalR | Two-way, groups, users | Connections plus backplane | One-way notifications only |
| Polling | Freshness of 30 s or more is fine | Requests | Sub-second needs |
Measure it with current-connections and memory per connection under a k6 load test, the reconnect rate in your logs, and end-to-end latency from publish to browser.
IAsyncEnumerable<T> is a sequence whose items arrive asynchronously. You produce one with an async iterator method that uses both await and yield return, and consume it with await foreach, which awaits MoveNextAsync() for each item and disposes the enumerator asynchronously. Cancellation is passed with .WithCancellation(ct) and received in the iterator through a parameter marked [EnumeratorCancellation]. It lets you process large or slow data item by item instead of buffering everything, for example EF Core AsAsyncEnumerable() or streaming JSON responses from ASP.NET Core. .NET 10 includes LINQ operators for it in the base library (System.Linq.AsyncEnumerable).
System.Threading.Channels provides fast, async-friendly queues for passing data between producers and consumers. Channel.CreateBounded<T>(capacity) gives backpressure: when full, WriteAsync waits (or drops items, depending on BoundedChannelFullMode). Channel.CreateUnbounded<T>() never blocks writers but can grow without limit. Writers call Complete() when done; readers loop with await foreach (var x in reader.ReadAllAsync(ct)) and finish when the channel is completed and empty. Options such as SingleReader and SingleWriter enable faster internal implementations. Channels are the standard building block for in-process background queues and pipelines.
There are five ways to get server changes to a client. Short polling asks on a timer: simple and cache-friendly, but wasteful, and data is up to one interval stale. It suits reports and KPIs. Long polling holds each request open until something happens, giving near real-time over plain HTTP when nothing else gets through a proxy. Server-Sent Events (SSE) keep one HTTP response open and stream text/event-stream messages one way, server to client, with automatic reconnect. They suit notifications, progress and AI token streams. WebSockets upgrade the connection to a full-duplex channel for low-latency two-way traffic such as chat or collaborative editing. SignalR sits on top: it negotiates WebSockets, falls back to SSE or long polling, and adds reconnects, groups and hub methods.
The trade-off: polling costs requests, while push costs one held connection per client. Those connections need capacity planning, proxy idle-timeout settings and a scale-out story.
How to tell it (STAR)
**S:** Our [document export] showed progress through Server-Sent Events. It was fine locally, but in production the bar sat at 0% and then jumped to 100%, and some streams dropped at exactly 60 seconds. **T:** I owned the fix, because users were starting duplicate exports and [load was doubling]. **A:** I compared `curl -N` straight to the pod with the same call through the ingress and saw the buffering only through nginx. I turned off proxy buffering and raised the read timeout for that route, excluded event streams from compression, moved to .NET 10's ServerSentEvents result, and added heartbeats and Last-Event-ID resume. **R:** The first progress event now arrives in under [a second], duplicate exports dropped by [about 80%], and we added a pipeline test so the next streaming endpoint doesn't hit the same problem.
Last updated 23 Nov 2026.