Compares short polling, long polling, Server-Sent Events, WebSockets and SignalR for pushing updates to clients from ASP.NET Core: mechanism, cost, proxies and when each fits.
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.
"I start from two questions: how fresh does the data need to be, and which direction does it flow? Short polling is the client calling
GET /orders/42/statusevery few seconds. It is trivial to build, works through every proxy and can be cached, but most calls return nothing new and the data is up to one interval old. Long polling improves latency: the server holds the request until there is news or a timeout, say 30 seconds, then the client immediately asks again. It works everywhere, but you hold a request open per client.For one-way feeds I like Server-Sent Events. It is a single HTTP response with
Content-Type: text/event-streamthat never ends. The server writesdata:lines and the browser'sEventSourceparses them, reconnects on its own and sendsLast-Event-IDso you can resume. In .NET 10 it is first-class:TypedResults.ServerSentEventstakes anIAsyncEnumerable. When the client also has to send a lot, or latency really matters, as in chat, collaborative editing or games, I use WebSockets: an HTTPUpgradethat returns 101 and becomes a full-duplex channel. But raw WebSockets give you no reconnect, no message routing and no fallback, so in ASP.NET Core I would normally use SignalR. It negotiates the best transport, gives you hub methods, groups and users, and reconnects automatically.The mistake I see is teams reaching for SignalR for a dashboard that refreshes every 30 seconds, then discovering sticky sessions and backplanes in production. My rule is to pick the least real-time option that meets the requirement, because every long-lived connection is capacity you have to plan for."
| Technique | Direction | Transport | Latency | Reconnect | Browser API |
|---|---|---|---|---|---|
| Short polling | Client pulls | Normal HTTP requests | Up to one interval | Not needed | fetch + timer |
| Long polling | Server pushes (simulated) | HTTP request held open | Low | Client re-issues | fetch loop |
| SSE | Server β client | One streaming HTTP response | Low | Built in (retry, Last-Event-ID) |
EventSource |
| WebSockets | Both ways | Upgraded TCP connection (ws://, wss://) |
Lowest | You build it | WebSocket |
| SignalR | Both ways | WebSockets β SSE β long polling | Low | Built in (withAutomaticReconnect) |
@microsoft/signalr |
| Need | Choose | Avoid |
|---|---|---|
| Data can be 30β60 s old (reports, KPIs) | Short polling with ETags or caching | SignalR: it adds infrastructure for no benefit |
| Notifications, progress bars, live feeds, LLM token streams | SSE | WebSockets, unless the client must also send a lot |
| Chat, collaborative editing, multiplayer | SignalR (or raw WebSockets for a custom protocol) | Polling: too slow and wasteful |
| Non-browser clients, server to server | gRPC streaming or a message broker | Browser-oriented protocols |
| Hostile corporate proxies | Long polling or SSE over HTTPS | Raw WebSockets with no fallback |
For an order-tracking page at [company], the first version polled every 2 seconds, about [3,000] requests per second at peak, and 98% of them returned "no change". We moved the tracking page to SSE, with a 15-second comment heartbeat to keep Azure Front Door from closing idle streams. Request volume dropped by [over 90%], and status changes reached the browser in under [500 ms] instead of up to 2 s.
Checks that the candidate understands how each technique works on the wire and can choose by freshness, direction and operational cost rather than habit.
Green flags
text/event-stream response with auto-reconnect and Last-Event-IDRed flags
HTTP/1.1 was designed for the client to ask and the server to answer. Every real-time technique is a way around that.
Short polling C ββGETβββΆ S C βββ200 (nothing)ββ S ... wait N s ... repeat
Long polling C ββGETβββΆ S (server waits until data or timeout) C βββ200 dataββ S repeat at once
SSE C ββGET Accept: text/event-streamβββΆ S
C βββ data: {...}\n\n ββ data: {...}\n\n ββ (stream never ends)
WebSocket C ββGET Upgrade: websocketβββΆ S C βββ101 Switching Protocolsββ S
C βββββ frames both ways βββββΆ S
SSE is plain text over a normal HTTP response:
HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache
id: 101
event: orderStatus
data: {"orderId":42,"status":"Packed"}
: heartbeat comment line keeps proxies from timing out
retry: 5000
id lets the browser send Last-Event-ID on reconnect, event names the event type, and retry sets the reconnect delay in milliseconds.EventSource API cannot set custom headers, so bearer tokens usually travel in a cookie or a query string, and query strings end up in logs.The client sends GET with Upgrade: websocket and Sec-WebSocket-Key. The server replies 101 Switching Protocols with Sec-WebSocket-Accept, and from then on both sides send framed messages (text, binary, ping, pong, close) over the same TCP connection. In ASP.NET Core this is app.UseWebSockets() plus context.WebSockets.AcceptWebSocketAsync(). Over HTTP/2 the upgrade uses extended CONNECT (RFC 8441), which Kestrel supports.
What raw WebSockets do not give you: reconnection, message routing, acknowledgements, broadcast to groups, scale-out, or a fallback when a proxy strips the Upgrade header. SignalR exists to fill those gaps.
client ββPOST /hub/negotiateβββΆ server: "available: WebSockets, ServerSentEvents, LongPolling"
client tries WebSockets βok?ββΆ use it
βfailββΆ try SSE βfailββΆ long polling
After that, hub invocations are serialised with JSON or MessagePack and carried over whichever transport won. Note that over SSE and long polling, client-to-server messages go as separate HTTP POSTs.
The moment you hold connections open, the limiting resources change. CPU and requests per second matter less; open sockets, memory per connection, proxy limits and idle timeouts matter more. Watch Kestrel's current-connections and the ASP.NET Core current-requests counter, and plan heartbeats shorter than the shortest idle timeout in the path.
/poll endpoint and an SSE endpoint that emit the same data. Load-test both with 1,000 virtual users in k6 and compare requests per second and p95 latency.EventSource reconnect and send Last-Event-ID.dotnet-counters monitor --counters Microsoft.AspNetCore.Server.Kestrel while you open 500 WebSocket connections, and watch current-connections.proxy_buffering off.skipNegotiation: false, block WebSockets in the browser, and watch it fall back to SSE.Three ways to push the same order status from a .NET 10 Minimal API: short polling, Server-Sent Events and a SignalR hub.
// Program.cs (.NET 10, nullable enabled)
using System.Net.ServerSentEvents;
using System.Runtime.CompilerServices;
using Microsoft.AspNetCore.SignalR;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<OrderFeed>();
builder.Services.AddSignalR();
var app = builder.Build();
// 1. Short polling: cheap to build; an ETag means unchanged polls return a 304 with no body.
app.MapGet("/orders/{id:int}/status", (int id, OrderFeed feed, HttpContext http) =>
{
var status = feed.Current(id);
var etag = $"\"{status.Version}\"";
if (http.Request.Headers.IfNoneMatch == etag) return Results.StatusCode(304);
http.Response.Headers.ETag = etag;
return Results.Ok(status);
});
// 2. SSE: one long-lived response; the framework sets text/event-stream and flushes each item.
app.MapGet("/orders/{id:int}/events", (int id, OrderFeed feed, CancellationToken ct) =>
TypedResults.ServerSentEvents(feed.Watch(id, ct)));
// 3. SignalR: two-way, with transport fallback and reconnect handled by the client library.
app.MapHub<OrderHub>("/hubs/orders");
app.Run();
public sealed record OrderStatus(int OrderId, string Status, long Version);
public sealed class OrderHub : Hub
{
// Clients join a group per order so we only push to people watching it.
public Task Watch(int orderId) => Groups.AddToGroupAsync(Context.ConnectionId, $"order-{orderId}");
}
public sealed class OrderFeed
{
public OrderStatus Current(int id) => new(id, "Packed", 3);
public async IAsyncEnumerable<SseItem<OrderStatus>> Watch(int id, [EnumeratorCancellation] CancellationToken ct)
{
// ct fires when the browser disconnects, so the loop ends instead of leaking.
while (!ct.IsCancellationRequested)
{
var s = Current(id);
yield return new SseItem<OrderStatus>(s, eventType: "orderStatus") { EventId = s.Version.ToString() };
await Task.Delay(TimeSpan.FromSeconds(5), ct);
}
}
}
// Browser side for SSE: reconnect and Last-Event-ID come for free.
const source = new EventSource("/orders/42/events");
source.addEventListener("orderStatus", e => render(JSON.parse(e.data)));
KeepAliveInterval) shorter than the shortest timeout in the path.text/event-stream from compression.The senior move is to treat "real-time" as a capacity and operations decision, not a library choice. Polling scales with request rate, which your stack already handles well. Push techniques scale with concurrent connections, which change your bottlenecks to sockets, memory, proxy limits and the cost of keeping instances in sync. I ask product owners what freshness they really need: "within 30 seconds" and "within 200 ms" lead to very different architectures.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Short polling | Minutes-old data, CDN-cacheable reads | Requests, mostly empty | Sub-second freshness, large fleets of clients |
| Long polling | Must work through anything, low message rate | One held request per client | High message rates (re-request overhead) |
| SSE | One-way feeds, notifications, AI token streams | One HTTP stream per client | Heavy client-to-server traffic |
| WebSockets | Custom protocol, binary, lowest latency | Connection per client, you own reconnect | Ordinary business notifications |
| SignalR | Two-way app features, groups, many browsers | Connection plus backplane or Azure SignalR | Server-to-server or non-JavaScript clients that gRPC suits better |
Behaviour under load (rough orders of magnitude, measure your own):
| Technique | 10,000 clients means | Typical limit you hit first |
|---|---|---|
| Polling every 5 s | ~2,000 requests per second | CPU, database load from repeated reads |
| Long polling (30 s timeout) | 10,000 held requests plus ~330 re-requests per second | Proxy connection limits, re-request churn at high message rates |
| SSE / WebSockets / SignalR | 10,000 open sockets, tens of KB of buffers each | Memory per connection, load balancer and proxy connection caps, idle timeouts, App Service plan connection limits |
| Azure SignalR Service | Connections billed per unit (about 1,000 concurrent per Standard unit) | Units and message quota |
Measure it: requests per second and "no change" ratio for polling; current-connections, memory per connection and reconnect rate for push. A reconnect storm after every deployment is a classic sign the design ignored graceful shutdown.
SignalR is ASP.NET Core's real-time framework. A hub is a class whose public methods clients call, and the server calls methods on clients through Clients.All, Clients.Group(...) or Clients.User(...). Hubs are transient, created per invocation, so they hold no state. On connect the client calls negotiate and uses the best transport available: WebSockets, then Server-Sent Events, then long polling. Groups fan messages out to subsets of connections, but they live in memory, so a reconnecting client must re-join them (usually in OnConnectedAsync). Strongly typed hubs (Hub<IOrderClient>) replace method-name strings with an interface. Authentication uses the normal pipeline with [Authorize]. Browsers can't send an Authorization header on WebSockets or EventSource, so as a workaround the token travels as an access_token query parameter, read in JwtBearerEvents.OnMessageReceived.
The trade-off: reconnects and routing come free, but every client holds a stateful connection that you must plan to scale.
A load balancer spreads traffic across healthy instances.
Health checks remove unhealthy instances (in Kubernetes: readiness for traffic, liveness for restarts). Algorithms: round robin, least connections/requests, hashing. Sticky sessions pin a user to one instance, which hurts scaling and failover. Connection draining stops new traffic to an instance before shutdown so in-flight requests finish.
gRPC uses long-lived HTTP/2 connections, so an L4 balancer balances connections, not calls: one client connection carries all its calls to one pod. Use L7 balancing (mesh/Envoy) or client-side load balancing.
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).
Last updated 23 Nov 2026.