LESSON 9 OF 14

9. Idempotency, Duplicate Messages, and Reliable Processing Design

Learn why duplicate deliveries occur in RabbitMQ and Hangfire, and how message IDs, idempotency keys, database constraints, and transactions make processing safe.

75 dk 46

Introduction

In asynchronous systems, it is unsafe to assume that a message will be consumed only once. With manual acknowledgements, RabbitMQ can requeue a message when a consumer connection is lost before the acknowledgement reaches the broker. A consumer may finish its database work and then stop before sending the acknowledgement, causing RabbitMQ to deliver the same message again. Hangfire can also execute a job again when an exception occurs or a process is interrupted before the job is completed.

This behavior is not a defect. It is a normal consequence of an at-least-once processing model. Application code must therefore tolerate duplicate messages and repeated job execution. In this lesson, we will make order notifications, report generation, and email delivery safer through idempotent processing.

What Is Idempotency?

Idempotency means that executing the same command or message multiple times produces the same observable result as executing it once. If an OrderPaid message is delivered twice, the customer should not receive two payment receipts. If a report-generation message is repeated, the system should maintain one logical report operation rather than creating unrelated duplicate reports.

Idempotency is not the same as exactly-once delivery. Instead of relying on the broker or job framework to deliver a message only once, the application makes repeated delivery safe. This is especially important when a workflow crosses multiple systems such as a database, an email provider, or an external HTTP API.

How can a duplicate message occur?

  1. The consumer receives a message.
  2. It writes a database record or calls an external service.
  3. The operation completes, but the process stops before the acknowledgement is sent.
  4. RabbitMQ sees an unacknowledged delivery and delivers the message again.

The redelivered property is a useful hint, but it is not a complete deduplication mechanism. The first delivery may have completed part of its work before the process failed, and the application cannot safely determine the final state by looking only at that flag.

Message IDs and Idempotency Keys

Every business message should have a stable identifier. RabbitMQ message properties include MessageId, and the message body can also contain a message ID. When a producer may recreate an event during a retry, a separate business-level IdempotencyKey is often more appropriate.

public sealed record OrderPaidMessage(
    Guid MessageId,
    Guid OrderId,
    string IdempotencyKey,
    DateTimeOffset OccurredAt);

MessageId identifies one published event. IdempotencyKey identifies the intended business result. For example, a producer can create a new transport message during recovery while preserving the same idempotency key for the same order. The right choice depends on the business operation.

Using an Inbox Table for Deduplication

A consumer can persist successfully processed message identifiers in an inbox or processed-message table. This table provides durable evidence that a particular message or business operation has already been handled.

public sealed class ProcessedMessage
{
    public long Id { get; set; }
    public string MessageId { get; set; } = null!;
    public string MessageType { get; set; } = null!;
    public DateTimeOffset ProcessedAt { get; set; }
}

public sealed class AppDbContext : DbContext
{
    public DbSet<ProcessedMessage> ProcessedMessages => Set<ProcessedMessage>();
    public DbSet<Notification> Notifications => Set<Notification>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ProcessedMessage>()
            .HasIndex(x => new { x.MessageType, x.MessageId })
            .IsUnique();

        modelBuilder.Entity<Notification>()
            .HasIndex(x => new { x.OrderId, x.Kind })
            .IsUnique();
    }
}

The unique index is an important final safety layer. If two consumers receive the same message concurrently, both may query the database before either insert is visible. An application-level AnyAsync check alone does not prevent this race. The database unique constraint makes the final decision atomically.

Transaction Boundaries

The inbox record and the business result should be written in the same database transaction. This prevents the system from recording a message as processed while failing to create the corresponding business record.

public sealed class OrderPaidHandler(AppDbContext db)
{
    public async Task HandleAsync(
        OrderPaidMessage message,
        CancellationToken cancellationToken)
    {
        await using var transaction =
            await db.Database.BeginTransactionAsync(cancellationToken);

        var alreadyProcessed = await db.ProcessedMessages.AnyAsync(
            x => x.MessageType == nameof(OrderPaidMessage) &&
                 x.MessageId == message.MessageId.ToString(),
            cancellationToken);

        if (alreadyProcessed)
        {
            await transaction.CommitAsync(cancellationToken);
            return;
        }

        db.Notifications.Add(new Notification
        {
            OrderId = message.OrderId,
            Kind = "PaymentReceipt",
            Status = "Pending",
            CreatedAt = DateTimeOffset.UtcNow
        });

        db.ProcessedMessages.Add(new ProcessedMessage
        {
            MessageId = message.MessageId.ToString(),
            MessageType = nameof(OrderPaidMessage),
            ProcessedAt = DateTimeOffset.UtcNow
        });

        await db.SaveChangesAsync(cancellationToken);
        await transaction.CommitAsync(cancellationToken);
    }
}

The notification and processed-message records are committed together. On a duplicate delivery, the handler returns without creating another notification. If two deliveries are processed concurrently, a unique-index violation may occur. That exception can be treated as evidence that another worker completed the same operation, but the code should identify the specific duplicate-key violation rather than swallowing every database exception.

The optimistic insert approach

Another option is to insert the inbox record first and call SaveChangesAsync. If the insert succeeds, the worker has claimed the operation. If a unique constraint exception occurs, another worker has already claimed the same key.

try
{
    db.ProcessedMessages.Add(new ProcessedMessage
    {
        MessageId = message.MessageId.ToString(),
        MessageType = nameof(OrderPaidMessage),
        ProcessedAt = DateTimeOffset.UtcNow
    });

    await db.SaveChangesAsync(cancellationToken);
}
catch (DbUpdateException exception) when (IsDuplicateKey(exception))
{
    // Duplicate delivery: acknowledge it safely.
    return;
}

