SkillPilotAI

Real-time: SignalR and SSE

Real-time means the server pushes updates the moment they happen instead of the client asking again and again. In ASP.NET Core you use SignalR for two-way messaging with groups, and Server-Sent Events (new result in .NET 10) for one-way feeds.

63.1 Why is it used?

  • In the demo a food app polls order 42 every 2 s; the first four answers are just "Placed".
  • With 1 lakh customers that is 50,000 requests per second, most of them wasted.
  • A change shows up only on the next poll, so updates can be up to 2 s late.
  • Fix: server push, where the server tells the client that the status changed.
JavaScript
// Polling: ask for status every 2slet n = 0;setInterval(async () => {  const res = await fetch(    "http://localhost:5063/orders/42");  const order = await res.json();  console.log(`request ${++n}: ${order.status}`);}, 2000);
Output
$ node poll.mjsrequest 1: Placedrequest 2: Placedrequest 3: Placedrequest 4: Placedrequest 5: Preparingrequest 6: Out for delivery

63.2 SignalR hub and groups

  • SignalR is built into ASP.NET Core; at its centre is a hub.
  • A hub inherits Hub; clients can call its public methods directly (TrackOrder).
  • Context.ConnectionId is the unique id of each connected client.
  • Groups.AddToGroupAsync adds the connection to group "order-42"; a message to a group reaches only its members (like a WhatsApp group).
  • AddSignalR registers the services, MapHub<OrderHub>("/hubs/orders") exposes the hub.
C#
using Microsoft.AspNetCore.SignalR; public class OrderHub : Hub{    public async Task TrackOrder(int orderId)    {        await Groups.AddToGroupAsync(            Context.ConnectionId,            $"order-{orderId}");    }}
C#
var builder = WebApplication.CreateBuilder(args);builder.Services.AddSignalR();builder.Services.AddSingleton<OrderStore>(); var app = builder.Build();app.MapHub<OrderHub>("/hubs/orders");
Output
$ dotnet run --urls http://localhost:5063info: Microsoft.Hosting.Lifetime[14]      Now listening on: http://localhost:5063info: Microsoft.Hosting.Lifetime[0]      Application started. Press Ctrl+C to shut down.

63.3 IHubContext: push from outside the hub

  • Status changes happen in a normal endpoint, not in the hub.
  • Inject IHubContext<OrderHub> to send messages from controllers, endpoints or background jobs.
  • Clients.Group($"order-{id}").SendAsync("StatusChanged", id, status) sends only to that order's group.
C#
app.MapPost("/orders/{id}/status",    async (int id, string status,        OrderStore store,        IHubContext<OrderHub> hub) =>    {        store.Set(id, status);        await hub.Clients            .Group($"order-{id}")            .SendAsync("StatusChanged",                id, status);        return Results.NoContent();    });
Output
$ curl -i -X POST \  "localhost:5063/orders/42/status?status=Preparing"HTTP/1.1 204 No ContentServer: Kestrel

63.4 JavaScript client

  • Official npm package @microsoft/signalr; same code in Node 22 and the browser.
  • HubConnectionBuilder().withUrl(...) takes the hub URL; withAutomaticReconnect reconnects if the connection drops.
  • connection.on("StatusChanged", ...) listens for the event.
  • await connection.start() opens the connection, then invoke("TrackOrder", 42) calls the hub method.
JavaScript
import * as signalR from "@microsoft/signalr"; const connection =  new signalR.HubConnectionBuilder()    .withUrl("http://localhost:5063/hubs/orders")    .withAutomaticReconnect()    .build(); connection.on("StatusChanged", (id, status) =>  console.log(`Order ${id}: ${status}`)); await connection.start();await connection.invoke("TrackOrder", 42);console.log("Tracking order 42");
Output
$ node client.mjs[2026-11-06T21:18:10.315Z] Information:WebSocket connected to ws://localhost:5063/...Tracking order 42Order 42: PreparingOrder 42: Out for delivery
How SignalR flows
  1. 1.Client POSTs /hubs/orders/negotiate: server lists available transports

  2. 2.WebSocket connection opens and stays open

  3. 3.Client invokes TrackOrder(42): connection joins group order-42

  4. 4.POST /orders/42/status changes the status

  5. 5.IHubContext sends StatusChanged to group order-42 only

  6. 6.Client on("StatusChanged") prints "Order 42: Preparing" with no polling

