MongoDB persistence uses the MongoDB document database for storage.
Use a MongoDB server version that is compatible with the version of MongoDB. your endpoint uses. See the MongoDB driver compatibility tables.
Persistence at a glance
For a description of each feature, see the persistence at a glance legend.
| Feature | |
|---|---|
| Supported storage types | Sagas, Outbox, Subscriptions |
| Transactions | Enabled and required by default |
| Concurrency control | Pessimistic locking for saga updates and deletes when transactions are enabled |
| Scripted deployment | Not supported |
| Installers | Index creation depends on the persistence version |
Usage
Add a NuGet package reference to NServiceBus.. Configure the endpoint to use the persistence through the following configuration API:
endpointConfiguration.UsePersistence<MongoPersistence>();
Customizing the connection
By default, a MongoClient is created that connects to mongodb:/ and uses the endpoint name as its database name.
To customize the connection, pass a MongoClient configured with your connection string in place of SharedMongoUrl:
var persistence = endpointConfiguration.UsePersistence<MongoPersistence>();
persistence.MongoClient(new MongoClient("SharedMongoUrl"));
Specify the database to use for NServiceBus documents using the following configuration API:
var persistence = endpointConfiguration.UsePersistence<MongoPersistence>();
persistence.DatabaseName("DatabaseName");
Transactions
MongoDB persistence enables and requires transactions by default. Transactions let the persistence use pessimistic locking and commit updates to multiple saga instances atomically during message processing.
MongoDB transactions require a replica set or sharded cluster. See the MongoDB transaction requirements for the minimum feature compatibility version for each configuration.
Disabling transactions
The following configuration API is available for compatibility with MongoDB server configurations that don't support transactions:
var persistence = endpointConfiguration.UsePersistence<MongoPersistence>();
persistence.UseTransactions(false);
Note that this disables the ability to use pessimistic locking for sagas, which might result in higher contention in the database.
Shared transactions
NServiceBus supports sharing MongoDB sessions between Saga persistence, Outbox storage, and business data. The shared session can be used to persist multiple document updates atomically.
Pass the MongoDB session to each collection API call that needs to participate in the shared transaction.
To access the shared session in a message handler:
public Task Handle(MyMessage message, IMessageHandlerContext context)
{
var session = context.SynchronizedStorageSession.GetClientSession();
var collection = session.Client.GetDatabase("mydatabase").GetCollection<MyBusinessObject>("mycollection");
return collection.InsertOneAsync(session, new MyBusinessObject(), null, context.CancellationToken);
}
To access the session through dependency injection, use IMongoSynchronizedStorageSession:
class MyService
{
IMongoSynchronizedStorageSession sharedSession;
// Resolved from DI container
public MyService(IMongoSynchronizedStorageSession sharedSession)
{
this.sharedSession = sharedSession;
}
public Task Create()
{
return sharedSession.MongoSession.Client
.GetDatabase("mydatabase")
.GetCollection<MyBusinessObject>("mycollection")
.InsertOneAsync(sharedSession.MongoSession, new MyBusinessObject());
}
}
The IMongoSynchronizedStorageSession lifetime is scoped to the message processing pipeline. Do not resolve the shared session into dependencies with a Singleton lifetime.
Testing
The TestableMongoSynchronizedStorageSession class in the NServiceBus. namespace has been provided to facilitate testing a handler that utilizes the shared transaction feature.
Outbox
Storage format
Outbox record documents are stored in a collection called outboxrecord.
Outbox documents are not separated by endpoint name. Because of that, multiple logical endpoints cannot share the same database since message identities are not unique across endpoints from a processing perspective.
Outbox cleanup
When the outbox is enabled, the deduplication data is kept for seven days by default. To customize this time frame, use the following API:
var persistence = endpointConfiguration.UsePersistence<MongoPersistence>();
persistence.TimeToKeepOutboxDeduplicationData(TimeSpan.FromDays(30));
Saga concurrency
Concurrent message handling can cause conflicts. See Saga concurrency for how NServiceBus handles these conflicts and for guidance on high-load scenarios.
Starting a saga
Example exception:
MongoDB.Driver.MongoCommandException: Command insert failed: WriteConflict.
Updating or deleting saga data
When transactions are enabled, MongoDB persistence uses exclusive locks for saga updates and deletes. It tries to acquire a lock for up to 60 seconds. If it cannot acquire one in that time, it throws a TimeoutException and the regular message retry policies apply.
Example exception:
System.TimeoutException: Unable to acquire exclusive write lock for saga on collection 'collectionName'
This means that the relevant Handle method on the saga will be invoked, even though the message might be later rolled back. Hence it is important to ensure not to perform any work in saga handlers that can't roll back together with the message. This also means that should there be high levels of concurrency there will be N-1 rollbacks where N is the number of concurrent messages. This can cause throughput issues and might require design changes.
Installer
Installers are not supported. Indexes are created regardless of the installer settings.