The inbox insert and business operation should still be protected by one transaction. If the business operation fails, the transaction must roll back so that a later delivery can retry the work.

When to Acknowledge a RabbitMQ Message

A consumer should not acknowledge a message before the database operation has succeeded. For a failed operation, the consumer should either requeue it for a controlled retry or route it to the retry and dead-letter flow introduced in the previous lesson.

consumer.ReceivedAsync += async (_, eventArgs) =>
{
    var body = eventArgs.Body.ToArray();
    var message = JsonSerializer.Deserialize<OrderPaidMessage>(body)!;

    try
    {
        await using var scope = serviceScopeFactory.CreateAsyncScope();
        var handler = scope.ServiceProvider
            .GetRequiredService<OrderPaidHandler>();

        await handler.HandleAsync(message, stoppingToken);
        await channel.BasicAckAsync(eventArgs.DeliveryTag, multiple: false);
    }
    catch (DuplicateKeyException)
    {
        await channel.BasicAckAsync(eventArgs.DeliveryTag, multiple: false);
    }
    catch (Exception)
    {
        await channel.BasicNackAsync(
            eventArgs.DeliveryTag,
            multiple: false,
            requeue: false);
    }
};

The requeue: false decision must match the retry and dead-letter topology. A temporary database outage may deserve another attempt, while invalid JSON or an unknown message contract should normally go to a dead-letter queue. Uncontrolled immediate requeue can create a hot redelivery loop.

Safe Email, Report, and Notification Processing

A database transaction cannot atomically include an SMTP call or an external HTTP request. If the application sends an email inside a transaction and the database commit later fails, the recipient may receive an email for a transaction that is not visible in the database. The reverse problem is also possible: the database commits successfully while the email provider is unavailable.

A practical design is to record the delivery intent in the database and process that record separately. This is commonly implemented with an outbox or delivery table.

public sealed class Notification
{
    public long Id { get; set; }
    public Guid OrderId { get; set; }
    public string Kind { get; set; } = null!;
    public string Status { get; set; } = "Pending";
    public int AttemptCount { get; set; }
    public string? ProviderReference { get; set; }
    public DateTimeOffset CreatedAt { get; set; }
    public DateTimeOffset? SentAt { get; set; }
}

A notification worker selects pending records, claims them briefly, calls the external provider, and stores the resulting status. If the provider supports an idempotency key, send the notification ID or order key with the request. If it does not, carefully record provider responses and local state transitions so that retries do not create uncontrolled duplicate effects.

Idempotent Hangfire Jobs

Hangfire stores job arguments and can retry failed jobs. Therefore, pass a small identifier to the job rather than a large entity object. The job can load the current state when it starts.

public sealed class ReportJob(AppDbContext db, IReportGenerator generator)
{
    public async Task GenerateAsync(
        Guid reportId,
        CancellationToken cancellationToken)
    {
        var report = await db.Reports.SingleAsync(
            x => x.Id == reportId,
            cancellationToken);

        if (report.Status == "Completed")
        {
            return;
        }

        report.Status = "Generating";
        await db.SaveChangesAsync(cancellationToken);

        var fileReference = await generator.GenerateAsync(
            reportId,
            cancellationToken);

        report.FileReference = fileReference;
        report.Status = "Completed";
        report.CompletedAt = DateTimeOffset.UtcNow;
        await db.SaveChangesAsync(cancellationToken);
    }
}

However, a simple Status == Completed check is not always enough. If two Hangfire workers start simultaneously, both can observe the Pending state. Use a row-version column, an atomic update, a unique constraint, or a suitable distributed-lock strategy to claim the work. For file generation, deriving the target file name from the idempotency key also reduces duplicate artifacts.

Common Mistakes

  • Relying only on the redelivered flag: It is a delivery hint, not durable deduplication.
  • Using AnyAsync without a unique index: Concurrent consumers can still create duplicate rows.
  • Acknowledging immediately after receipt: A process failure before business completion can lose the message.
  • Sending email inside a database transaction: External calls are not automatically part of the database transaction.
  • Retrying forever: Poison messages can create an endless redelivery loop. Define attempt limits and dead-letter behavior.
  • Passing large entities to Hangfire: Job arguments are serialized; passing identifiers keeps jobs smaller and easier to re-run.
  • Treating every duplicate as a failure: A previously completed message can usually be acknowledged safely without repeating the side effect.

Practice Exercise

  1. Create a ProcessedMessages table with a unique index on MessageType, MessageId.
  2. Publish the same OrderPaidMessage JSON payload to RabbitMQ twice.
  3. Verify that the first delivery creates one notification and one inbox record.
  4. Verify that the second delivery does not increase the notification count.
  5. Simulate a consumer shutdown after the database commit but before the acknowledgement.
  6. Observe the redelivery and confirm that idempotency prevents a second notification.
  7. Enqueue the same report job twice and verify that the system does not create two completed logical reports.

Conclusion

Reliable asynchronous design is not based on eliminating duplicate delivery; it is based on making duplicate delivery safe. RabbitMQ acknowledgements and retry policies reduce message loss, while application-level idempotency prevents the same business operation from being performed twice.

Use a message ID or business idempotency key together with database unique constraints and carefully defined transaction boundaries. For email, reports, and notifications, an outbox or delivery-table design is usually safer than performing external side effects directly inside the database transaction. In the next lesson, we will combine these principles with correlation IDs, observability, and operational monitoring to build a more production-ready asynchronous system.

Sources