Introduction

Real time in Angular and .NET looks simple until the team needs to choose the right technology to move from “works on my machine” to production without fragility. Usually, the discussion starts with a vague product request: “we need the screen to update by itself”. From there, four very different paths appear: WebSockets, Server-Sent Events (SSE), SignalR and Long Polling. They are not equivalent, they do not solve the same scenario at the same cost and they should not be treated as synonyms.

I wrote this tutorial to answer the question that really matters: when to use each approach without over-engineering. In some cases, a one-way stream is already enough. In others, the application needs a bidirectional channel, automatic fallback and an abstraction that hides the protocol’s complexity. And, in certain corporate environments, the ugliest solution in theory becomes the most reliable in practice because it crosses proxies, load balancers and network policies with less friction.

The central point here is pragmatic. WebSockets offer persistent bidirectional communication. SSE delivers updates from the server to the browser over HTTP with a simple API. SignalR is a high-level abstraction for ASP.NET Core that chooses the best available transport and also offers hubs, groups and reconnection. Long Polling still exists because compatibility and predictability still beat elegance in environments where WebSockets and SSE are blocked.

💡 Tip: when the requirement is only to push events from the server to the client, start with SSE or SignalR before moving to WebSockets. In many products, the smallest sufficient solution is the one that survives best over time.

In this article, I also use the blog’s samples repository as practical support. The .NET and Angular sample was prepared to show the same processing flow over four different transports, without hiding what changes in the frontend, the backend and operations.

Prerequisites

To follow the tutorial, you will need:

  • .NET 10 SDK to run the sample’s backend
  • Node.js or Bun to run the demo Angular frontend
  • Basic knowledge of ASP.NET Core, Angular and HTTP
  • Familiarity with the concepts of endpoint, hub and asynchronous request

Clone the samples repository:

1
2
git clone https://github.com/lzocateli/blog-zocateli-sample.git
cd blog-zocateli-sample

If you want to reproduce the scenario locally, the backend is in src/BlogSamples and the demo frontend in frontend/search-ui-bun/. The sample was designed to display a processing task with incremental progress, precisely to highlight the difference between transport, latency and client complexity.

⚠️ Warning: SSE depends on a streaming response. In Nginx, Cloudflare and other proxies, buffering can delay or break the experience if the backend does not write and flush the events correctly.

When each technology makes sense

Before getting into the implementation, I like to reduce the discussion to a simple criterion: which direction does the data flow need to follow? If the application only needs to publish states, notifications or progress, there is no reason to pay the cognitive cost of a full bidirectional connection. If the client also needs to send frequent commands in real time, then the conversation changes.

Long Polling is the most conservative starting point. It works with any traditional HTTP infrastructure, crosses more restrictive proxies and is easy to understand: the client makes a request, and the server holds it until there is new data or until the timeout. In return, you pay with latency and the overhead of repeated connections. It is a useful compromise when compatibility beats elegance.

SSE is a very interesting middle ground for dashboards, audit trails, job status and notification feeds. It uses an open HTTP connection and the browser receives events continuously via EventSource. The client does not send messages over the same channel, so the solution is naturally one-way. This reduces the problem’s surface, simplifies the implementation and is still more compatible than many teams imagine.

WebSockets come in when the conversation needs to be truly bidirectional. Chat, collaboration, games, interactive telemetry, simultaneous editing and real-time commands are scenarios where the full-duplex model makes sense. The price is well known: a persistent connection, extra attention to scalability, affinity on load balancers and greater sensitivity to network intermediaries.

SignalR solves another category of problem: I want a real-time contract in ASP.NET Core without having to choose the transport manually in each case. The framework negotiates WebSockets, SSE and Long Polling as the platform allows. In .NET projects, this reduces friction and still offers high-level features such as hubs, groups and reconnection.

In short: Long Polling is the safety net, SSE is the simple and efficient stream, WebSockets is the persistent bidirectional channel, and SignalR is the abstraction that delegates the decision to the runtime.

WebSockets in practice with .NET and Angular

WebSockets start as HTTP and then upgrade to a persistent channel. This detail changes everything: the connection stops being a request-response cycle and becomes a pipe open in both directions. That means less overhead per message, low latency and a very useful mental model for applications that need to react to user interactions and server events without reopening a connection for every action.

