Server-Sent Events in ASP.NET Core: Real-time Without WebSockets

When updates only flow from server to browser, Server-Sent Events are simpler than WebSockets. Stream them from ASP.NET Core with reconnects included.

R M Shahidul Islam Shahed · 3 min read

Not every real-time feature needs a two-way connection. Build progress, live order status, a stock ticker, a notification badge: data flows one way, from server to browser. For those, Server-Sent Events (SSE) are simpler than WebSockets. They run over plain HTTP, reconnect on their own and need no client library. This post streams them from ASP.NET Core.

SSE in one minute

The browser opens a normal HTTP request and the server keeps it open, writing events as text:

text
event: progress
id: 41
data: {"percent":65}

Each event is a few field: value lines followed by a blank line. In the browser, EventSource reads them:

javascript
const source = new EventSource("/api/jobs/42/events");
source.addEventListener("progress", e => {
  const { percent } = JSON.parse(e.data);
  bar.value = percent;
});

If the connection drops, EventSource reconnects by itself and sends the last id it saw in a Last-Event-ID header, so the server can continue where it left off.

SSE or SignalR?

Server-Sent Events SignalR
Direction Server to browser Both ways
Transport Plain HTTP WebSockets, with fallbacks
Client library None (EventSource is built in) @microsoft/signalr
Reconnect Built in, with Last-Event-ID Built in
Binary data No, text only Yes

Choose SSE when the browser only listens. Choose SignalR when clients also send messages, or when you need groups and scale-out handled for you.

Stream events from an endpoint

The source of events is usually a channel or a service. Here, a job reports progress into a Channel<T>:

csharp
public sealed record JobProgress(int Percent, string Step);

public sealed class JobTracker
{
    private readonly ConcurrentDictionary<int, Channel<JobProgress>> _jobs = new();

    public ChannelReader<JobProgress> Watch(int jobId) =>
        _jobs.GetOrAdd(jobId, _ => Channel.CreateUnbounded<JobProgress>()).Reader;

    public ValueTask ReportAsync(int jobId, JobProgress progress) =>
        _jobs.GetOrAdd(jobId, _ => Channel.CreateUnbounded<JobProgress>()).Writer.WriteAsync(progress);
}

The endpoint sets the content type and writes each event, flushing so it reaches the browser at once:

csharp
app.MapGet("/api/jobs/{id:int}/events", async (int id, JobTracker tracker, HttpContext http, CancellationToken ct) =>
{
    http.Response.Headers.ContentType = "text/event-stream";
    http.Response.Headers.CacheControl = "no-cache";

    var eventId = 0;
    await foreach (var progress in tracker.Watch(id).ReadAllAsync(ct))
    {
        var json = JsonSerializer.Serialize(progress, JsonSerializerOptions.Web);
        await http.Response.WriteAsync($"event: progress\nid: {++eventId}\ndata: {json}\n\n", ct);
        await http.Response.Body.FlushAsync(ct);

        if (progress.Percent >= 100) break;
    }
}).RequireAuthorization();

The CancellationToken fires when the browser disconnects, which ends the loop and frees the request.

.NET 10 also adds a built-in result for this, TypedResults.ServerSentEvents, which takes an IAsyncEnumerable and writes the format for you. The hand-written version above shows what goes over the wire, and works on any version.

Keep the connection alive

Proxies and load balancers close connections that stay silent too long, often after 60 seconds. Send a comment line every 15–30 seconds; EventSource ignores lines starting with :.

csharp
await http.Response.WriteAsync(": keep-alive\n\n", ct);
await http.Response.Body.FlushAsync(ct);

Merge it into your loop with a timer, or write events from a PeriodicTimer when nothing else happened.

Resume after a reconnect

When EventSource reconnects, it sends Last-Event-ID. If your events come from a store (a database table of order status changes, say), read from there:

csharp
var lastId = long.TryParse(http.Request.Headers["Last-Event-ID"], out var v) ? v : 0;
var missed = await db.OrderEvents
    .Where(e => e.OrderId == id && e.Id > lastId)
    .OrderBy(e => e.Id)
    .ToListAsync(ct);

Send the missed events first, then continue with live ones. For purely transient data like progress percentages, sending the current state on connect is enough.

Things that get in the way

  • Response compression and buffering. A compressing proxy may hold events until it has enough to compress. Exclude text/event-stream from compression, or turn buffering off at the proxy (for nginx, X-Accel-Buffering: no).
  • Output caching. Never cache an event stream; mark the endpoint so the cache skips it.
  • HTTP/1.1 connection limits. Browsers allow about six connections per domain over HTTP/1.1, and each open EventSource uses one. Over HTTP/2 that limit effectively disappears. Serve SSE over HTTPS with HTTP/2 enabled.
  • Authentication. EventSource sends cookies but can't set headers. Use cookie authentication, or a short-lived token in the query string (and keep it out of your logs).

Wrapping up

When data only flows from server to browser, SSE gives you real-time updates with a plain HTTP endpoint, a few lines of text per event, and reconnects built into the browser. Flush after each event, send keep-alives, honour Last-Event-ID, and keep the stream away from compression and caching.

Keep reading

All articles →
Real-time Apps

SignalR in ASP.NET Core: Typed Hubs, Groups and Authentication

Build real-time features with strongly typed hubs, per-tenant groups, JWT authentication and server-side broadcasts, plus the scale-out step.

3 min read
Real-time Apps

Build a Live Sales Dashboard with SignalR and .NET 10

Push real-time metrics to the browser with strongly-typed hubs, groups and a Redis backplane.

1 min read
Architecture & Production .NET

Background Jobs in ASP.NET Core with BackgroundService and PeriodicTimer

Run scheduled work inside your ASP.NET Core app: BackgroundService, PeriodicTimer, scoped DbContext, safe reruns, and when to reach for Hangfire.

4 min read