Skip to content

Transactional Inbox Pattern

What Problem Does It Solve?

The Transactional Inbox pattern makes a message consumer safe when the same message can be delivered more than once. It records a durable receipt for a message in the consumer's own database transaction, alongside the consumer's business update.

Message brokers such as Azure Service Bus commonly provide at-least-once delivery. With the default peek-lock receive mode, Service Bus retains a message until the consumer completes it. If the process crashes, loses its lock, times out while completing, or experiences a transient network fault after doing useful work, Service Bus can redeliver the message. This is the correct trade-off for reliability: a duplicate is safer than a lost business operation. Azure Service Bus delivery guidance

Without a transactional inbox, a consumer can reserve stock, charge a card, send an email, or decrement a balance twice. The inbox makes the receiver's database update and the assertion "this message has been processed" one atomic decision:

  1. Start a transaction in the consumer's data store.
  2. Insert the message identity into an inbox or processed-messages table.
  3. Apply the consumer's business change.
  4. Commit the transaction.
  5. Only then complete the broker message.

If the same message arrives again, the unique inbox record already exists. The consumer recognizes a duplicate, does not repeat the business change, and completes the message.


Transactional Inbox, Idempotency, and Exactly-Once

The Transactional Inbox pattern is a concrete implementation of the broader Idempotent Consumer pattern. "Idempotent" means processing the same logical message repeatedly has the same observable outcome as processing it once.

It does not deliver global exactly-once semantics. It produces an important, realistic guarantee:

At-least-once message delivery plus an atomic inbox record and local business update results in effectively-once application of that message to the consumer's own database.

It cannot atomically include an unrelated external system. For example, recording an invoice in the consumer's database and calling a card processor are two resource managers. If the consumer must emit another event after its local update, combine its inbox with the Transactional Outbox pattern: the local transaction inserts the inbox record, applies business state, and writes an outgoing event; a relay publishes that event later.

flowchart LR
    SB[Azure Service Bus] --> Consumer[Consumer]
    Consumer --> TX{Local database transaction}
    TX --> Inbox[(Inbox / ProcessedMessages)]
    TX --> State[(Consumer business state)]
    TX --> Outbox[(Optional outbox)]
    TX --> Commit[Commit]
    Commit --> Complete[Complete Service Bus message]
    Outbox --> Relay[Outbox relay]
    Relay --> Next[Next broker destination]

Why Redelivery Happens

An inbox is not evidence that a broker is unreliable; it is a response to normal distributed-systems failure modes.

Situation What can happen Inbox response
Worker crashes after local commit but before completion The broker redelivers the message. Existing inbox record prevents repeated local work.
Completion reaches Service Bus but acknowledgement is lost The worker may retry or the broker may redeliver. Existing inbox record prevents repeated local work.
Processing runs longer than the message lock The lock expires and another worker receives the message. Transactional uniqueness allows only one local effect.
Host restarts with in-flight work Locked messages are made available again. Redelivered message is safely recognized.
Producer retries an uncertain send The broker might receive multiple copies. The consumer remains protected, even outside the broker detection window.

Service Bus duplicate detection suppresses repeated sends with the same MessageId during a configured history window. It is useful, but it does not remove the need for a receiver-side inbox: it cannot prevent redelivery after a receiver fails before settlement, and its window is finite. Duplicate detection in Azure Service Bus


Basic Message Flow

sequenceDiagram
    participant B as Azure Service Bus
    participant C as Inventory consumer
    participant D as Inventory database

    B->>C: Deliver OrderCreated (MessageId: E123)
    C->>D: Begin transaction
    C->>D: Insert InboxMessage(E123)
    C->>D: Reserve stock
    C->>D: Commit transaction
    Note over C,B: Consumer crashes before Complete
    B->>C: Redeliver E123
    C->>D: Begin transaction
    C->>D: Insert InboxMessage(E123) -> unique-key conflict
    C->>D: Roll back/no business change
    C->>B: Complete E123

The duplicate path is a successful outcome, not an error that should fill alerting dashboards. Record it as a metric or low-severity trace so that an unusual rate of duplicates can be investigated.


Inbox Schema Design

The inbox belongs to the consumer. Every independently deployed subscriber needs its own inbox state because each subscriber decides whether it has applied a message.

CREATE TABLE dbo.InboxMessages
(
    ConsumerName nvarchar(128) NOT NULL,
    MessageId nvarchar(128) NOT NULL,
    ReceivedUtc datetime2 NOT NULL,
    MessageType nvarchar(200) NOT NULL,
    CorrelationId nvarchar(128) NULL,
    PayloadHash varbinary(32) NULL,
    ProcessedUtc datetime2 NOT NULL,
    PRIMARY KEY (ConsumerName, MessageId)
);
Field Why it exists
ConsumerName Enables one database to host several consumers without accidental cross-consumer deduplication.
MessageId The stable logical message identifier; use the producer-set Service Bus MessageId, not the broker delivery count or lock token.
ReceivedUtc and ProcessedUtc Support retention, lag diagnostics, and audit.
MessageType and CorrelationId Make troubleshooting and trace correlation practical.
PayloadHash Detects a producer defect where the same ID is reused with different contents.

