In this lesson, you will learn how to optimize your SignalR bandwidth usage by switching from standard JSON to binary serialization using MessagePack.
When you send data through a SignalR Hub, SignalR defaults to using JSON. While human-readable and versatile, JSON is a text-based format that carries significant overhead due to repeated field names and character encoding. As you scale your real-time applications—especially those transmitting frequent, high-frequency telemetry or game state updates—this overhead can impact your latency and total bandwidth consumption.
Switching to MessagePack
MessagePack is a binary-based serialization format. Instead of sending long property names as strings, it uses compact, type-aware binary representations. This effectively compresses your payloads before they hit the wire.
To implement this, you first install the Microsoft.AspNetCore.SignalR.Protocols.MessagePack NuGet package. Once installed, you configure the Hub pipeline in your Program.cs to support both JSON and MessagePack:
builder.Services.AddSignalR()
.AddMessagePackProtocol();
By adding this, your server can automatically negotiate the most efficient protocol with the client. When a client (like a .NET or JavaScript browser client) initiates a connection, it indicates its supported protocols. If the client also supports MessagePack, SignalR will switch to it for that connection automatically.
Why Optimization Matters
Beyond mere payload size, MessagePack can be faster for the CPU to parse because it avoids complex string parsing and character escaping. If you are dealing with large object graphs or collections transmitted via your Hub methods, the performance gains are multiplicative.
However, remember that MessagePack is binary, making it harder to debug via browser network tools compared to JSON. When working in complex scenarios, consider using the MessagePack.Annotations to explicitly define index-based serialization (e.g., using [Key(0)]) to further reduce payload size by stripping property names entirely from the binary stream.
Key Takeaway: By implementing the MessagePack protocol, you trade human-readable JSON for a compact, high-performance binary format that reduces payload size and lowers serialization overhead in bandwidth-constrained real-time applications.