In practice, the gain comes with extra responsibilities. WebSockets require attention to horizontal scalability, because the connection stays alive and may depend on session affinity or a backplane for message distribution. It is also common to find a corporate proxy, gateway or CDN that does not handle WebSockets as well as ordinary HTTP traffic. That does not make the technology bad; it just requires a more serious analysis of the environment.

The strongest scenario for WebSockets in Angular and .NET is when the client also sends frequent commands: starting a task, canceling an operation, adjusting execution parameters or keeping an interactive session. Instead of opening new requests for every step, the client and the server share a continuous channel.

📝 Example: in a job supervision panel, the user can trigger a task, receive incremental progress and cancel the operation without leaving the same communication channel.

SSE in practice with .NET and Angular

SSE, or Server-Sent Events, is the opposite of technological glamour, and that is exactly why it is so often useful. The browser opens an HTTP connection with EventSource and keeps listening to named events sent by the server. There is no bidirectionality on the same channel; the server writes, the client reads. It looks limited, but for status updates, notifications, processing progress and event feeds it is often enough.

SSE’s strong point is operational simplicity. Because it stays very close to HTTP, it is usually easier to get through existing infrastructure than a WebSocket connection. The browser API is lean and reconnection can be handled with native behavior or a thin layer of code. For Angular applications, this fits well with a reactive interface that only needs to reflect the latest state.

The main care lies in delivering the stream. If the backend writes the event but the proxy holds the buffer, the user sees nothing until the flush or until buffering is disabled. That is exactly why SSE needs to be documented together with the edge architecture, and not just as a controller detail.

SignalR as an abstraction layer

SignalR is where many discussions get confusing, so it is worth separating the roles clearly. SignalR is not “a protocol competing” with WebSockets. It is a high-level abstraction for ASP.NET Core applications that chooses the available transport and delivers a simpler experience for the developer. If WebSockets is available, great. If not, SignalR can fall back to SSE or Long Polling without breaking the application’s contract.

For .NET teams, this is usually valuable because it reduces repetitive decisions. Instead of each screen deciding on its own how to talk to the backend, I centralize the conversation in hubs, methods and events. The frontend calls a method, the hub responds with an event, and the framework negotiates the transport in between. This also helps when you want groups, selective broadcast, automatic reconnection and a clearer domain model.

The trade-off is that this layer can hide details the team should understand. SignalR helps, but it does not remove the need to know when WebSockets, SSE or Long Polling are behind the abstraction. If the application needs extreme predictability in a specific environment, it is better to measure the real behavior than to assume the framework will solve everything on its own.

Long Polling as fallback and maximum compatibility

Long Polling is often treated as an old technique, but that is a misreading. It remains important because there is a huge number of environments in which the best protocol is simply the one that passes the firewall, the proxy and the security policy without discussion. Instead of opening a persistent channel, the client makes a request and the server holds the response until there is an update or a timeout.

The practical effect is predictability. You may pay with higher latency and more request overhead, but you gain almost universal compatibility. For users behind very restrictive proxies, corporate environments with conservative rules and legacy stacks, Long Polling is still a valid solution. It is better to have a slower fallback than no updates at all.

The real problem is trying to use Long Polling as the first choice when the application clearly calls for a more efficient channel. If the product depends on many events per second or on instant interaction, the cost of repeated requests quickly shows up in CPU, network and observability. In that situation, Long Polling should stay in reserve, not behind the wheel.

Decision matrix for choosing the approach

When I need to decide quickly, I use a simple matrix:

Decision matrix between WebSockets, SSE, SignalR and Long Polling

ScenarioBest starting pointReason
Server → client onlySSELower complexity, simple HTTP stream
Client also sends frequent commandsWebSocketsReal bidirectional channel
I want an ASP.NET Core abstraction and automatic fallbackSignalRTransport negotiation and hubs
Restrictive or legacy infrastructureLong PollingGreater compatibility
Dashboard UI with job progressSSE or SignalRLow complexity and good UX
Real-time chat or collaborationWebSockets or SignalRBidirectionality and low latency

This matrix does not replace measurements, but it avoids the most common trap: using the most powerful technology just because it is more exciting. In production, the smallest mechanism that meets the requirement is often the one that is least work to operate.

Practical Example

