Why locking in the first place? Because in many scenarios we need to guarantee the consistency of the data, this means that we will not allow for one user changing data that another user has already edited. There are 2 types of locks that we can implement:
- optimistic
- pessimistic
When pessimistic?
A pessimistic lock is a exclusive lock while editing a record. If one process has acquired the exclusive lock, then no other process can read/update until that lock is released. As you can obviously notice, this is not performant when we need to allow reads while disallow writes.
One scenario where a a pessimistic lock is useful: imagine that you have a worker implementing an outbox pattern, it has to read an element from the database and send an event. If you want to scale that worker, you have to make sure that each database entry is read only once.
When optimistic?
As per Microsoft article, we assume using the optimistic lock that the collection is not often changed, collisions are rare and we have to control and prevent collisions in a fashion where we allow reads and disallow collision-writes.
One of the most used method to test for optimistic concurrency violation is to use a timestamp
Enough with the theory, getting to the point. How to implement this in mongo? Simple as adding a timestamp property and leverage that with every database action. The following implementation has the following assumptions:
- The write concern is at least Acknowledged because we actually need to know if the operation was “received” however for better consistency you should set it to “Majority”. More about write concerns
- We cannot delete/update/replace multiple documents based on a Linq Expression because we need to validate each timestamp.
Now follows the implementation:
- I didn’t add the read methods since it was too much code and it’s not part of the topic
- I also did not add an example for Bulk operations because it was too much code and it defeats the purpose. In bulk operations you have to remember each operation model and analyze the response for each operation type.
The base document is just a class with id and timestamp:
public class BaseDocument { [BsonConstructor] public BaseDocument() { Timestamp = DateTimeOffset.UtcNow.Ticks; } public BaseDocument(Guid id) { Id = id; Timestamp = DateTimeOffset.UtcNow.Ticks; } [BsonId(IdGenerator = typeof(GuidGenerator))] [BsonIgnoreIfDefault] [BsonRepresentation(BsonType.String)] public Guid Id { get; set; } [BsonElement("Timestamp")] public long Timestamp { get; set; } }
public sealed class CollectionUnitOptimistic<TDocument> where TDocument : BaseDocument<TDocument> { private IMongoCollection<TDocument> MongoCollection { get; } public CollectionUnitOptimistic(IMongoCollection<TDocument> mongoCollection) { MongoCollection = mongoCollection; } public Task<long> CountAsync( Expression<Func<TDocument, bool>> filter, CountOptions countOptions = null, IClientSessionHandle session = null) { Ensure.IsNotNull(filter, nameof(filter)); return session != null ? MongoCollection.CountDocumentsAsync(session, filter, countOptions) : MongoCollection.CountDocumentsAsync(filter, countOptions); } public Task<long> CountAsync( FilterDefinition<TDocument> filter, CountOptions countOptions = null, ClientSessionHandle session = null) { Ensure.IsNotNull(filter, nameof(filter)); return session != null ? MongoCollection.CountDocumentsAsync(session, filter, countOptions) : MongoCollection.CountDocumentsAsync(filter, countOptions); } public async Task DeleteOneAsync( BaseDocument document, IClientSessionHandle session = null) { FilterDefinition<TDocument> filter = Builders<TDocument>.Filter.Eq(x => x.Id, document.Id) & Builders<TDocument>.Filter.Eq(r => r.Timestamp, document.Timestamp); DeleteResult result = session == null ? await MongoCollection.DeleteOneAsync(filter).ConfigureAwait(false) : await MongoCollection.DeleteOneAsync(session, filter).ConfigureAwait(false); if (!result.IsAcknowledged) { throw ThrowHelpers.NotAcknowledged(); } if (result.DeletedCount != 1 && MongoCollection.CountDocuments(r => r.Id == document.Id) == 1) { throw ThrowHelpers.ConcurrencyDeleteOneFailed(document); } } public async Task DeleteManyAsync( IEnumerable<BaseDocument> documents, IClientSessionHandle session = null) { List<DeleteOneModel<TDocument>> deleteModels = new List<DeleteOneModel<TDocument>>(); documents.ForEach(r => deleteModels.Add(new DeleteOneModel<TDocument>( Builders<TDocument>.Filter.Eq(t => t.Id, r.Id) & Builders<TDocument>.Filter.Eq(t => t.Timestamp, r.Timestamp) ))); BulkWriteResult<TDocument> result; if (session is null) { result = await MongoCollection.BulkWriteAsync(deleteModels); } else { result = await MongoCollection.BulkWriteAsync(session, deleteModels); } if (!result.IsAcknowledged) { throw ThrowHelpers.NotAcknowledged(); } if (result.DeletedCount != deleteModels.Count) { List<Guid> documentIds = documents.Select(r => r.Id).ToList(); if (MongoCollection.CountDocuments(Builders<TDocument>.Filter.In(r => r.Id, documentIds)) == documentIds.Count) { throw ThrowHelpers.ConcurrencyException(); } } } public async Task<List<TDocument>> InsertManyAsync( List<TDocument> documents, IClientSessionHandle session = null) { Ensure.IsNotNull(documents, nameof(documents)); foreach (TDocument document in documents) { document.Id = (document.Id == Guid.Empty) ? Guid.NewGuid() : document.Id; document.Timestamp = DateTimeOffset.UtcNow.Ticks; } if (session == null) { await MongoCollection.InsertManyAsync(documents).ConfigureAwait(false); } else { await MongoCollection.InsertManyAsync(session, documents).ConfigureAwait(false); } return documents; } public async Task<TDocument> InsertOneAsync( TDocument document, IClientSessionHandle session = null) { Ensure.IsNotNull(document, nameof(document)); document.Id = (document.Id == Guid.Empty) ? Guid.NewGuid() : document.Id; document.Timestamp = DateTimeOffset.UtcNow.Ticks; if (session == null) { await MongoCollection.InsertOneAsync(document).ConfigureAwait(false); } else { await MongoCollection.InsertOneAsync(session, document).ConfigureAwait(false); } return document; } public async Task ReplaceOneAsync( TDocument document, IClientSessionHandle session = null) { Ensure.IsNotNull(document, nameof(document)); Ensure.IsNotEmpty(document.Id, nameof(document.Id)); ReplaceOneResult result; long currentTS = document.Timestamp; document.Timestamp = DateTimeOffset.UtcNow.Ticks; FilterDefinition<TDocument> filter = Builders<TDocument>.Filter.Eq(r => r.Id, document.Id) & Builders<TDocument>.Filter.Eq(r => r.Timestamp, currentTS); if (session == null) { result = await MongoCollection.ReplaceOneAsync(filter, document, new ReplaceOptions { IsUpsert = false }).ConfigureAwait(false); } else { result = await MongoCollection.ReplaceOneAsync(session, filter, document, new ReplaceOptions { IsUpsert = false }).ConfigureAwait(false); } if (!result.IsAcknowledged) { throw ThrowHelpers.NotAcknowledged(); } if (result.ModifiedCount == 0 && MongoCollection.CountDocuments(r => r.Id == document.Id) == 1) { throw ThrowHelpers.ConcurrencyReplaceOneFail(document); } } public async Task ReplaceManyAsync( IEnumerable<TDocument> documents, IClientSessionHandle session = null) { Ensure.IsNotNull(documents, nameof(documents)); List<ReplaceOneModel<TDocument>> replaceModels = new List<ReplaceOneModel<TDocument>>(); foreach (TDocument document in documents) { FilterDefinition<TDocument> filter = Builders<TDocument>.Filter.Eq(r => r.Id, document.Id) & Builders<TDocument>.Filter.Eq(r => r.Timestamp, document.Timestamp); document.Timestamp = DateTimeOffset.UtcNow.Ticks; ReplaceOneModel<TDocument> replaceModel = new ReplaceOneModel<TDocument>( filter, document ) { IsUpsert = false }; replaceModels.Add(replaceModel); } BulkWriteResult<TDocument> result; if (session == null) { result = await MongoCollection.BulkWriteAsync(replaceModels).ConfigureAwait(false); } else { result = await MongoCollection.BulkWriteAsync(session, replaceModels).ConfigureAwait(false); } if (!result.IsAcknowledged) { throw ThrowHelpers.NotAcknowledged(); } if (result.ModifiedCount != documents.Count()) { var documentIds = documents.Select(r => r.Id); if (MongoCollection.CountDocuments(r => documentIds.Contains(r.Id)) != documentIds.Count()) { throw ThrowHelpers.ConcurrencyException(); } throw ThrowHelpers.NotAcknowledged(); } } public async Task ReplaceOneUpsertAsync( TDocument document, IClientSessionHandle session = null) { Ensure.IsNotNull(document, nameof(document)); //if the id is empty, we will upsert the document document.Id = (document.Id == Guid.Empty) ? Guid.NewGuid() : document.Id; ReplaceOneResult result; long currentTS = document.Timestamp; document.Timestamp = DateTimeOffset.UtcNow.Ticks; FilterDefinition<TDocument> filter = Builders<TDocument>.Filter.Eq(r => r.Id, document.Id) & Builders<TDocument>.Filter.Eq(r => r.Timestamp, currentTS); if (session == null) { result = await MongoCollection.ReplaceOneAsync(filter, document, new ReplaceOptions { IsUpsert = true }).ConfigureAwait(false); } else { result = await MongoCollection.ReplaceOneAsync(filter, document, new ReplaceOptions { IsUpsert = true }).ConfigureAwait(false); } if (!result.IsAcknowledged) { throw ThrowHelpers.NotAcknowledged(); } if (result.ModifiedCount == 0 && MongoCollection.CountDocuments(r => r.Id == document.Id) == 1) { throw ThrowHelpers.ConcurrencyReplaceOneFail(document); } } public async Task UpdateManyAsync( List<TDocument> documents, UpdateDefinition<TDocument> update, IClientSessionHandle session = null) { Ensure.IsNotNull(documents, nameof(documents)); Ensure.IsNotNull(update, nameof(update)); List<UpdateOneModel<TDocument>> updateModels = new List<UpdateOneModel<TDocument>>(); documents.ForEach(r => updateModels.Add( new UpdateOneModel<TDocument>( Builders<TDocument>.Filter.Eq(t => t.Id, r.Id) & Builders<TDocument>.Filter.Eq(t => t.Timestamp, r.Timestamp), update.Set(r => r.Timestamp, DateTimeOffset.UtcNow.Ticks)) { IsUpsert = false } )); BulkWriteResult<TDocument> result = null; if (session is null) { result = await MongoCollection.BulkWriteAsync(updateModels); } else { result = await MongoCollection.BulkWriteAsync(session, updateModels); } if (!result.IsAcknowledged) { throw ThrowHelpers.NotAcknowledged(); } if (result.DeletedCount != documents.Count) { List<Guid> documentIds = documents.Select(r => r.Id).ToList(); if (MongoCollection.CountDocuments(Builders<TDocument>.Filter.In(r => r.Id, documentIds)) == documentIds.Count) { throw ThrowHelpers.ConcurrencyException(); } throw ThrowHelpers.NotAcknowledged(); } } }