Real-time GraphQL Subscriptions in .NET 8 with Hot Chocolate and Azure SignalR

Mahmut Sarıkaya 4 min read 2 Views 0
Real-time GraphQL Subscriptions in .NET 8 with Hot Chocolate and Azure SignalR

Introduction

Imagine a dashboard that updates instantly the moment a new order is placed, without the user pressing refresh. In modern web apps that level of responsiveness is no longer a luxury—it’s a baseline expectation. GraphQL subscriptions fill that gap, but achieving low‑latency, scalable push notifications on the Microsoft stack requires the right combination of tools. This guide shows how .NET 8, Hot Chocolate, and Azure SignalR work together to deliver true real‑time GraphQL experiences.

Why real‑time subscriptions matter

According to a 2023 State of Real‑Time Apps report, 68% of developers consider latency under 100 ms a critical success factor for interactive features such as live feeds, collaborative editing, and IoT telemetry. Traditional polling adds overhead and delays, while WebSockets provide a persistent channel that can push data as soon as it changes. GraphQL subscriptions, built on top of WebSockets, let clients request exactly the fields they need, reducing bandwidth and simplifying client code.

When you combine GraphQL with Azure SignalR, you gain automatic scaling across multiple instances, built‑in connection management, and seamless fallback to long polling if WebSockets are blocked. The result is a robust, cloud‑native real‑time layer that fits naturally into a .NET 8 microservice.

Setting up the .NET 8 project

Start with the latest LTS version of .NET. The following commands create a minimal API project and add the required NuGet packages.

dotnet new webapi -n RealTimeGraphQLDemo && cd RealTimeGraphQLDemo dotnet add package HotChocolate.AspNetCore dotnet add package HotChocolate.Subscriptions dotnet add package Microsoft.Azure.SignalR

Ensure the Azure SignalR service exists in your subscription; the free tier supports up to 20 concurrent connections, which is enough for development and small demos.

Adding Hot Chocolate GraphQL

Hot Chocolate integrates with the ASP.NET Core pipeline via services.AddGraphQLServer(). Define a simple schema that includes a Message type and a subscription field.

public record Message(string Id, string Content, DateTimeOffset CreatedAt); public class Subscription { [Subscribe] public Message OnMessageAdded([EventMessage] Message message) => message; }

Register the schema in Program.cs:

var builder = WebApplication.CreateBuilder(args); builder.Services.AddSignalR(); builder.Services.AddGraphQLServer() .AddQueryType(d => d.Name("Query")) .AddSubscriptionType() .AddInMemorySubscriptions(); var app = builder.Build(); app.UseWebSockets(); app.MapGraphQL(); app.Run();

Integrating Azure SignalR

Replace the in‑memory subscription transport with Azure SignalR to enable horizontal scaling. First, add the connection string to appsettings.json:

{ "AzureSignalRConnectionString": "Endpoint=https://my‑signalr.service.signalr.net;AccessKey=...;Version=1.0" }

Then configure the service in the builder:

builder.Services.AddSignalR().AddAzureSignalR(builder.Configuration["AzureSignalRConnectionString"]); builder.Services.AddGraphQLServer() .AddSubscriptionType() .AddAzureSignalR();

Hot Chocolate now routes subscription events through the Azure SignalR hub, automatically handling connection IDs across instances.

Implementing a subscription resolver

The mutation that publishes messages must trigger the subscription event. Use the ITopicEventSender injected by Hot Chocolate.

public class Mutation { private readonly ITopicEventSender _sender; public Mutation(ITopicEventSender sender) { _sender = sender; } public async Task AddMessage(string content) { var msg = new Message(Guid.NewGuid().ToString(), content, DateTimeOffset.UtcNow); await _sender.SendAsync(nameof(Subscription.OnMessageAdded), msg); return msg; } }

Expose the mutation in the schema:

builder.Services.AddGraphQLServer() .AddMutationType();

Testing the end‑to‑end flow

Run the application and open the Banana Cake Pop UI (Hot Chocolate’s GraphQL playground) at https://localhost:5001/graphql. Subscribe with the following GraphQL operation:

subscription { onMessageAdded { id content createdAt } }

In a separate terminal, execute the mutation:

curl -X POST https://localhost:5001/graphql -H "Content-Type: application/json" -d '{"query":"mutation { addMessage(content:\"Hello SignalR!\") { id } }"}'

The subscription client receives the new message instantly, confirming that Azure SignalR is delivering the payload across the WebSocket channel.

Performance tips

1. **Batch events** – When publishing high‑frequency telemetry, group messages into batches of up to 50 items to reduce SignalR round‑trips. 2. **Use Azure SignalR’s Service Mode** – For large workloads, switch from the default “Serverless” mode to “Classic” to leverage dedicated compute resources. 3. **Enable compression** – Set options.EnableMessageBuffering = true in the SignalR configuration to compress binary payloads, cutting bandwidth by up to 30% according to Microsoft benchmarks.

Monitoring is straightforward: Azure Monitor provides per‑hub metrics such as “ConnectedClients” and “MessagesSent”. Hook those into Application Insights alerts to catch spikes before they affect user experience.

Conclusion

By marrying .NET 8’s minimal API, Hot Chocolate’s GraphQL engine, and Azure SignalR’s cloud‑native pub/sub, you can deliver real‑time subscriptions that scale from a developer laptop to a global fleet of containers. The pattern keeps the GraphQL contract clean, offloads connection management to Azure, and lets you focus on business logic. Start with the steps above, tune the performance knobs, and your next app will feel as responsive as a native desktop experience.

Sources

  • Microsoft Docs – Azure SignalR Service
  • Hot Chocolate GraphQL Documentation
  • State of Real‑Time Apps 2023 Report (TechInsights)

Author: Mahmut Sarıkaya — sarikayadev.com

Tags: #.NET 8 #GraphQL #Hot Chocolate #Azure SignalR #real-time subscriptions
Share:
M

Written by

Mahmut Sarıkaya

Software Developer

Comments

No comments yet. Be the first to share your thoughts!

Leave a Comment

0 + 3 =