SignalR is Microsoft's open-source ASP.NET library for real-time web: the server pushes messages to connected clients the moment something happens. Hubs, the Clients.All/Caller/Others/Group targets, transport fallback (WebSockets → Server-Sent Events → Long Polling) and scale-out are the exam points.
Medium 40 minSyllabus: “SignalR”
Mark as
The idea in one minute
Polling is a child in the back seat asking 'Are we there yet?' every five minutes. A real-time connection is the driver promising to announce it the moment you arrive. SignalR sets up that promise between browsers and an ASP.NET server — over a WebSocket when the road allows, or an older, slower route when it does not — so dashboards, chats and notifications update instantly without anyone asking.
Key points — the night-before list
SignalR (David Fowler and Damian Edwards, 2011; ASP.NET SignalR 1.0 in 2013; ASP.NET Core SignalR in 2018) adds real-time server-to-client push and two-way RPC to ASP.NET applications.
Uses: chat, live dashboards and scores, notifications, collaborative editing, multiplayer games, auctions, progress of long-running jobs.
A hub is a class deriving from Hub; clients call its public methods, and it calls client-side handlers with Clients.All, Clients.Caller, Clients.Others or Clients.Group(name) plus SendAsync("method", args).
Transports with automatic fallback, best first: WebSockets → Server-Sent Events → Long Polling (classic ASP.NET SignalR also had Forever Frame). A negotiate request chooses one.
JavaScript client: new signalR.HubConnectionBuilder().withUrl("/chathub").build(), connection.on("ReceiveMessage", fn), await connection.start(), connection.invoke("SendMessage", …).
Groups via Groups.AddToGroupAsync(Context.ConnectionId, "Kollam"); lifecycle hooks OnConnectedAsync / OnDisconnectedAsync. Hubs are transient — keep no state in their fields.
Scale-out over several servers needs a backplane (Redis) or Azure SignalR Service. ASP.NET SignalR and ASP.NET Core SignalR clients and servers are not interchangeable.
01The real-time web and what SignalR does
Ordinary HTTP — and AJAX on top of it — is client-initiated: the server can answer, but it cannot speak first. Many applications need the opposite: a new chat message, a changed cricket score, a unit booked in an allotment draw, a finished report. Real-time web functionality means the server pushes such updates to connected clients the instant they happen.
SignalR is an open-source library from Microsoft for adding real-time functionality to ASP.NET applications. It was started in 2011 by David Fowler and Damian Edwards; ASP.NET SignalR 1.0 shipped in 2013 for the .NET Framework, and the redesigned ASP.NET Core SignalR arrived with ASP.NET Core 2.1 in 2018. It hides the messy details: choosing a transport, keeping the connection alive, reconnecting, routing messages to individual users or groups, and scaling across servers.
Chat and messaging — help desks, team chat, comment threads.
Notifications and alerts — 'your application has been approved', system warnings.
Collaborative apps — shared editing, whiteboards, live polls.
Games, auctions and progress bars — anything where seconds matter or where a long job reports its progress.
The programming model is remote procedure calls in both directions: browser code calls methods on the server's hub, and the hub calls JavaScript functions registered in the browser. Switch the Client–server tiers tool on this page to SignalR push mode to watch one server message fan out to every connected client.
02Server-push techniques: polling, long polling, SSE and WebSockets
Technique
How it works
Direction
Latency and overhead
Polling
The client asks every N seconds whether anything changed
Client pulls
Delay up to N s (N/2 on average); mostly empty requests, full headers each time
Long polling
The server holds each request open until it has data or a timeout, then the client re-requests at once
Push emulated over HTTP
Low delay; one HTTP request per message and reconnect costs
Server-Sent Events (SSE)
One long HTTP response streaming text/event-stream; browser EventSource API with automatic reconnect
Server → client only
Low delay and overhead; text only; the client sends with separate requests
WebSockets
An HTTP request with Upgrade: websocket is answered with 101 Switching Protocols; the TCP connection then carries full-duplex frames (ws://, wss://; RFC 6455, 2011)
Both directions
Lowest: frame headers of only 2–14 bytes, no HTTP headers per message
Forever Frame (classic SignalR only)
A hidden iframe receives an endless stream of script blocks
Server → client
Worked only in Internet Explorer
Polling with C clients and interval T seconds:
request rate = C / T requests per second
average extra delay ≈ T / 2 (worst case ≈ T)
share of empty polls = 1 − (update rate × T) when updates are rarer than polls
Example: C = 10,000 dashboards, T = 5 s, one update per minute
10,000 / 5 = 2,000 requests/s; average delay 2.5 s;
each client polls 12 times a minute but only 1 poll has news → 11/12 ≈ 92 % wasted
PSC favourite
The technology giving a two-way persistent connection in which the server can send content without first being asked is WebSocket (asked in 2026). SignalR's benefit over polling: real-time two-way communication with automatic transport negotiation (asked in 2025) — it does not use only WebSockets.
03How SignalR connects: negotiation and transport fallback
Opening a connection (ASP.NET Core SignalR)
Negotiate
The client POSTs to /hubUrl/negotiate. The server replies with a connection id/token and the transports it supports.
Try the best transport
The client tries WebSockets first; if the browser, a proxy or the server cannot do it, it falls back to Server-Sent Events, and finally to Long Polling.
Handshake
Client and server agree on the hub protocol: JSON (default) or the binary MessagePack.
Keep alive
Both sides send small ping messages (every 15 s by default); if nothing arrives for 30 s the other side is considered gone.
Reconnect
With withAutomaticReconnect(), a dropped client retries after 0, 2, 10 and 30 seconds before giving up.
Fallback matters in the real world: old browsers, corporate proxies that strip the Upgrade header, and servers without WebSocket support (IIS before version 8, i.e. before Windows Server 2012) cannot use WebSockets. The application code stays the same whichever transport is chosen — that is the point of SignalR. Classic ASP.NET SignalR tried WebSockets → Server-Sent Events → Forever Frame (IE only) → Long Polling.
TextWithout these headers a reverse proxy silently downgrades every client to SSE or long polling
# nginx in front of the app: pass the WebSocket upgrade through the proxy
location /allotmenthub {
proxy_pass http://app_servers;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
04Hubs on the server
A hub is the central class of a SignalR application. It derives from Microsoft.AspNetCore.SignalR.Hub; its public methods can be called by clients, and through its Clients property it calls methods that clients have registered. Context describes the current connection (Context.ConnectionId, Context.User, Context.UserIdentifier) and Groups manages group membership.
C#
using Microsoft.AspNetCore.SignalR;
public class AllotmentHub : Hub
{
// called by a browser: connection.invoke("SendMessage", "Anil", "Draw starts at 11")
public async Task SendMessage(string user, string text)
{
await Clients.All.SendAsync("ReceiveMessage", user, text); // everyone, sender included
}
public async Task WatchDistrict(string district)
{
await Groups.AddToGroupAsync(Context.ConnectionId, district);
await Clients.Caller.SendAsync("Info", "Now watching " + district); // only the caller
}
public async Task Typing(string user)
{
await Clients.Others.SendAsync("UserTyping", user); // everyone except the caller
}
public override async Task OnConnectedAsync()
{
await Clients.Others.SendAsync("Info", "An officer joined");
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception? exception)
{
await Clients.Others.SendAsync("Info", "An officer left");
await base.OnDisconnectedAsync(exception);
}
}
Target
Who receives the message
Clients.All
Every connected client
Clients.Caller
Only the connection that called the hub method
Clients.Others
Everyone except the caller
Clients.Client(id), Clients.Clients(ids)
Specific connections
Clients.AllExcept(ids)
Everyone except the listed connections
Clients.Group("Kollam"), Clients.Groups(…)
Members of one or more groups
Clients.OthersInGroup("Kollam")
A group's members except the caller
Clients.User(userId), Clients.Users(…)
Every connection (tab, device) of an authenticated user
C#
// Program.cs — register SignalR and map the hub to a URL
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSignalR();
builder.Services.AddSingleton<BookingNotifier>();
var app = builder.Build();
app.UseStaticFiles(); // serves the HTML page and signalr.js
app.MapHub<AllotmentHub>("/allotmenthub");
app.Run();
// pushing from outside a hub (a controller, a background job) with IHubContext
public class BookingNotifier
{
private readonly IHubContext<AllotmentHub> _hub;
public BookingNotifier(IHubContext<AllotmentHub> hub) => _hub = hub;
// called after a booking has been saved in the database
public Task UnitBookedAsync(string district, int schemeId, int unitsLeft) =>
_hub.Clients.Group(district).SendAsync("UnitsLeft", schemeId, unitsLeft);
}
Watch out
Hubs are transient: SignalR creates a new hub object for every method call and disposes it afterwards. A counter kept in a hub field is lost immediately — store shared state in a singleton service, a database or a cache, and never keep long-lived references to the hub itself.
05The JavaScript client
HTML
<ul id="messages"></ul><input id="msg"><button id="send">Send</button><script src="js/signalr.min.js"></script><!-- from the @microsoft/signalr npm package --><script>
const connection = new signalR.HubConnectionBuilder()
.withUrl("/allotmenthub")
.withAutomaticReconnect() // retry after 0, 2, 10 and 30 seconds
.configureLogging(signalR.LogLevel.Information)
.build();
connection.on("ReceiveMessage", (user, text) => { // the hub calls this
const li = document.createElement("li");
li.textContent = user + ": " + text; // textContent: no HTML injection
document.getElementById("messages").appendChild(li);
});
connection.on("UnitsLeft", (schemeId, left) => {
document.getElementById("left-" + schemeId).textContent = left;
});
connection.onreconnecting(() => console.log("Connection lost, reconnecting…"));
connection.onclose(() => console.log("Disconnected"));
async function start() {
try {
await connection.start(); // negotiate, then open the best transport
await connection.invoke("WatchDistrict", "Kollam");
} catch (err) {
console.error(err);
setTimeout(start, 5000); // the first connection failed: try again
}
}
start();
document.getElementById("send").addEventListener("click", async () => {
const text = document.getElementById("msg").value;
await connection.invoke("SendMessage", "Anil", text); // runs AllotmentHub.SendMessage
});
</script>
connection.on("name", handler) registers a function the server may call; register handlers before start() so no early message is missed.
connection.invoke("Method", …args) calls a hub method and returns a promise that resolves with its return value (or rejects with its error); connection.send(…) is fire-and-forget.
start() and stop() open and close the connection; onreconnecting, onreconnected and onclose report its state.
Clients also exist for .NET (Microsoft.AspNetCore.SignalR.Client), Java and others; all speak the same hub protocol.
06Groups, users, scale-out and hosting
Groups are named sets of connections — 'Kollam', 'admins', 'scheme-7' — created implicitly by Groups.AddToGroupAsync(Context.ConnectionId, name) and left with RemoveFromGroupAsync. Membership is not remembered across reconnections, so clients rejoin (as the start() function above does). Users are identified by Context.UserIdentifier (from the authenticated user), so Clients.User(id) reaches every tab and device of one person.
Scale-out is the hard part. With three servers behind a load balancer, each server knows only its own connections: a message sent on server 1 never reaches clients held by server 2. Two standard fixes exist:
A backplane — every server publishes messages to a shared message bus that relays them to all servers: Redis in ASP.NET Core (builder.Services.AddSignalR().AddStackExchangeRedis("redis:6379")); classic SignalR also offered SQL Server and Azure Service Bus backplanes.
Azure SignalR Service — a managed service that holds all client connections itself; the app servers only send messages to it (AddSignalR().AddAzureSignalR()).
With several servers, sticky sessions are needed so the negotiate request and the following connection reach the same server — unless every client uses WebSockets with negotiation skipped, or Azure SignalR Service is used.
Hosting notes: IIS needs the WebSocket Protocol feature enabled (IIS 8 or later); Kestrel supports WebSockets natively; every open connection consumes a socket and some memory, so connection limits and timeouts must be planned. Messages should be small — send ids and changed values, not whole pages.
Groups, users, backplanes and a managed cloud service
Similar libraries in other ecosystems include Socket.IO (Node.js) and hosted services such as Pusher and Firebase. For the exam, remember SignalR as 'real-time push for ASP.NET, built on hubs, with automatic transport fallback'.
Step through · SignalR broadcast from one client to all
step 1 / 11
Step 1: negotiate → WebSocket opened
Client A's start() negotiates; both sides support WebSockets, so one full-duplex connection opens.
Worked examples
Try the problem first, then reveal the working one step at a time.
EX 1Polling vs SignalR push for a live draw
25,000 citizens watch a live allotment-draw page. A new result appears about every 30 s. (a) With polling every 4 s, find the request rate, the average delay and the share of wasted polls. (b) With SignalR, how many push messages per second are sent, and what does the 15-second keep-alive add?
EX 2Choosing the right Clients target
In a hub method, which target fits each case? (a) A chat message for everyone in the room; (b) a 'message saved' receipt for the sender only; (c) 'Anil is typing…' for everyone else; (d) a unit-count update only for officers watching Kollam; (e) an approval notice for user anil on every device he has open; (f) a message to the Kollam group except the officer who posted it.
EX 3Which transport will be used?
Predict the transport for an ASP.NET Core SignalR client in each case: (a) a current browser talking to Kestrel directly; (b) the same browser behind a corporate proxy that strips the Upgrade header; (c) an old browser without EventSource behind that proxy; (d) a current browser reaching an app on IIS 7.5 (Windows Server 2008 R2).
EX 4Designing a live allotment dashboard
Officers in 14 districts must see unit counts change the moment a booking is saved. The application runs on 3 servers behind a load balancer. Outline the design.
Practice session
Work each problem on paper first, then check. Marking one solved earns 10 XP.0/5 solved
Q1
Write a hub method LeaveDistrict(string district) that removes the caller from the district's group and confirms only to the caller, and the JavaScript line that calls it.
Q2
4,000 clients poll every 2 s for data that changes 6 times a minute. Find the request rate, the average and worst-case delay, and the share of polls that return nothing new.
Q3
A developer counts messages in a field: private int _count; public Task Send(string m) { _count++; … }. The count is always 1. Why, and how should it be fixed?
Q4
Explain the difference between connection.on, connection.invoke and connection.send in the JavaScript client, with one example each.
Q5
Why does a multi-server SignalR deployment usually need sticky sessions, and when can it do without them?
Exam traps
SignalR is not 'WebSockets only' — WebSockets is the preferred transport; Server-Sent Events and Long Polling are automatic fallbacks.
Clients.All includes the caller; Clients.Others excludes it.
Hub instances are created per call (transient) — fields do not survive between calls.
Group membership belongs to a connection and is lost on reconnection; clients must rejoin their groups.
Classic ASP.NET SignalR and ASP.NET Core SignalR are incompatible: a jQuery-era client cannot talk to a Core hub.
Server-Sent Events push only server → client; in that mode SignalR sends client-to-server calls as ordinary HTTP POSTs.
Quiz — KPSC style
10 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
SignalR & real-time web · Question 1 of 10✓ 0 · ✗ 0
SignalR is a library for:
Past-paper questions on this topic
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.
Past papers · Question 1 of 3✓ 0 · ✗ 0
Modelled on QP 050/2026 · Deputy Manager (IT) / Assistant Programmer / Computer Programmer etc (20 May 2026), Q.67 (reworded)original paper (PDF)
Which technology keeps a persistent two-way connection open between client and server, so the server can push content without the client asking for it first?