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

Binary Protocol Performance Tuning

Switch from JSON to MessagePack to minimize latency and payload size in high-throughput applications.

In this lesson, you will learn how to optimize your SignalR throughput by replacing the default text-based JSON protocol with the high-performance MessagePack binary format.

Why JSON isn't always enough

By default, SignalR uses JSON to serialize messages. While human-readable and convenient for debugging, JSON is verbose. It repeats property names in every single packet and relies on text-based encoding for numbers and booleans, which leads to larger payloads and increased CPU overhead for string parsing. In a high-throughput system—such as a real-time trading dashboard or a multiplayer game—these extra bytes add up, consuming unnecessary bandwidth and increasing latency.

The MessagePack Advantage

MessagePack is an efficient binary serialization format. It functions much like a compact version of JSON, but instead of sending property names as strings (e.g., "username": "Alice"), it uses a schema-based approach or indexed arrays to represent data. This significantly shrinks the payload size and allows the runtime to deserialize the data much faster, as it doesn't need to parse complex text structures.

To implement this in your SignalR application, you first install the Microsoft.AspNetCore.SignalR.Protocols.MessagePack NuGet package. Then, configure your server to support it during the Service collection registration:

// Startup.cs or Program.cs
builder.Services.AddSignalR()
    .AddMessagePackProtocol();

Client-Side Configuration

Once the server is configured, your clients must also be updated to request the binary protocol. If the client doesn't explicitly opt-in to the binary protocol, SignalR will fallback to the standard JSON format. For a JavaScript or C# client, the setup is straightforward:

// C# Client initialization
var connection = new HubConnectionBuilder()
    .WithUrl("https://your-hub-url")
    .AddMessagePackProtocol() // Must match the server configuration
    .Build();

By switching to MessagePack, your application effectively reduces the "chatter" between the client and server. The reduction in payload size is especially noticeable when sending high-frequency updates, such as telemetry data or real-time ticker prices, where every millisecond of serialization time matters.

Key Takeaway: Moving from JSON to the MessagePack binary protocol reduces payload size and CPU usage, providing a crucial performance boost for high-frequency, real-time SignalR applications.