Introduction
SignalR pushes live updates to browsers — ShopNest live chat, stock price dashboard, and order status notifications without polling every second.
After this article you will
- Create Hub with server and client methods
- Use groups for chat rooms and channels
- Handle connect/disconnect lifecycle
- Authenticate SignalR connections
- Scale out with Redis backplane
Prerequisites
- Article 42 — Minimal APIs
- ShopNest with EF Core and auth from Modules 2–4
Concept deep-dive
public class ChatHub : Hub
{
public async Task JoinRoom(string roomId) =>
await Groups.AddToGroupAsync(Context.ConnectionId, roomId);
public async Task SendMessage(string roomId, string user, string message)
{
await Clients.Group(roomId).SendAsync("ReceiveMessage", new
{
user,
message,
at = DateTime.UtcNow
});
}
public override async Task OnConnectedAsync()
{
await Clients.Caller.SendAsync("Connected", Context.ConnectionId);
await base.OnConnectedAsync();
}
}
// Program.cs
builder.Services.AddSignalR();
app.MapHub<ChatHub>("/hubs/chat");
// JavaScript client
const connection = new signalR.HubConnectionBuilder()
.withUrl("/hubs/chat", { accessTokenFactory: () => token })
.withAutomaticReconnect()
.build();
connection.on("ReceiveMessage", (msg) => appendToChat(msg));
await connection.start();
await connection.invoke("JoinRoom", "shopnest-support");
await connection.invoke("SendMessage", "shopnest-support", user, text);
Redis backplane: builder.Services.AddSignalR().AddStackExchangeRedis(...) — sync messages across multiple server instances.
Hands-on — ShopNest Live Chat / Stock Dashboard
- ChatHub + simple Razor page with @microsoft/signalr script.
- Support room + product Q&A room via groups.
- [Authorize] on hub; pass JWT via accessTokenFactory.
- StockTickerHub broadcasts price updates every 5s (demo timer).
Common errors & best practices
- Calling Clients.All in huge app — use groups to limit broadcast scope.
- No reconnect logic on client — users miss messages after network blip.
- Scaling without backplane — users on server B miss server A messages.
Interview questions
Q: SignalR vs polling?
A: SignalR maintains persistent connection — lower latency and server load than polling.
Q: WebSockets vs SignalR?
A: SignalR negotiates best transport (WebSockets, SSE, long polling).
Q: Redis backplane purpose?
A: Message bus between app instances in load-balanced deployment.
Summary
- Hubs connect server push to browser/mobile clients
- Groups scope messages to chat rooms or dashboards
- JWT auth works with accessTokenFactory
- Redis backplane required for multi-instance ShopNest
Previous: Minimal APIs
Next: Clean Architecture
FAQ
SignalR with Blazor?
Blazor Server uses SignalR under the hood — different use case from custom hubs.
.NET client?
HubConnectionBuilder works in MAUI/mobile for ShopNest apps.