LESSON 14 OF 14

14. Observability, Testing Strategy, and a Production-Ready Asynchronous System

Prepare RabbitMQ and Hangfire workflows for production with structured logging, correlation IDs, health checks, metrics, testing, Docker, security, and scaling.

110 dk 42

Introduction

In the previous lessons, we implemented RabbitMQ producers and consumers, retries and dead-letter queues, idempotency, Hangfire job types, and a workflow that combines both technologies. In this final lesson, we will make the system not only functional, but also observable, testable, and maintainable in production.

In an asynchronous system, a successful HTTP request does not mean that the business operation is complete. The API may have only published a message, the consumer may process it later, a transient failure may trigger a retry, or a Hangfire job may run on a different worker. To understand where a request is in its lifecycle, we need structured logs, correlation IDs, metrics, and health checks working together.

We will use an order-notification workflow as the example: the API publishes a message, a RabbitMQ consumer processes it, a Hangfire email job is created when necessary, and every stage carries the same correlation ID.

1. An observability model

Observability is usually built from three complementary types of data:

  • Logs: What happened, which message or job was involved, and what failed?
  • Metrics: How often does it happen, how long does it take, and how much work is waiting?
  • Trace and correlation data: How can the producer, broker, consumer, and job execution be connected?

Instead of writing unstructured text, use searchable fields such as OrderId, MessageId, CorrelationId, JobId, Attempt, and DurationMs. Never write access tokens, connection strings, payment data, or unnecessary personal information to logs.

Creating a correlation ID

If an incoming request already contains a correlation ID, preserve it. Otherwise generate one and add it to both the response header and the logging scope.

public sealed class CorrelationIdMiddleware(RequestDelegate next)
{
    public async Task InvokeAsync(HttpContext context, ILogger<CorrelationIdMiddleware> logger)
    {
        const string headerName = "X-Correlation-Id";
        var correlationId = context.Request.Headers[headerName].FirstOrDefault();
        correlationId = string.IsNullOrWhiteSpace(correlationId)
            ? Guid.NewGuid().ToString("N")
            : correlationId;

        context.Response.Headers[headerName] = correlationId;

        using (logger.BeginScope(new Dictionary<string, object>
        {
            ["CorrelationId"] = correlationId,
            ["TraceId"] = Activity.Current?.TraceId.ToString() ?? "none"
        }))
        {
            await next(context);
        }
    }
}

The message contract should also contain the correlation ID. This allows a consumer to continue tracing the workflow even when it no longer has access to the original HTTP request.

public sealed record OrderNotificationMessage(
    Guid MessageId,
    Guid OrderId,
    string CorrelationId,
    DateTimeOffset OccurredAt);

When the consumer receives the message, it starts a new logging scope with the message's CorrelationId. If the RabbitMQ connection is recovered later, the relationship between the events is still preserved because the ID travels with the message.

Structured logging

public sealed class OrderMessageHandler(
    ILogger<OrderMessageHandler> logger,
    IOrderRepository orders,
    IBackgroundJobClient jobs)
{
    public async Task HandleAsync(OrderNotificationMessage message, CancellationToken ct)
    {
        using var scope = logger.BeginScope(new Dictionary<string, object>
        {
            ["MessageId"] = message.MessageId,
            ["OrderId"] = message.OrderId,
            ["CorrelationId"] = message.CorrelationId
        });

        var started = Stopwatch.GetTimestamp();
        logger.LogInformation("Order notification processing started");

        try
        {
            if (await orders.IsNotificationSentAsync(message.OrderId, ct))
            {
                logger.LogInformation("Duplicate message skipped");
                return;
            }

            var jobId = jobs.Enqueue<NotificationJob>(job =>
                job.SendAsync(message.OrderId, message.CorrelationId, CancellationToken.None));

            await orders.MarkNotificationScheduledAsync(message.OrderId, jobId, ct);
            logger.LogInformation("Notification job scheduled with JobId {JobId}", jobId);
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "Order notification processing failed");
            throw;
        }
        finally
        {
            logger.LogInformation("Order notification processing finished in {DurationMs} ms",
                Stopwatch.GetElapsedTime(started).TotalMilliseconds);
        }
    }
}

The throw statement is important. If the consumer swallows the exception, RabbitMQ may treat the message as successfully processed. The error must reach the layer responsible for retry or dead-letter handling.

2. Health checks and readiness

A liveness check answers whether the process is running. A readiness check answers whether the application can accept work together with its required dependencies. Separate checks for SQL Server, RabbitMQ, and Hangfire storage are usually more informative than one generic endpoint.

