Course contentsShow
← C#
Lesson 1467 of 1,90813. Real-time Communication with SignalRFree lesson

Real-Time Telemetry and Monitoring

Export connection metrics and throughput data to observability platforms like Prometheus.

In this lesson, you will learn how to instrument your SignalR hubs to export connection metrics and throughput data directly into observability platforms like Prometheus.

Why Monitor SignalR?

SignalR applications often suffer from "black box" syndrome. While you know your messages are being sent, you may lack visibility into how many active connections exist, how many messages are being dropped due to backpressure, or how long hub methods take to execute under load. By exposing these metrics via an IMeterFactory or standard EventCounters, you can scrape this data into Prometheus to visualize the health of your real-time infrastructure.

Instrumenting Hubs for Prometheus

To capture real-time telemetry, we inject a custom Meter into our application. Instead of logging, we increment counters or record durations within our Hub methods. When Prometheus scrapes your /metrics endpoint, it reads these high-performance, low-overhead values.

Consider this example of tracking active hub invocations and message throughput:

public class MonitoringHub : Hub
{
    private static readonly Counter<int> MessageCounter = 
        MyMetrics.Meter.CreateCounter<int>("signalr_messages_total");

    public override async Task OnConnectedAsync()
    {
        // Increment global connection gauge
        ConnectionMetrics.ActiveConnections.Add(1);
        await base.OnConnectedAsync();
    }

    public async Task SendUpdate(string data)
    {
        MessageCounter.Add(1, new KeyValuePair<string, object?>("method", "SendUpdate"));
        await Clients.All.SendAsync("ReceiveUpdate", data);
    }
}

Visualizing Throughput

Once your Meter is configured, you don't just see "number of messages." You gain the ability to use Prometheus expressions like rate(signalr_messages_total[1m]) to see your throughput in real-time. This is critical for identifying spikes in traffic that might necessitate horizontal scaling or trigger your backpressure mitigation logic. By mapping these metrics to your specific Hub methods, you can pinpoint which parts of your real-time ecosystem are causing latency bottlenecks or memory pressure before they affect user experience.

Key Takeaway: Instrument your hubs using .NET System.Diagnostics.Metrics to export granular, high-fidelity real-time telemetry, allowing Prometheus to correlate hub method performance with your overall system throughput.