63.5 Groups keep data private

  • Checkpoint: A tracks order 42, B tracks order 7. When order 42 changes, B sees nothing.
  • The message goes only to group order-42.
  • With Clients.All every customer would see someone else's order status: a privacy bug.
Output
# Client A (order 42)Tracking order 42Order 42: Preparing# Client B (order 7)Tracking order 7

63.6 Server-Sent Events in .NET 10

  • For one-way data (live cricket score) full SignalR is not needed.
  • SSE is plain HTTP: one response that stays open and sends events.
  • .NET 10 adds TypedResults.ServerSentEvents, which streams an IAsyncEnumerable.
  • Content-Type is text/event-stream; each ball arrives as one event; a browser reads it with EventSource.
C#
app.MapGet("/scores/live",    (CancellationToken ct) =>        TypedResults.ServerSentEvents(            LiveScore(ct), eventType: "score")); static async IAsyncEnumerable<Score> LiveScore(    [EnumeratorCancellation] CancellationToken ct){    for (var ball = 1; ball <= 3; ball++)    {        await Task.Delay(1000, ct);        yield return new Score(            $"0.{ball}", ball * 4);    }}
Output
$ curl -i -N localhost:5063/scores/liveHTTP/1.1 200 OKContent-Type: text/event-streamCache-Control: no-cache,no-storeevent: scoredata: {"over":"0.1","runs":4}event: scoredata: {"over":"0.2","runs":8}event: scoredata: {"over":"0.3","runs":12}

63.7 SignalR is not just WebSocket

  • SignalR is a library with its own protocol that picks the transport itself.
  • The negotiate response lists WebSockets, ServerSentEvents and LongPolling.
  • If WebSockets are blocked SignalR falls back automatically.
  • A plain WebSocket client cannot talk to a SignalR hub directly.
HTTP
POST /hubs/orders/negotiate?negotiateVersion=1Host: localhost:5063
Output
HTTP/1.1 200 OKContent-Type: application/json{  "negotiateVersion": 1,  "connectionId": "llMaSDTUjCbhN1kqyeM1EA",  "availableTransports": [    { "transport": "WebSockets" },    { "transport": "ServerSentEvents" },    { "transport": "LongPolling" }  ]}

63.8 Comparison: Polling vs SSE vs SignalR

PointPollingSSESignalR
DirectionClient asks again and againServer -> client onlyTwo-way
TransportRepeated HTTP requestsOne long HTTP response (text/event-stream)WebSockets, fallback SSE / long polling
LatencyUp to the poll interval (2 s here)ImmediateImmediate
Server loadHigh: most answers are the sameLowLow, but connections stay open
Groups / usersNoNo (build it yourself)Built in
Browser clientfetchEventSource@microsoft/signalr

63.9 When to use which

Which real-time tool?
  1. 1.Do you need server -> client updates only (score, notifications, AI stream)?

  2. 2.Yes: Server-Sent Events (TypedResults.ServerSentEvents in .NET 10)

  3. 3.Need two-way messages, groups, users or mobile clients?

  4. 4.Yes: SignalR (WebSockets with SSE / long polling fallback)

  5. 5.Need your own custom protocol on the socket?

  6. 6.Yes: raw WebSockets

63.10 Common mistakes

  • Not awaiting start() before invoke: "Cannot send data if the connection is not in the 'Connected' State."
  • Using Clients.All when only one user or group should get the message.
  • Not rejoining groups after a reconnect: the new connection has a new id and lost its group membership.
  • Storing state in hub fields: a new hub object is created for every call.
  • Scaling to several servers without a Redis backplane or Azure SignalR Service: messages reach only clients on the same server.
JavaScript
// Wrong: start not awaitedconnection.start();await connection.invoke("TrackOrder", 42);// Error: Cannot send data if the// connection is not in the// 'Connected' State. // Right: connect first, then invokeawait connection.start();await connection.invoke("TrackOrder", 42);// Tracking order 42

63.11 Interview tips

  • "I create a SignalR hub, register it with AddSignalR and MapHub, and push to groups with IHubContext from anywhere."
  • SignalR prefers WebSockets and falls back to SSE or long polling.
  • For a one-way feed I use the .NET 10 ServerSentEvents result.
  • On multiple servers add a Redis backplane or Azure SignalR Service.
  • Polling is simple but wastes requests and adds delay.