builder.Services.AddHealthChecks()
    .AddSqlServer(
        builder.Configuration.GetConnectionString("Default")!,
        name: "sql",
        tags: ["ready"])
    .AddRabbitMQ(
        sp => sp.GetRequiredService<IConnection>(),
        name: "rabbitmq",
        tags: ["ready"]);

app.MapHealthChecks("/health/live", new HealthCheckOptions
{
    Predicate = _ => false
});

app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
    Predicate = check => check.Tags.Contains("ready")
});

/health/live can show that the process is alive, while /health/ready can verify that SQL Server and RabbitMQ are usable. Container orchestrators can use these endpoints for different decisions.

Health endpoints do not have to be exposed to the public internet. Restrict them at the network layer or make them accessible only from an internal network. Health probes can also create a large volume of normal logs, so their logging categories should be filtered appropriately.

3. Metrics worth collecting

Evaluating an asynchronous system only by HTTP response time is misleading. A useful baseline includes the following metrics:

ComponentMetricMeaning
APIRequest count and error rateShows the health of the producer endpoint.
RabbitMQPublish, delivery, ack, nack, and queue depthShows message buildup and delivery problems.
ConsumerProcessing duration, retry count, and redelivery countShows message-processing quality.
HangfireEnqueued, processing, succeeded, failed, and job durationShows worker capacity and backlog.

Avoid high-cardinality metric labels. Creating a separate time series for every OrderId can quickly increase storage and query costs. Keep order identifiers in logs and use bounded labels such as operation name and result in metrics.

public static class AsyncMetrics
{
    public static readonly Meter Meter = new("Orders.AsyncProcessing");
    public static readonly Counter<long> MessagesPublished =
        Meter.CreateCounter<long>("orders.messages.published");
    public static readonly Counter<long> MessagesFailed =
        Meter.CreateCounter<long>("orders.messages.failed");
    public static readonly Histogram<double> ProcessingDuration =
        Meter.CreateHistogram<double>("orders.message.processing.duration", "ms");
}

OpenTelemetry can export these measurements to a collector or an application performance monitoring system. ASP.NET Core and HttpClient activities can also participate in the same trace when the required instrumentation is configured.

4. A testing strategy

One test type is not enough for asynchronous applications. A practical test pyramid includes four levels:

  1. Unit tests: Test handlers, retry decisions, idempotency checks, and job services with external dependencies replaced by test doubles.
  2. Contract tests: Validate message fields, required values, and compatibility between message versions.
  3. Integration tests: Exercise realistic behavior with SQL Server, RabbitMQ, or Hangfire storage.
  4. End-to-end tests: Validate the complete flow from the API through the consumer and job result in Docker.

Testing the consumer as a unit

[Fact]
public async Task Duplicate_message_does_not_enqueue_job()
{
    var message = new OrderNotificationMessage(
        Guid.NewGuid(), Guid.NewGuid(), "corr-123", DateTimeOffset.UtcNow);
    var repository = Substitute.For<IOrderRepository>();
    repository.IsNotificationSentAsync(message.OrderId, Arg.Any<CancellationToken>())
        .Returns(true);
    var jobs = Substitute.For<IBackgroundJobClient>();
    var handler = new OrderMessageHandler(
        NullLogger<OrderMessageHandler>.Instance, repository, jobs);

    await handler.HandleAsync(message, CancellationToken.None);

    jobs.DidNotReceiveWithAnyArgs().Enqueue<NotificationJob>(null!);
}

This test verifies the idempotency rule. Add separate tests that verify a new message creates one job, the repository receives the correct correlation ID, and exceptions are propagated so the retry pipeline can act.

Testing the API integration

Use WebApplicationFactory<Program> to test the real ASP.NET Core HTTP pipeline. In the test environment, use an isolated database and replace RabbitMQ with a fake publisher or a disposable container.

public class OrderApiTests(WebApplicationFactory<Program> factory)
    : IClassFixture<WebApplicationFactory<Program>>
{
    [Fact]
    public async Task Publish_endpoint_returns_correlation_id()
    {
        using var client = factory.CreateClient();
        using var request = new HttpRequestMessage(HttpMethod.Post, "/orders/42/notify");
        request.Headers.Add("X-Correlation-Id", "test-correlation");

        var response = await client.SendAsync(request);

        response.EnsureSuccessStatusCode();
        Assert.Equal("test-correlation",
            response.Headers.GetValues("X-Correlation-Id").Single());
    }
}

