In this lesson, you will learn how to architect SignalR hubs to strictly isolate data traffic between tenants by leveraging scoped group management.
The Challenge of Multi-Tenancy
In a multi-tenant system, a single SignalR hub instance processes connections from multiple clients across different organizations. If you simply broadcast a message, you risk a "data leak," where Tenant A receives updates intended for Tenant B. To prevent this, we must enforce logical isolation at the connection level by tethering every user to their specific TenantId.
Isolating Traffic via Groups
The most efficient way to achieve this is to treat the TenantId as a foundational part of your connection management. As soon as a user authenticates, you should extract their TenantId (typically from their ClaimsPrincipal) and assign them to a dedicated group that shares the same ID.
public class TenantHub : Hub
{
public override async Task OnConnectedAsync()
{
// Extract the TenantId from the authenticated user's claims
var tenantId = Context.User?.FindFirst("TenantId")?.Value;
if (!string.IsNullOrEmpty(tenantId))
{
// Join a group uniquely identified by the TenantId
await Groups.AddToGroupAsync(Context.ConnectionId, $"tenant_{tenantId}");
}
await base.OnConnectedAsync();
}
}
Broadcasting Within Boundaries
Once you have organized your connections into tenant_{id} groups, you must restrict all outbound communication to these groups. When a background service or another hub method needs to push a real-time update, you use the group name as the broadcast target. This ensures that even if you have thousands of tenants on one server, the SignalR infrastructure handles the filtering for you:
public async Task SendUpdateToTenant(string tenantId, string message)
{
// Targeted broadcasting ensures Tenant B never hears Tenant A's data
await Clients.Group($"tenant_{tenantId}").SendAsync("ReceiveUpdate", message);
}
By decoupling your communication logic from the global hub context and tying it to these tenant-specific groups, you create a robust perimeter that prevents cross-tenant data leakage while maintaining high-performance real-time throughput.
Key Takeaway: Always derive your group names from the authenticated TenantId claim to enforce hard boundaries on message distribution and prevent cross-tenant data exposure.