The blog’s sample was built to show the same task flow over four transports. In the backend, I expose a creation endpoint, a query endpoint and a stream for SSE and WebSocket. In the Angular frontend, I switch the connection according to the chosen transport and update the same interface with the same event model.

.NET Backend

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
var grupo = app.MapGroup("/api/tempo-real")
    .WithTags("Tempo real")
    .RequireCors("TempoReal");

grupo.MapPost("/tarefas", (TempoRealProcessamentoService processamentoService, TempoRealCriacaoRequest request) =>
{
    if (string.IsNullOrWhiteSpace(request.Descricao))
    {
        return Results.BadRequest(new { erro = "A descrição da tarefa é obrigatória." });
    }

    var resposta = processamentoService.CriarTarefa(request.Descricao.Trim());
    return Results.Created($"/api/tempo-real/tarefas/{resposta.TarefaId}", resposta);
});

grupo.MapGet("/tarefas/{tarefaId:guid}/stream", async (
    Guid tarefaId,
    HttpContext context,
    TempoRealProcessamentoService processamentoService,
    CancellationToken cancellationToken) =>
{
    context.Response.ContentType = "text/event-stream";
    await foreach (var proximoEstado in processamentoService.ObterFluxoAsync(tarefaId, cancellationToken))
    {
        await context.Response.WriteAsync($"data: {JsonSerializer.Serialize(proximoEstado)}\n\n", cancellationToken);
        await context.Response.Body.FlushAsync(cancellationToken);
    }
});

📂 Source Code: The complete backend example is available in the blog’s samples repository at BlogSamples/Messaging/TempoReal/.

Angular with SignalR

1
2
3
4
5
6
7
8
9
const connection = new signalR.HubConnectionBuilder()
  .withUrl('/hubs/tempo-real', { withCredentials: true })
  .withAutomaticReconnect()
  .build();

connection.on('estado', (estado: TempoRealEstadoResponse) => onEstado(estado));

await connection.start();
await connection.invoke('AcompanharTarefa', tarefaId);

📂 Source Code: The demo frontend is in the blog’s samples repository at frontend/search-ui-bun/, where I adapted the interface to switch between the four transports.

The important detail here is not the number of lines, but the mental model. The same backend produces the same task state; what changes is how that state crosses the network and how the interface decides to listen to the updates.

Tips and Good Practices

  • Start from the data direction requirement. If the flow is only server → client, I prefer SSE or SignalR before thinking about WebSockets. This reduces complexity, makes operations easier and avoids opening a more expensive channel than necessary.

  • Disable buffering when using SSE. Streaming without flushing the response becomes “almost streaming”. In production, I always validate the complete chain of proxy, CDN and server to ensure events reach the browser at the expected time.

  • Treat SignalR as a contract, not as magic. It solves a lot, but it still depends on transport, reconnection and network policy. Understanding what happens underneath avoids surprises when the environment switches from WebSocket to Long Polling.

  • Use Long Polling as a conscious fallback. It is useful when the infrastructure is restrictive, but it is not the ideal choice for high volume. As the application grows, the cost difference in requests and latency shows up quickly.

  • Model the event state in a stable way. The client should not have to guess the meaning of each payload. A single event model simplifies logs, debugging, reconnection and rendering in the UI.

  • Watch the edge environment from the start. Proxies, load balancers, security policies and timeouts are part of the real-time architecture, not operational details. Ignoring them produces a system that works in dev and fails outside it.

Objective Summary

  • WebSockets — offer persistent bidirectional communication over a single connection, which reduces per-message overhead and favors interactive scenarios such as chat and collaboration.
  • SSE — delivers events from the server to the browser via text/event-stream, with a native browser API and operational simplicity for dashboards and notifications.
  • SignalR — is a high-level ASP.NET Core abstraction that negotiates WebSockets, SSE or Long Polling and exposes hubs, groups and reconnection.
  • Long Polling — keeps maximum compatibility with traditional HTTP infrastructure, but pays with more latency and more requests to the server.
  • Angular + .NET — work very well for real-time applications when the event model is stable and the transport is chosen by requirement, not by fashion.
  • Edge infrastructure — can be the deciding factor between an elegant solution and an operationally reliable one; buffering and proxies directly affect SSE and WebSockets.

Read Also

References