The composite primary key is the concurrency mechanism. If two workers receive copies of the same message, only one transaction can insert (ConsumerName, MessageId). The other must treat a unique-key conflict as a duplicate only after verifying that it refers to the same logical event.

Do not use Service Bus DeliveryCount, lock token, enqueue sequence number, or current timestamp as the deduplication key: they are delivery-specific, not message-specific. Producers must create stable and unique message IDs.


.NET / EF Core Implementation

The following consumer uses Azure.Messaging.ServiceBus and EF Core. It starts a transaction, attempts to insert the inbox marker, applies the inventory change, commits, and then completes the message. The exact way an application identifies a SQL unique-constraint violation depends on the provider; isolate that provider-specific logic behind a method rather than treating every database failure as a duplicate.

using Azure.Messaging.ServiceBus;
using Microsoft.EntityFrameworkCore;

public sealed class InventoryMessageHandler(InventoryDbContext dbContext)
{
    public async Task HandleAsync(
        ServiceBusReceivedMessage message,
        CancellationToken cancellationToken)
    {
        var orderCreated = message.Body.ToObjectFromJson<OrderCreatedV1>()
            ?? throw new InvalidOperationException("Invalid OrderCreated message.");

        await using var transaction = await dbContext.Database
            .BeginTransactionAsync(cancellationToken);

        try
        {
            dbContext.InboxMessages.Add(new InboxMessage
            {
                ConsumerName = "inventory-order-created-v1",
                MessageId = message.MessageId,
                MessageType = message.Subject ?? "orders.created.v1",
                CorrelationId = message.CorrelationId,
                ReceivedUtc = DateTimeOffset.UtcNow,
                ProcessedUtc = DateTimeOffset.UtcNow
            });

            var reservation = await dbContext.Reservations.SingleOrDefaultAsync(
                item => item.OrderId == orderCreated.OrderId,
                cancellationToken);

            if (reservation is null)
            {
                dbContext.Reservations.Add(Reservation.Create(
                    orderCreated.OrderId, orderCreated.Lines));
            }

            await dbContext.SaveChangesAsync(cancellationToken);
            await transaction.CommitAsync(cancellationToken);
        }
        catch (DbUpdateException exception) when (IsInboxDuplicate(exception))
        {
            await transaction.RollbackAsync(cancellationToken);
        }
    }

    private static bool IsInboxDuplicate(DbUpdateException exception)
    {
        return false;
    }
}

public sealed class InboxMessage
{
    public string ConsumerName { get; init; } = null!;
    public string MessageId { get; init; } = null!;
    public string MessageType { get; init; } = null!;
    public string? CorrelationId { get; init; }
    public DateTimeOffset ReceivedUtc { get; init; }
    public DateTimeOffset ProcessedUtc { get; init; }
}

The hosting code completes the Service Bus message only after HandleAsync returns successfully:

processor.ProcessMessageAsync += async args =>
{
    await handler.HandleAsync(args.Message, args.CancellationToken);
    await args.CompleteMessageAsync(args.Message, args.CancellationToken);
};

If processing fails for a transient reason, do not complete the message. Let the lock expire or explicitly abandon it so Service Bus can retry. For a malformed message or a permanent business failure, dead-letter it with a reason and diagnostic context. Do not dead-letter simply because the inbox says the message is a duplicate; completion is correct in that case.

The sample intentionally shows a placeholder IsInboxDuplicate because silently classifying arbitrary DbUpdateException values as duplicates would hide outages, deadlocks, schema faults, and constraint violations in the business update. For SQL Server, detect the specific unique-index violation for the inbox key; then, where messages are security- or money-sensitive, verify a stored payload hash matches before accepting it as the same logical message.


Azure Functions Considerations

An Azure Function with a Service Bus trigger can implement the same pattern. The function must use the stable message ID and write the inbox marker and business change in one transaction. The Functions runtime handles receive and settlement behaviour according to trigger configuration; the application remains responsible for idempotent local processing.

Use these practical rules:

  • Prefer peek lock for business messages where loss is unacceptable. ReceiveAndDelete trades duplicates for message loss and is rarely appropriate for important work.
  • Keep local transactions short. Perform slow external calls outside the database transaction, or model them as their own command/event workflow.
  • Configure lock renewal only for work that is legitimately longer than the lock duration; first reduce the work or split it if possible.
  • Avoid excessive prefetch relative to concurrency and processing time, because messages can lose their locks while waiting in memory.
  • Scale out safely only when the inbox's unique constraint and business invariants support concurrent processing.
  • Use Application Insights to record message ID, correlation ID, entity name, delivery count, and the duplicate/processed outcome.

For workloads that must update several consumer documents atomically in Azure Cosmos DB, store the inbox record and business documents under the same logical partition key, then use a TransactionalBatch. The batch succeeds once or returns a conflict when the inbox document already exists. Microsoft's Idempotent Consumer pattern includes this Cosmos DB approach.

