Azure / azure-signalr

Azure SignalR Service SDK for .NET
https://aka.ms/signalr-service
MIT License
427 stars 101 forks source link

A server node cannot send messages to clients before Azure SignalR assigns the first client connection to it #1937

Closed engmarknabil closed 6 months ago

engmarknabil commented 6 months ago

Description

When having multiple server nodes, each node cannot send messages to clients until Azure SignalR assigns the first client connection to it. Before that, Hub.Clients is null.

To Reproduce

Clone this repo and follow the readme

Exceptions (if any)

Further technical details

nfogg commented 6 months ago

Hello, I am a colleague of @engmarknabil and can give some additional details.

We have implemented a Hub subclass named ClientEventService and during the backend server application launch we see messages like:

[12:12:23] info: Microsoft.Azure.SignalR.ServiceConnection[20] Service connection c2b8c44a-92dd-4ef9-8d08-4286f0fb0000 connected. [12:12:23] info: Microsoft.Azure.SignalR.StrongServiceConnectionContainer[1] Hub 'ClientEventService' is now connected to '(Primary)https://*****-signalr.service.signalr.net(hub=ClientEventService)'.

The backend servers are in a cluster. SignalR is used by the backend to forward events to frontend clients.

We have noticed some unexpected behaviour.

After backend application launch we are able to accept new client connections and everything works as expected once at least one client connects to each backend instance.

Once the first inbound client connection is made the instance can then send messages to any connected client, even if that client never connected to this instance.

However, a backend server is unable to send messages to any clients until it has received at least one incoming client connection. Until a client connection is received, the Clients property of the Hub is empty.

This is a problem for us as under light load following a deployment, a backend instance may need to react to external events and send messages to one or more connected clients before having received any client connection requests. We have chosen Azure SignalR in order to abstract the management of client connections and allow any backend instance to communicate with any client.

Is our observed behaviour expected? If so, are there any recommended mitigations?

vwxyzh commented 6 months ago

@engmarknabil please following this document.

in simple words:

  1. require IHubContext<YourHub> from DI
  2. send message by the hub context, e.g.: context.Clients.SendAsync("test-client")
terencefan commented 6 months ago

sample PR: https://github.com/engmarknabil/SignalRTester/pull/1

engmarknabil commented 6 months ago

Thanks @vwxyzh and @terencefan. That solved our issue.