Skip to content

[P2] Add connection limiting per virtual key for SignalR hubs #182

@nickna

Description

@nickna

Description

While implementing virtual key authentication for SignalR hubs (#174), we identified a potential scalability concern: there's currently no limit on the number of concurrent SignalR connections a single virtual key can establish. This could lead to resource exhaustion if a customer (intentionally or unintentionally) opens hundreds or thousands of connections.

Current State

  • Virtual keys can open unlimited SignalR connections
  • Each connection consumes server resources (memory, CPU)
  • No connection pooling guidance for clients

Proposed Solution

1. Add Connection Limiting

Implement a per-virtual-key connection limit in the SignalR hubs:

public override async Task OnConnectedAsync()
{
    var virtualKeyId = GetVirtualKeyId();
    
    // Track active connections in Redis
    var activeConnections = await _cache.IncrementAsync($"vkey_connections:{virtualKeyId}");
    
    // Check against configurable limit
    var maxConnections = _configuration.GetValue<int>("SignalR:MaxConnectionsPerVirtualKey", 100);
    if (activeConnections > maxConnections)
    {
        await _cache.DecrementAsync($"vkey_connections:{virtualKeyId}");
        _logger.LogWarning("Virtual Key {KeyId} exceeded connection limit of {Limit}", 
            virtualKeyId, maxConnections);
        Context.Abort();
        return;
    }
    
    // Continue with normal connection...
}

public override async Task OnDisconnectedAsync(Exception? exception)
{
    var virtualKeyId = GetVirtualKeyId();
    await _cache.DecrementAsync($"vkey_connections:{virtualKeyId}");
    // Continue with normal disconnection...
}

2. Add Configuration

Add new configuration options:

{
  "SignalR": {
    "MaxConnectionsPerVirtualKey": 100,
    "ConnectionLimitWindowMinutes": 5
  }
}

3. Client Guidance

Document best practices for clients:

  • Implement connection pooling
  • Use exponential backoff for reconnections
  • Reuse connections for multiple subscriptions

Benefits

  • Prevents resource exhaustion attacks
  • Ensures fair resource allocation
  • Improves overall system stability

Implementation Notes

  • Use Redis for distributed connection counting
  • Make limits configurable per environment
  • Consider different limits for different hub types
  • Add metrics for monitoring connection patterns

Testing Requirements

  • Test connection limit enforcement
  • Test proper cleanup on disconnection
  • Test behavior across multiple server instances
  • Load test with many virtual keys at their limits

Related

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions