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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
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; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 |
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(); } } } |