Table of Contents

Inbox Deduplication

The inbox pattern prevents duplicate message processing when the broker redelivers a message — for example after a consumer crash, network timeout, or explicit NACK. BareWire's inbox is built into the TransactionalOutboxMiddleware and shares the same database and transaction as the outbox.

How It Works

  1. A message arrives on a receive endpoint
  2. The middleware checks whether (MessageId, ConsumerType) already exists in the inbox table
  3. If the entry exists and is marked as processed — the message is skipped (duplicate)
  4. If no entry exists — a lock row is inserted with an expiry time
  5. The consumer processes the message inside a transaction — a TransactionScope on providers with ambient-transaction support (PostgreSQL, SQL Server), or an explicit local transaction on SQLite (see Transactional Outbox)
  6. On success, the entry is marked as processed — permanently preventing reprocessing

Composite Key

The inbox key is (MessageId, ConsumerType), where ConsumerType is the receive endpoint name (the BW-MessageType header, then a type name, are fallbacks used only when no endpoint name is available). This means:

  • The same message is processed once per endpoint: deduplication covers the whole delivery on that endpoint, not each consumer separately
  • The same message delivered to different endpoints (e.g. an email queue and an audit queue both bound to PaymentReceived) is processed independently on each of them
  • The entry is marked processed only after every consumer of the delivery has succeeded. When one consumer succeeds and another throws, nothing is marked processed, so a redelivered copy runs every consumer of the endpoint again, including the ones that already succeeded. Their transactional work rolls back together, but non-transactional side effects of each consumer must be idempotent

Two-Phase Lock

  1. Lock — on first receipt the inbox creates an entry with ExpiresAt = now + InboxLockTimeout. If an entry already exists and has not expired, the message is rejected (on endpoints that use delayed redelivery, the copy is deferred instead).
  2. Mark processed — after the consumer completes successfully, the middleware sets ProcessedAt. Entries with ProcessedAt != null never allow reprocessing, even after ExpiresAt has elapsed.

If a consumer crashes before marking processed and the lock expires, the broker can redeliver the message and a new lock will be acquired — providing at-least-once semantics with deduplication.

Configuration

The inbox is configured through the same AddBareWireOutbox call as the outbox:

builder.Services.AddBareWireOutbox(
    configureDbContext: options => options.UseNpgsql(connectionString),
    configureOutbox: outbox =>
    {
        outbox.InboxLockTimeout = TimeSpan.FromSeconds(30);   // default: 30s
        outbox.InboxRetention = TimeSpan.FromDays(7);         // default: 7 days
        outbox.CleanupInterval = TimeSpan.FromHours(1);       // default: 1 hour
    });
  • InboxLockTimeout — how long a processing lock is held before it expires. Set this higher than your longest expected consumer execution time.
  • InboxRetention — how long processed entries are kept before the cleanup service purges them. Must be longer than the maximum broker redelivery window.
  • CleanupInterval — how often the background service removes old inbox entries.

Delayed redelivery intervals

InboxLockTimeout must still exceed the longest consumer run time, including in-process retries; otherwise the lock expires during processing and the message may be processed twice. When an endpoint uses UseDelayedRedelivery, the inbox settings also constrain its schedule: every delayed redelivery level must be at least InboxLockTimeout + max(5 s, 10 %) (35 s with the defaults), and the schedule total must stay below InboxRetention. A violation fails bus start with BareWireConfigurationException; a bus without such an endpoint starts normally. Keep the schedule well below InboxRetention, so that a returning copy, any queue backlog and its processing finish before the inbox row is purged; otherwise a duplicate passes deduplication. InboxRetention must exceed InboxLockTimeout plus the margin, otherwise no delayed redelivery schedule is possible. A shorter schedule requires lowering InboxLockTimeout.

See also: Delayed Redelivery - schedule, guarantees and operations.

Preserving MessageId on Re-Publish

For inbox deduplication to work across re-publishes of the same logical message, pass the original MessageId as a header:

var headers = new Dictionary<string, string>
{
    ["message-id"] = originalMessageId.ToString()
};
await bus.PublishAsync(message, headers, ct);

Without this, each PublishAsync call generates a new MessageId and the inbox treats the message as new.

Multiple Consumers, Same Message

A common pattern is to have multiple consumers react to the same event — each with its own inbox entry:

// Both consumers receive PaymentReceived independently
rmq.ReceiveEndpoint("email-notifications", e =>
{
    e.Consumer<EmailNotificationConsumer, PaymentReceived>();
});

rmq.ReceiveEndpoint("audit-log", e =>
{
    e.Consumer<AuditLogConsumer, PaymentReceived>();
});

If the broker redelivers a message, each consumer's inbox entry is checked independently. EmailNotificationConsumer might have already processed it while AuditLogConsumer has not — the inbox handles both correctly.

Duplicate Metric

Every message the inbox skips as a duplicate — because the same (MessageId, ConsumerType) pair is already locked or already processed — increments one counter on the BareWire meter:

Instrument Type Unit Tags Meaning
barewire.inbox.duplicates counter {message} consumer_type Messages skipped by the inbox as duplicates.
  • consumer_type is the receive endpoint name. When a message carries no endpoint name the tag is unknown — a value taken from message headers is never used as a tag, so a producer cannot inflate the metric's cardinality. The message id is never recorded.
  • The counter is created when an IMeterFactory is registered in DI — the .NET generic host registers one by default. Without it, deduplication works exactly the same and only the metric is skipped.
  • A steady non-zero rate is expected wherever duplicates are part of the delivery model (for example outbox retries after a transport rejection, or a fan-out where one subscriber rejected the message); compare it with barewire.outbox.rows.retried to see how many retries turned into duplicates.

Inspecting the Inbox

The InboxDeduplication sample exposes an endpoint to inspect inbox state:

GET /inbox   — returns inbox entries with (MessageId, ConsumerType, ProcessedAt)

See: samples/BareWire.Samples.InboxDeduplication/