For real RabbitMQ integration tests, generate unique exchange and queue names. Remove them after the test. Connecting tests to production queue names can cause real consumers to process test messages accidentally.

5. End-to-end validation with Docker

Run the API, worker, RabbitMQ, and SQL Server in the same Compose network. Do not rely only on startup order. Use health checks and retry-aware connection logic because a container can be started before its service is ready to accept connections.

services:
  api:
    build: ./src/Orders.Api
    environment:
      RabbitMq__Host: rabbitmq
      ConnectionStrings__Default: Server=sql;Database=Orders;User Id=sa;Password=Your_password123;TrustServerCertificate=True
    depends_on:
      rabbitmq:
        condition: service_healthy
      sql:
        condition: service_healthy

  worker:
    build: ./src/Orders.Worker
    environment:
      RabbitMq__Host: rabbitmq
      ConnectionStrings__Hangfire: Server=sql;Database=Hangfire;User Id=sa;Password=Your_password123;TrustServerCertificate=True

  rabbitmq:
    image: rabbitmq:management
    healthcheck:
      test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
      interval: 10s
      timeout: 5s
      retries: 10

  sql:
    image: mcr.microsoft.com/mssql/server:2022-latest
    environment:
      ACCEPT_EULA: Y
      MSSQL_SA_PASSWORD: Your_password123
      MSSQL_PID: Developer

Do not use the sample password in production. Supply secrets through environment secrets, container secrets, or a centralized secret-management system. Do not expose RabbitMQ's default user to an external network, and protect its management interface with authentication and network controls.

6. Performance, security, and scaling

Performance

  • Choose the consumer prefetch value by measuring processing time, throughput, and memory usage.
  • Do not start unlimited parallel work inside one consumer.
  • Keep message payloads small. Store large data in the database and send only an identifier in the message.
  • Pass IDs rather than entities or large collections to Hangfire jobs.
  • Define alert thresholds for queue depth, processing latency, and failed jobs.

Security

  • Never store RabbitMQ credentials in source code.
  • Validate message payloads and avoid accepting unexpected types during deserialization.
  • Restrict Dashboard access with roles or network policies.
  • Mask personal data in logs.
  • Apply least privilege to producer and consumer service accounts.

Scaling

Increasing the number of RabbitMQ consumers can improve throughput, but database and external-service capacity may become the real bottleneck. When increasing Hangfire workers, verify that concurrent execution of the same job cannot violate business rules. If necessary, use a distributed lock, a concurrency limit, or an application-level idempotency key.

7. Common mistakes

  • Keeping the correlation ID only in the HTTP header: Consumer and Hangfire stages cannot be correlated. Copy it into the message and job arguments.
  • Acknowledging too early: If the message is acknowledged before processing finishes, a process failure can cause data loss.
  • Logging an exception without rethrowing it: The retry mechanism may never run.
  • Combining liveness and readiness into one check: The deployment system cannot distinguish a live process from a process ready to accept work.
  • Using real queue names in tests: Parallel tests can mix messages and state.
  • Passing large objects to a job: Hangfire storage grows unnecessarily and serialization can break after a model change.
  • Assuming a successful HTTP response means completion: Return a correlation ID and an operation status that users or clients can track.

8. Short practice exercise

Make the existing order-notification flow production-ready:

  1. Add CorrelationId to logs from the API, producer, consumer, and Hangfire job.
  2. Create /health/live and /health/ready endpoints.
  3. Add at least three metrics for processing duration, failure count, and retry count.
  4. Verify with a unit test that a duplicate message does not create a second job.
  5. Use WebApplicationFactory to test that the correlation ID response header is preserved.
  6. Start the Docker Compose environment and inspect queue depth and consumer capacity in the RabbitMQ management interface.
  7. Stop RabbitMQ temporarily and observe producer and consumer logs. Record the expected reconnect, retry, or redelivery behavior after the broker becomes available again.

Conclusion

A production-ready asynchronous system is not complete merely because RabbitMQ messages and Hangfire jobs can execute. The team must be able to understand the current state of work, recover safely after failures, and measure the boundaries of system capacity.

In this lesson, structured logging made events searchable, correlation IDs connected the complete workflow, and health checks and metrics improved operational visibility. Unit, integration, and end-to-end tests provided confidence in reliability. Finally, we evaluated Docker deployment, security, performance, and scaling decisions.

The API, RabbitMQ producer-consumer pipeline, and Hangfire workflow built throughout this course can now become an asynchronous architecture that is observable, testable, and manageable in production.

Sources