LESSON 14 OF 14

14. Integration Testing, Observability, and Production Readiness

Validate SignalR hub and API workflows with integration tests, then apply structured logging, metrics, correlation IDs, and production readiness checks.

55 dk 60

Introduction

In the previous lessons, you completed the main SignalR building blocks: hubs, user and group messaging, JWT security, reconnection, background services, and the Redis backplane. This final lesson turns the real-time application into a system that can be tested, monitored, and safely deployed.

A real-time system is not successful merely because a message reaches a browser. When a connection fails, the team must be able to identify which component failed. When an unauthorized user invokes a hub method, the request must be rejected. When a client reconnects, the behavior must be observable and predictable. Under load, connection counts, memory, sockets, and message latency must be measurable. We will address these requirements through three connected practices: integration testing, observability, and production readiness.

1. Divide the testing strategy into layers

Instead of turning every scenario into one large end-to-end test, separate tests by responsibility.

  • Unit tests: Isolate authorization decisions, validation, and business rules inside hub-related services.
  • API integration tests: Verify routing, model binding, authentication, authorization, service registration, persistence, and HTTP responses together.
  • Hub integration tests: Validate negotiation, connection establishment, hub invocation, and delivery of client methods.
  • Deployment or smoke tests: Validate TLS, proxy configuration, Redis, health checks, and a basic messaging workflow in a production-like environment.

ASP.NET Core integration tests commonly use WebApplicationFactory<TEntryPoint> and a test host. The test project references the application and can replace configuration, databases, authentication, or external services for isolation.

2. Prepare the test project

Assume the solution contains an application named RealtimeApp and a test project named RealtimeApp.Tests. Add xUnit, ASP.NET Core MVC Testing, and the SignalR .NET Client:

dotnet add RealtimeApp.Tests package Microsoft.AspNetCore.Mvc.Testing
dotnet add RealtimeApp.Tests package Microsoft.AspNetCore.SignalR.Client
dotnet add RealtimeApp.Tests package xunit

Expose the application entry point to the test project with:

public partial class Program { }

Use an isolated database, deterministic test authentication, and test-specific configuration. Every test should create its own data and should not depend on the execution order of other tests.

3. Write an API integration test

The following factory starts the application pipeline with a test environment. In a real project, the service configuration can replace the production database and register a test authentication handler.

public sealed class AppFactory : WebApplicationFactory<Program>
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.UseEnvironment("Testing");
        builder.ConfigureAppConfiguration((_, configuration) =>
        {
            configuration.AddInMemoryCollection(new Dictionary<string, string?>
            {
                ["ConnectionStrings:Default"] = "DataSource=:memory:",
                ["SignalR:EnableDetailedErrors"] = "true"
            });
        });
    }
}

For example, test that an authorized user can create a task and that the response follows the expected contract:

public class TaskApiTests : IClassFixture<AppFactory>
{
    private readonly HttpClient _client;

    public TaskApiTests(AppFactory factory)
    {
        _client = factory.CreateClient();
        _client.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue("Test", "user-42");
    }

    [Fact]
    public async Task CreateTask_ReturnsCreated()
    {
        var response = await _client.PostAsJsonAsync("/api/tasks", new
        {
            Title = "Integration test",
            Group = "team-alpha"
        });

        response.StatusCode.Should().Be(HttpStatusCode.Created);
        var task = await response.Content.ReadFromJsonAsync<TaskResponse>();
        task!.Title.Should().Be("Integration test");
    }
}

This test validates more than a controller method. It covers routing, model binding, authorization, dependency injection, serialization, and the HTTP status code through the application pipeline.

4. Test the hub connection and message flow

A hub integration test should verify that the connection is established, the client subscribes to the expected server method, and invoking a hub method results in a message. Because WebSocket support may be limited in an in-memory test server, a practical approach is to start a temporary Kestrel host on a random local port for end-to-end hub tests. The negotiate endpoint can also be tested separately as a normal HTTP integration test.

Assume the hub contract looks like this:

public interface ITaskClient
{
    Task TaskUpdated(TaskUpdatedMessage message);
}

public class TaskHub : Hub<ITaskClient>
{
    [Authorize(Policy = "TaskEditor")]
    public async Task UpdateTask(UpdateTaskRequest request)
    {
        var result = await _taskService.UpdateAsync(request, Context.UserIdentifier!);
        await Clients.Group(request.Group)
            .TaskUpdated(result);
    }
}

A client connecting to the real test host can follow this pattern:

var received = new TaskCompletionSource<TaskUpdatedMessage>(
    TaskCreationOptions.RunContinuationsAsynchronously);

await using var connection = new HubConnectionBuilder()
    .WithUrl($"{serverUrl}/hubs/tasks", options =>
    {
        options.AccessTokenProvider = () => Task.FromResult<string?>(editorToken);
    })
    .WithAutomaticReconnect()
    .Build();

connection.On<TaskUpdatedMessage>("TaskUpdated", message =>
    received.TrySetResult(message));

await connection.StartAsync();
await connection.InvokeAsync("JoinGroup", "team-alpha");
await connection.InvokeAsync("UpdateTask", new
{
    Id = taskId,
    Group = "team-alpha",
    Title = "Updated"
});

var message = await received.Task.WaitAsync(TimeSpan.FromSeconds(5));
message.Title.Should().Be("Updated");

Use an event-driven wait such as TaskCompletionSource instead of a fixed and lengthy Task.Delay. The test will complete quickly when the message arrives and will fail with a useful timeout when it does not.

5. Test authorization and connection scenarios