flowchart TD
    Message[Service Bus message] --> Receive[Function or worker receives in peek lock]
    Receive --> Batch[Database transaction or Cosmos TransactionalBatch]
    Batch --> Check{Inbox ID already exists?}
    Check -->|No| Apply[Write inbox marker + business state]
    Apply --> Commit[Commit]
    Check -->|Yes| Duplicate[Skip business state]
    Commit --> Settle[Complete message]
    Duplicate --> Settle
    Batch -->|Transient failure| Retry[Abandon / retry]
    Batch -->|Permanent failure| DLQ[Dead-letter with reason]

External Side Effects

The inbox makes writes to the consumer's own transactional store safe. It does not make an arbitrary HTTP call, email, file operation, or payment request participate in that same transaction.

Avoid this unsafe sequence:

insert inbox marker
call external payment provider
commit local database transaction

If the provider succeeds and the local transaction rolls back, a retry repeats the charge. Instead, make the local transaction create a durable command or outbox event for the external action, then have a dedicated sender invoke the provider using an idempotency key such as the inbox event ID. Persist the provider's response and design a reconciliation process for uncertain outcomes.

flowchart LR
    Input[Incoming event] --> InboxTx[Inbox + local state + outbox transaction]
    InboxTx --> Outbox[(Outbox)]
    Outbox --> Sender[External-effect sender]
    Sender -->|Idempotency key| Provider[Payment/email/provider API]
    Sender --> Result[(Persist outcome)]

This composition is often called inbox-outbox or consume-transform-publish. It makes the input safe to replay and makes the next message reliable, but the external provider remains a separate consistency boundary.


Ordering, Retention, and Replay

Ordering

An inbox answers “have I already processed this message?” not “did I process all related messages in the correct order?” If order matters per account, order, or aggregate:

  • Include an aggregate ID and an application-level sequence number in the event.
  • Use Service Bus sessions with SessionId equal to that aggregate ID where FIFO processing within the aggregate is required.
  • Define how the consumer treats a sequence gap: wait, retry, query the source, or compensate.
  • Do not require global ordering unless the domain truly demands it; it severely limits throughput and availability.

Retention

Keep inbox records longer than the maximum credible redelivery, replay, disaster recovery, and audit period. There is no universally correct value. A few days may be adequate for ephemeral telemetry; financial or regulated workflows can require months or longer. Archive old records before deleting them if support investigations depend on them.

Deleting an inbox record reopens the possibility that an old replay is treated as new. If that is intentional, ensure the business operation itself is additionally idempotent through a unique business key or version check.

Replay

Replays should be intentional and observable. Define whether a replay uses the same event ID (normal for a safe reprocessing test) or a new corrective event ID (normal for a new business action). Never re-run production messages blindly across an inbox retention boundary.


Advantages and Disadvantages

Advantages

  • Prevents duplicate message deliveries from repeating local business effects.
  • Fits Azure Service Bus peek-lock delivery and normal process-restart behaviour.
  • Uses one local transaction rather than a distributed transaction with the broker.
  • Provides an auditable record of what each consumer processed.
  • Composes cleanly with the Transactional Outbox pattern for reliable downstream publication.

Disadvantages and trade-offs

  • Requires a stable producer-controlled message ID and a durable, correctly indexed inbox store.
  • Adds storage, cleanup, migration, and operational monitoring responsibilities.
  • Provides eventual consistency; a sender cannot assume all consumers completed immediately.
  • Does not make external side effects atomic without a provider idempotency contract or an additional workflow.
  • Does not solve ordering by itself.

Transactional Inbox Compared with Alternatives

Approach What it protects Limitation
Transactional Inbox Consumer's local database state against duplicate deliveries. Requires consumer-owned durable storage and idempotent external effects.
Broker duplicate detection Duplicate sends to a Service Bus entity within its configured window. Does not prevent receiver redelivery and has a finite window.
Idempotent domain write A naturally unique business update, such as one order record per OrderId. May be insufficient when one message changes several tables or causes side effects.
Transactional Outbox Reliable publication from a producer after a local state change. Protects the sending side; consumers still need an inbox or idempotency design.
Receive and delete Lower receive/settlement overhead. Risks message loss if the consumer fails after receipt.
Distributed transaction Atomic coordination across multiple transactional participants. Adds coupling and is generally unsuitable for broker-plus-cloud-service workflows.

Interview-Ready Summary

The Transactional Inbox pattern protects a message consumer from at-least-once delivery. The consumer stores the message ID in an inbox table in the same transaction as its business update, then completes the broker message only after the transaction commits. If Service Bus redelivers the message because a worker crashed or settlement was uncertain, the unique inbox record identifies the duplicate and prevents the business update from running again.

It provides effectively-once application to the consumer's own database, not universal exactly-once semantics. Use it with Service Bus peek lock, stable MessageId values, explicit dead-letter handling, and idempotent external providers. Pair it with a Transactional Outbox when the consumer must publish a new event reliably.


Further Reading