📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

πŸ“š Interview question

Your product needs live updates in the browser: order status changes, a notification badge and a live dashboard. Compare polling, long polling, Server-Sent Events, WebSockets and SignalR. How does each work, what does each cost, and when would you choose each in ASP.NET Core?

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.

Junior Theory Beginner aspnet-core polling real-time server-sent-events signalr websockets

🎯 Key points

  • Short polling: client asks every N seconds; simple, cacheable, wasteful and adds up to N seconds of latency
  • Long polling: server holds the request open until data or timeout; near real-time over plain HTTP, one held request per client
  • SSE: one long-lived HTTP response with text/event-stream; server-to-client only, auto-reconnect with Last-Event-ID
  • WebSockets: HTTP Upgrade (101) to a full-duplex TCP channel; bidirectional, binary or text, no built-in reconnect
  • SignalR: abstraction over WebSockets, SSE and long polling with negotiation, reconnect, groups and hub RPC
  • Every open connection costs a socket, memory and a slot at proxies and load balancers; scale-out needs a backplane or Azure SignalR Service
  • Choose the simplest that meets latency and direction: polling for minutes-old data, SSE for one-way feeds, SignalR or WebSockets for two-way

⏱ 30-second answer

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.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"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/status every 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-stream that never ends. The server writes data: lines and the browser's EventSource parses them, reconnects on its own and sends Last-Event-ID so you can resume. In .NET 10 it is first-class: TypedResults.ServerSentEvents takes an IAsyncEnumerable. When the client also has to send a lot, or latency really matters, as in chat, collaborative editing or games, I use WebSockets: an HTTP Upgrade that 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."


How each one works

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

When to use / when not

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

What each costs on the server

  • Polling costs CPU and requests, not connections. 10,000 clients polling every 5 s is 2,000 requests per second.
  • Long polling, SSE and WebSockets each hold a connection per client: a socket, buffers and some memory per connection in Kestrel. They also take a slot at every reverse proxy and load balancer in the path, and idle timeouts there (for example 4 minutes on Azure Load Balancer, 230 s on App Service's front end for a request) will cut them unless you send heartbeats.
  • SignalR adds a negotiate request and per-connection state. Across several instances you need sticky sessions, plus a Redis backplane or Azure SignalR Service.

Production example

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.

πŸ” What the interviewer is checking

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

  • Explains SSE as a streaming text/event-stream response with auto-reconnect and Last-Event-ID
  • Knows WebSockets start with an HTTP Upgrade and that SignalR negotiates and falls back
  • Talks about connection counts, proxy idle timeouts and heartbeats
  • Starts from the business freshness requirement

Red flags

  • "Always use SignalR" or "WebSockets are always faster"
  • Thinks SSE is bidirectional or that polling has no cost
  • No awareness that long-lived connections affect scaling and load balancers

πŸ“š Learn in depth

1. The problem: HTTP is request/response

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

2. Server-Sent Events on the wire

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
  • Each event ends with a blank line. id lets the browser send Last-Event-ID on reconnect, event names the event type, and retry sets the reconnect delay in milliseconds.
  • Over HTTP/1.1, browsers limit each origin to about 6 connections, so several SSE tabs can starve your other requests. HTTP/2 multiplexes streams over one connection, which removes the problem.
  • The browser 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.

3. WebSockets on the wire

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.

4. How SignalR picks a transport

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.

5. Capacity: connections, not requests

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.

Try it yourself

  1. Build a /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.
  2. Open an SSE endpoint in Chrome DevTools (Network β†’ EventStream tab) and watch events arrive. Kill the server and see EventSource reconnect and send Last-Event-ID.
  3. Run dotnet-counters monitor --counters Microsoft.AspNetCore.Server.Kestrel while you open 500 WebSocket connections, and watch current-connections.
  4. Put nginx in front of your SSE endpoint with default buffering, notice that events arrive in bursts, then fix it with proxy_buffering off.
  5. Start a SignalR client with skipNegotiation: false, block WebSockets in the browser, and watch it fall back to SSE.

πŸ’» Code

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)));

⚠ Common mistakes

  • Mistake: Choosing SignalR or WebSockets for data that only changes every minute. Why it is wrong: You pay for long-lived connections, sticky sessions and a backplane to save a few cheap requests. Instead: Poll with ETags or caching, and move to SSE only when latency matters.
  • Mistake: Polling every second "to be safe". Why it is wrong: 10,000 clients make 10,000 requests per second, almost all returning nothing. Instead: Match the interval to the business need, or switch to SSE or long polling.
  • Mistake: Using raw WebSockets in a business app and hand-rolling reconnect, routing and broadcast. Why it is wrong: You rebuild SignalR badly, without a fallback for proxies that block upgrades. Instead: Use SignalR unless you need a custom binary protocol.
  • Mistake: Forgetting idle timeouts on proxies and load balancers. Why it is wrong: Connections are silently cut after a few minutes and clients see random disconnects. Instead: Send heartbeats (SSE comment lines, SignalR KeepAliveInterval) shorter than the shortest timeout in the path.
  • Mistake: Leaving response buffering or compression on for SSE. Why it is wrong: nginx, IIS or the response compression middleware hold events back and release them in bursts. Instead: Disable proxy buffering for the route and exclude text/event-stream from compression.
  • Mistake: Treating SSE as bidirectional. Why it is wrong: SSE is server to client only. Instead: Send client actions as normal POSTs, or use SignalR or WebSockets.
  • Mistake: Putting bearer tokens in SSE or WebSocket query strings without thinking about logs. Why it is wrong: Query strings end up in proxy and server logs, which is a Privacy Act and security problem. Instead: Use short-lived tokens, cookies, or strip the parameter from logs.

πŸ› Senior insight: trade-offs

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.

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions SignalR as the default choice for two-way updates. Why: Checks whether they know what SignalR adds over raw WebSockets.
    How to answer

    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.

  2. When: Candidate mentions long-lived connections behind a load balancer. Why: Checks understanding of sticky sessions, idle timeouts and connection draining.
    How to answer

    A load balancer spreads traffic across healthy instances.

    • Layer 4 (TCP/UDP: Azure Load Balancer, AWS NLB, Kubernetes Services via kube-proxy) picks a backend per connection using IPs and ports. Fast, protocol-agnostic, no HTTP awareness.
    • Layer 7 (HTTP: App Gateway, ALB, Front Door, ingress controllers, Envoy, YARP) picks per request, can route by path/host/header, terminate TLS, retry and add headers.

    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.

  3. When: Candidate mentions streaming SSE events from an IAsyncEnumerable. Why: Checks they can produce and cancel async streams correctly.
    How to answer

    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).

↩ Usually asked after

More in Real-Time and Special APIs

Last updated 23 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me