Negative security scenarios are as important as successful ones. Cover at least the following cases:

  • A client without a JWT cannot negotiate or establish a hub connection.
  • An authenticated user without the TaskEditor policy cannot invoke UpdateTask.
  • A user cannot receive messages from a group they have not joined.
  • A message sent through Clients.User is delivered only to the intended user.
  • A new connection with an invalid or expired token is rejected.

Keep the claims used by tests close to the production design. Explicitly define which claim supplies the user identifier, such as NameIdentifier. Otherwise tests may pass while user-targeted messaging fails in the deployed application.

6. Test reconnection and background services

For reconnection tests, observe the client’s Reconnecting, Reconnected, and Closed events. Simulate a temporary outage and verify that the client reconnects and that group membership is restored according to the application’s design.

var reconnected = new TaskCompletionSource<string?>();
connection.Reconnected += id =>
{
    reconnected.TrySetResult(id);
    return Task.CompletedTask;
};

await StopServerTemporarilyAsync();
await StartServerAgainAsync();

await reconnected.Task.WaitAsync(TimeSpan.FromSeconds(15));

For a background service, tests that wait for real time can become fragile. Replace its IHubContext<TaskHub, ITaskClient> dependency with a test double and verify that the expected user or group method is called. Then use a smaller number of smoke tests to verify the service, Redis, and SignalR together on a real host.

7. Structured logging and correlation IDs

Plain-text logs are not enough to investigate a report such as “the message did not arrive.” Every HTTP request and hub operation should be associated with a correlation ID or trace ID.

app.Use(async (context, next) =>
{
    var correlationId = context.Request.Headers.TryGetValue(
        "X-Correlation-ID", out var value)
        ? value.ToString()
        : Guid.NewGuid().ToString("N");

    context.Response.Headers["X-Correlation-ID"] = correlationId;
    using (LogContext.PushProperty("CorrelationId", correlationId))
    {
        await next();
    }
});

Inside a hub, log connection, user, and group information as structured properties. Do not write tokens, passwords, or sensitive message bodies to logs:

public override async Task OnConnectedAsync()
{
    using var scope = _logger.BeginScope(new Dictionary<string, object>
    {
        ["ConnectionId"] = Context.ConnectionId,
        ["UserId"] = Context.UserIdentifier ?? "anonymous"
    });

    _logger.LogInformation("SignalR connection established");
    await base.OnConnectedAsync();
}

The Microsoft.AspNetCore.SignalR and Microsoft.AspNetCore.Http.Connections categories are particularly useful for connection, protocol, and transport diagnostics. Avoid leaving verbose logging enabled permanently in production; enable it temporarily and with appropriate access controls.

8. Metrics and alerts

Logs explain individual events, while metrics reveal system-wide trends. At minimum, monitor:

  • Active SignalR connection count.
  • Connection establishment and disconnection rates.
  • Hub invocation count and failure rate.
  • Message publication latency.
  • API and negotiate response duration.
  • Redis backplane errors and latency.
  • CPU, memory, socket, and thread-pool usage.

You can add an application-specific meter:

public static class RealtimeMetrics
{
    public static readonly Meter Meter = new("RealtimeApp.SignalR");
    public static readonly Counter<long> PublishedMessages =
        Meter.CreateCounter<long>("realtime.messages.published");
    public static readonly Histogram<double> PublishDuration =
        Meter.CreateHistogram<double>("realtime.publish.duration", "ms");
}

Avoid using user IDs or connection IDs as metric labels because they create high cardinality. Group names and error categories should also be controlled when they can have unlimited variation. OpenTelemetry can export application meters, ASP.NET Core HTTP measurements, and traces to a centralized observability platform.

9. Production readiness checklist

AreaCheck
SecurityHTTPS is enforced, CORS uses an allow-list, JWT lifetime is reviewed, and hub policies are tested.
ConnectivityWebSocket proxy settings, timeouts, keep-alive, and reconnection behavior are verified.
ScalingRedis connectivity, sticky-session requirements, pub/sub latency, and Redis outage behavior are evaluated.
ResourcesActive connections, memory, TCP sockets, CPU, and thread-pool limits are measured.
ObservabilityCorrelation IDs, structured logs, metrics, traces, dashboards, and alerts are available.
DeploymentHealth checks, rollback procedures, secret management, and smoke tests are prepared.

10. Common mistakes

  • Testing only controllers: Hub negotiation, connection, and transport failures remain undetected.
  • Using the production Redis instance in tests: Tests interfere with one another and may send messages to real users.
  • Waiting with a fixed Task.Delay: Tests become slow and flaky.
  • Logging tokens or message bodies: Sensitive information can leak through logs.
  • Adding a user label to every metric: High cardinality can overload the metrics backend.
  • Trying TLS and proxy settings only at the end: WebSocket upgrade, CORS, 307, and 404 problems appear during deployment.

Short practice exercise

Task: Build an integration and observability package for the task dashboard from the previous lessons.

  1. Test task creation through the API.
  2. Verify that an authorized user connects to the hub and receives a group message.
  3. Test that an unauthorized user cannot invoke the update method.
  4. Produce a structured log containing a correlation ID when a message is published.
  5. Add a counter for published messages and a histogram for publication duration.
  6. Write a smoke test or documented verification step for at least five items in the production checklist.

Conclusion

A production-ready SignalR application is more than a working hub. Integration tests catch failures in HTTP, authentication, authorization, and real message delivery before release. Structured logs and correlation IDs make it possible to follow the lifecycle of a single connection. Metrics provide continuous visibility into active connections, errors, latency, and resource consumption.

As a final review, ensure that your test coverage includes connection, messaging, authorization, reconnection, background-service, and Redis scenarios. Measure performance limits, verify security settings, and prepare a rollback plan before deployment. The result is not merely a sample SignalR application, but an observable, testable, and scalable real-time system.

Sources