How to Implement Real-Time Notifications in ASP.NET Core 10 Using Server-Sent Events (2026)

An order dashboard can lose its network connection between two status updates. When it reconnects, it needs to know what it missed. ASP.NET Core can send server-sent events with an event ID, read the browser’s Last-Event-ID on reconnection, and replay retained events. This tutorial streams application notifications, with a reset event when the replay buffer no longer covers the gap.

What makes a notification stream resumable?

Each event includes an identifier the receiver can use as its next resume cursor. Browser EventSource reconnects after ordinary network interruptions and can send the last received ID. A server with retained events can replay the rows after it. Heartbeats keep quiet connections active and help diagnose buffering. They should not advance the cursor.

The client reconnects with its last ID. The server replays retained notifications or tells the client to refresh its snapshot.
The client reconnects with its last ID. The server replays retained notifications or tells the client to refresh its snapshot.
Transport Direction Good fit
SSE Server to browser Notifications, event progress, status changes
WebSocket or SignalR Bidirectional Interactive sessions and negotiated transports
Periodic polling Client requests snapshots Simpler setup when update latency is flexible

The lab uses one process with 100 retained events. New connections begin at the current position. An older or foreign cursor gets a reset event. For business events that must survive a restart, keep a durable stream with stable IDs and a separate snapshot endpoint.

Build an ASP.NET Core notification server

Use .NET 10 and create an empty web app. No additional NuGet packages are required. Save the server in Program.cs and the browser files in wwwroot. Run the unauthenticated lab on loopback.

BASH
dotnet new web -n NotificationFeed -f net10.0
cd NotificationFeed
dotnet run --no-launch-profile --urls http://localhost:5073
Program.cs
using System.Globalization;
using System.Text.Json;
using Microsoft.AspNetCore.Http.Features;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<Feed>();
var app = builder.Build();
app.UseDefaultFiles();
app.UseStaticFiles();
app.MapGet("/notifications", async (HttpContext context, Feed feed, CancellationToken ct) =>
{
    var last = context.Request.Headers["Last-Event-ID"];
    long? after = null;
    if (last.Count > 0)
    {
        if (last.Count != 1 || !long.TryParse(last[0], NumberStyles.None,
            CultureInfo.InvariantCulture, out var parsed))
        { context.Response.StatusCode = 400; return; }
        after = parsed;
    }
    var res = context.Response;
    res.ContentType = "text/event-stream";
    res.Headers.CacheControl = "no-store";
    context.Features.Get<IHttpResponseBodyFeature>()?.DisableBuffering();
    await res.WriteAsync("retry: 3000\n\n", ct);
    await res.Body.FlushAsync(ct);
    while (!ct.IsCancellationRequested)
    {
        var state = feed.Read(after);
        after ??= state.Latest;
        if (state.Gap)
        {
            await res.WriteAsync($"id: {state.Latest}\nevent: reset\ndata: {{}}\n\n", ct);
            await res.Body.FlushAsync(ct);
            after = state.Latest;
            continue;
        }
        foreach (var row in state.Items)
        {
            var json = JsonSerializer.Serialize(row, JsonSerializerOptions.Web);
            await res.WriteAsync($"id: {row.Id}\nevent: notification\ndata: {json}\n\n", ct);
            after = row.Id;
        }
        if (state.Items.Length > 0)
        {
            await res.Body.FlushAsync(ct);
            continue;
        }
        try { await state.Changed.WaitAsync(TimeSpan.FromSeconds(15), ct); }
        catch (TimeoutException)
        {
            await res.WriteAsync(": heartbeat\n\n", ct);
            await res.Body.FlushAsync(ct);
        }
    }
});
app.MapPost("/notifications", (Input body, Feed feed) =>
{
    if (body.Message is not { Length: > 0 and <= 160 }) return Results.BadRequest();
    return Results.Accepted(value: feed.Add(body.Message));
});
app.Run();

record Input(string? Message);
record Notice(long Id, string Message);
sealed class Feed
{
    private readonly object _gate = new();
    private readonly Queue<Notice> _items = new();
    private TaskCompletionSource _changed = new(TaskCreationOptions.RunContinuationsAsynchronously);
    private long _id = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();

