Building a SignalR chat application with C# and .NET, then scaling with a Redis backplane and multiple dynos on Heroku, with session affinity (sticky sessions)
dotnet new webapp -o SignalRChat
The SignalR server library is included in the ASP.NET Core shared framework, but the JavaScript client library isn't automatically included. Use LibMan to get it.
dotnet tool install -g Microsoft.Web.LibraryManager.Cli
Note: You may need to add $HOME/.dotnet/tools
to your PATH
libman install @microsoft/signalr@latest -p unpkg -d wwwroot/js/signalr --files dist/browser/signalr.js
Created the following files:
hubs/ChatHub.cs
: The hub class that serves as a high-level pipeline that handles client-server communicationPages/Index.cshtml
: The main Razor file, combining HTML and embedded C# with Razor syntax.wwwroot/js/chat.js
: The chat logic for the application
Updated the main program (Program.cs
) to use SignalR. (The initial commit has the version prior to introducing the Redis backplane).
dotnet build
dotnet run
Open two browsers, navigate to application. Send message in one, see it show up in the other in real time.
This assumes you have an instance of Redis running locally, listening on port 6379
. (You could also spin up a Docker container and port forward your 6379
.)
StackExchange.Redis Package information
dotnet add package Microsoft.AspNetCore.SignalR.StackExchangeRedis
See the updated code for Program.cs
in the latest commit, which configures the app to use Redis as a backplane.
Connection information was tailored for deployment to Heroku, expecting a Redis connection string at REDIS_URL
. See Heroku documentation on connecting to Key-Value Store in .NET.
Start application. Connect via Redis CLI. Run pubsub channels
to see list of channels. Run subscribe SignalRChatSignalRChat.Hubs.ChatHub:all
to subscribe.
Reload application in the browser. Send messages. See messages in Redis CLI.
heroku login
heroku create my-signalr-demo-app
heroku buildpacks:add heroku/dotnet
heroku addons:add heroku-redis
See Procfile
in project root folder.
git push heroku main
Test in browsers, this time pointing to Heroku app URL instead of localhost.
heroku ps:type web=standard-1x
heroku ps:scale web=3
Reload application in the browser. Note in network inspector that WebSocket connections are failing.
More on the session affinity feature here.
heroku features:enable http-session-affinity
Reload application in the browser. WebSocket connections should be maintained, and chat messages should come across in real time.