For the complete documentation index, see llms.txt. This page is also available as Markdown.

MongoDb Outbox

Reference · Applies to Brighter V10

MongoDB Outbox Usage

The MongoDB Outbox allows integration between MongoDB and Brighter's outbox support. The configuration is described in Command Processor Configuration Reference.

To support transactional messaging when using MongoDB requires us to use MongoDB's support for ACID transactions. You should understand best practices for using transactions with MongoDB, including replica set requirements for multi-document transactions.

For this we will need the Outbox package for MongoDB:

  • Paramore.Brighter.Outbox.MongoDb

Paramore.Brighter.Outbox.MongoDb will pull in another package:

  • Paramore.Brighter.MongoDb

MongoDB Outbox NuGet Packages

To use the MongoDB Outbox, you need to install the following packages from NuGet:

dotnet add package Paramore.Brighter.Outbox.MongoDb
dotnet add package Paramore.Brighter.MongoDb

MongoDB Outbox Collection Management

The MongoDB Outbox supports different strategies for collection management through the MakeCollection property:

  • OnResolvingACollection.Assume: Assumes the collection already exists (default behavior)

  • OnResolvingACollection.Validate: Validates that the collection exists, throws an exception if it doesn't

  • OnResolvingACollection.CreateIfNotExists: Creates the collection if it doesn't exist

Note: You are responsible for creating and maintaining the collection if you choose to manage it manually. This includes tasks such as adding indexes to optimize query performance and configuring Time-To-Live (TTL) indexes for automatic message cleanup.

MongoDB Outbox Options

MongoDbConfiguration is constructed with a client and a database name, and carries the rest as properties. The MongoDB Inbox and the MongoDB distributed lock take the same type, so one instance can configure all three.

Option
Type
Default
Description

Client

IMongoClient

none

Supplies the MongoDB driver client used for every collection Brighter opens.

TimeProvider

TimeProvider

TimeProvider.System

Supplies the clock used for message timestamps and time-to-live expiry.

DatabaseSettings

MongoDatabaseSettings?

null

Sets the database-level settings, such as read preference and write concern.

InstrumentationOptions

InstrumentationOptions

All

Sets how much telemetry detail the Outbox emits.

Outbox

MongoDbCollectionConfiguration?

null

Configures the collection this Outbox writes messages to.

Inbox

MongoDbCollectionConfiguration?

null

Configures the collection the MongoDB Inbox writes to.

Locking

MongoDbCollectionConfiguration?

null

Configures the collection the MongoDB distributed lock writes its lock documents to.

databaseName is a constructor parameter, not a property you can set. It surfaces as the get-only DatabaseName, and there is no default: a MongoDbConfiguration cannot be constructed without it. Client has no default either — pass an IMongoClient, or use the constructor that takes a connection string and builds one for you.

Outbox defaults to null and the Outbox will not run without it, so read that null as you must set this rather than as this is optional.

Each of Outbox, Inbox and Locking takes a MongoDbCollectionConfiguration:

Option
Type
Default
Description

Name

string

""

Names the MongoDB collection.

MakeCollection

OnResolvingACollection

Assume

Sets what Brighter does when it resolves the collection — see Collection Management.

Settings

MongoCollectionSettings?

null

Sets the collection-level settings used when the collection is opened.

CreateCollectionOptions

CreateCollectionOptions?

null

Supplies the options used when Brighter creates the collection.

TimeToLive

TimeSpan?

null

Sets the TTL index Brighter creates on TimeStamp when it creates the collection; that index removes nothing — see TTL Support.

MongoDB Outbox Configuration

Basic Configuration

As described in Command Processor Configuration Reference, we configure Brighter to use an outbox with the AddProducers method call.

Advanced Configuration

For more advanced scenarios, you can provide custom MongoDB client settings and collection configurations:

Using a Connection Provider

You can also use a custom connection provider for more control over the MongoDB connection:

MongoDB Outbox Time-To-Live (TTL) Support

TimeToLive asks for a MongoDB TTL index on the TimeStamp field. At Brighter 10.8.1 that index expires nothing, so if you want MongoDB to remove old messages, create the index yourself:

  • Brighter creates its index only when it creates the collection, which it does only with MakeCollection = OnResolvingACollection.CreateIfNotExists. Under the default, Assume, there is no index.

  • The index it creates, brighter_ttl_Outbox on TimeStamp, removes no document. Brighter stores TimeStamp as an embedded document of DateTime, Ticks and Offset, and MongoDB expires a document only when the indexed field holds a date.

A TTL index on TimeStamp.DateTime does expire them:

MongoDB's TTL monitor runs once a minute, so a document can outlive its time-to-live by up to a minute.

Using the Outbox in Handlers

In your handler, take a dependency on IAmAMongoDbTransactionProvider, which Brighter registers for the MongoDbUnitOfWork you set as the TransactionProvider, and on the IAmAMongoDbConfiguration you registered beside it. Brighter does not register IAmATransactionConnectionProvider for MongoDB; that interface is for relational databases, and a handler that asks for it cannot be created.

Pass the provider to DepositPostAsync as it is. IAmAMongoDbTransactionProvider is an IAmABoxTransactionProvider<IClientSessionHandle>, and the MongoDbOutbox writes in an IClientSessionHandle, so that is the transaction type Brighter configures. It is also the session type the MongoDB driver's collection methods take.

Before Brighter 10.8.1, the interface was an IAmABoxTransactionProvider<IClientSession>, so DepositPostAsync threw InvalidOperationException: Supplied transaction provider doesn't match configured transaction type. unless you cast the provider to IAmABoxTransactionProvider<IClientSessionHandle> first.

Start the transaction through the provider, write your documents in its session, and call DepositPostAsync with the provider so the message is written to the Outbox in the same transaction. Commit through the provider; if anything fails, roll back and neither your change nor the message is written. Once the transaction has committed, you can call ClearOutboxAsync to dispatch the message immediately, or you can rely on the Outbox Sweeper to dispatch it for you.

Running more than one instance? Configure a distributed lock so only one Sweeper (and Archiver) runs at a time — see MongoDB Distributed Lock.

MongoDB Outbox Message Structure

The MongoDB Outbox stores messages as BSON documents with the following structure:

  • MessageId: The unique identifier for the message

  • Topic: The topic/destination for the message

  • MessageType: The type of the message

  • TimeStamp: When the message was created (UTC), as an embedded document of DateTime, Ticks and Offset. A TTL index belongs on TimeStamp.DateTime

  • CorrelationId: Optional correlation identifier

  • ReplyTo: Optional reply-to address

  • ContentType: The content type of the message

  • PartitionKey: Optional partition key for message routing

  • HeaderBag: JSON serialized message headers

  • Body: The message body as bytes

  • Dispatched: Timestamp when the message was dispatched (null if not yet dispatched)

Here is an example of a message document stored in the outbox collection:

MongoDB Outbox Error Handling

The MongoDB Outbox will throw appropriate exceptions for various error conditions:

  • ArgumentException: When required configuration is missing

  • MongoException: For MongoDB-specific errors like connection failures or transaction conflicts

  • InvalidOperationException: For outbox-specific errors like attempting operations without proper transaction context

Transaction Requirements

MongoDB transactions require:

  • MongoDB 4.0+ for replica sets

  • MongoDB 4.2+ for sharded clusters

  • Replica set deployment (transactions don't work on standalone instances)

Make sure your MongoDB deployment supports transactions before using the MongoDB Outbox pattern.

Last updated

Was this helpful?