    public Notice Add(string message)
    {
        lock (_gate)
        {
            var row = new Notice(++_id, message);
            _items.Enqueue(row);
            if (_items.Count > 100) _items.Dequeue();
            var signal = _changed;
            _changed = new(TaskCreationOptions.RunContinuationsAsynchronously);
            signal.TrySetResult();
            return row;
        }
    }
    public (long Latest, bool Gap, Notice[] Items, Task Changed) Read(long? after)
    {
        lock (_gate)
        {
            var gap = after is long id && (id > _id ||
                id < (_items.Count == 0 ? _id : _items.Peek().Id - 1));
            return (_id, gap, gap || after is null ? [] :
                _items.Where(x => x.Id > after.Value).ToArray(), _changed.Task);
        }
    }
}

The stream sends SSE fields in UTF-8 and terminates each event with a blank line. JSON serialization escapes line breaks inside a notification. The feed captures the replay snapshot and the pending change signal under one lock so a publish cannot slip between reading and waiting. This sample writes frames explicitly to demonstrate heartbeat comments and retry hints. ASP.NET Core 10 also offers TypedResults.ServerSentEvents for streams that fit its event API.

Connect with EventSource and test a reconnect

Place these files in wwwroot and open http://localhost:5073/. EventSource sends GET requests and reconnects automatically when appropriate. Insert text using textContent so a notification cannot inject markup.

wwwroot/index.html
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Notification lab</title>
<h1>Notifications</h1>
<ul id="notifications" aria-live="polite"></ul>
<script src="/client.js" defer></script>
</html>
wwwroot/client.js
const feed = new EventSource("/notifications");
feed.addEventListener("notification", event => {
    const item = JSON.parse(event.data);
    const row = document.createElement("li");
    row.textContent = item.message;
    document.querySelector("#notifications").append(row);
});
feed.addEventListener("reset", () => {
    document.querySelector("#notifications").replaceChildren();
    // Reload the authoritative notification list in a deployed application.
});
window.addEventListener("pagehide", () => feed.close(), { once: true });
BASH
curl -iN http://localhost:5073/notifications
# In another terminal
curl -i http://localhost:5073/notifications \
  -H 'Content-Type: application/json' -d '{"message":"Shipment ready"}'
# Reconnect with an earlier ID printed by the stream.
curl -iN http://localhost:5073/notifications -H 'Last-Event-ID: REPLACE_ME'

Expect one notification per publish and heartbeat comments after quiet periods. Disconnect the first request, publish another message and reconnect with the first ID. The second message should replay. Send a very old ID to exercise reset. A production reset handler must refresh authoritative state and reconcile events that arrive while that refresh runs.

Deploy behind proxies and enforce identity

Disable buffering on the SSE route through every intermediary that would otherwise accumulate response chunks. Set proxy and load balancer idle timeouts above the heartbeat interval, and verify with the actual production path. Long-lived connections need a memory and connection budget. Disconnect clients that cannot keep up, then let them replay from a safe cursor. Prefer HTTP/2 where supported to reduce pressure from per-origin connection limits.

Use a same-origin authenticated cookie or a client that can attach a bearer token to its streaming request. Native EventSource cannot set an arbitrary Authorization header. Avoid putting long-lived bearer tokens in URLs. Protect the publish endpoint with an appropriate authorization policy and CSRF protection when using cookies. Enforce user or tenant scope for both the live and replay queries, and plan reauthentication for long-lived streams.

What if two replicas receive the same reconnect?

Both need access to the same durable event sequence and retention policy. Use a shared stream, a persistent ID, and a bounded per-connection buffer. Sticky sessions cannot recover an in-memory history after process loss.

Does seeing one event mean it was processed exactly once?

No. A reconnect can replay a previously applied event. Reconcile or deduplicate by event ID when the client performs a meaningful effect.

Define reset and snapshot semantics together

A reset event means the stream alone can no longer reconcile the screen. Have the snapshot API return both the current visible state and a matching cursor. While fetching it, either buffer live updates and apply only events newer than that cursor, or restart a stream from the cursor after replacing the view. Without a shared boundary, an event can arrive during snapshot loading and be applied twice or disappear.

Choose retention by recovery window and throughput. A fixed event count covers a shorter time during a burst. If a user disconnects overnight, a full refresh may be cheaper than replaying every event. Monitor connected clients, reconnect rate, replay size, reset frequency and event-to-delivery lag. Correlate replay with authorization scope so a reconnect cannot leak another user’s notifications.

Takeaway. Define the cursor, retained history and snapshot as one protocol. Heartbeats and EventSource keep the transport useful, while replay keeps the UI accurate.

References

Comments