DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Write Integration Tests on MongoDB With .NET Core and Docker
  • Loading XML into MongoDB
  • Feature Flags in .NET 8 and Azure
  • Implementing CRUD Operations With NLP Using Microsoft.Extensions.AI

Trending

  • Cloud Security and Privacy: Best Practices to Mitigate the Risks
  • How to Build Real-Time BI Systems: Architecture, Code, and Best Practices
  • Rust, WASM, and Edge: Next-Level Performance
  • Efficient API Communication With Spring WebClient
  1. DZone
  2. Data Engineering
  3. Databases
  4. How to do Document-level Locking on MongoDB and .NET Core

How to do Document-level Locking on MongoDB and .NET Core

By 
David Guida user avatar
David Guida
·
Jan. 11, 21 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
12.1K Views

Join the DZone community and get the full member experience.

Join For Free

Hi All! Today we’re going to see how MongoDB handles locks and how we can achieve Document-level locking.

The default MongoDB storage engine, WiredTiger, uses optimistic concurrency control, or OCC. In a nutshell, it assumes that

multiple transactions can frequently complete without interfering with each other.

WIKIPEDIA

This basically means we’re somewhat sure that nobody else is going to update our data while we’re working on it.

In case that happens, one operation is going to succeed, while the others will fail, entering some kind of retry loop.

We’re relying on the nature of the data and the operations available on the Domain. In short, we’re being optimistic that things will end up just fine.

When we want to be absolutely sure that only one consumer will be able to operate a specific set of data, we could use some form of locking.

This falls into the realm of Pessimistic Locking: we block access to the data till we’re done with it. The drawback is simple: what if we never release a lock? The other consumers will deadlock, so we need a proper strategy (for example timeouts) to handle those cases.

It can get complicated and ugly pretty quickly so be careful.

There might be some situations, however, where you need more fine control over the locking strategy, for example when you're dealing with Sagas and Distributed Transactions.

Now, WiredTiger allows locking only at the global, database, or collection levels. This means that we cannot lock a single document.

Luckily for us, operations on MongoDB are atomic, so we can “fake” some sort of pessimistic locking and handle part of the complexity on the application side.

The idea is to decorate every document with two additional properties, something like:

JSON
 




x


 
1
{    
2
  "LockId" : UUID("6ca9d76f-01ac-42cc-88ca-b2ecd5b286c3"),    
3
  "LockTime" : ISODate("2020-12-28T04:42:13.528Z") 
4
}



When we want to lock a document, we fetch it by ID but we also make sure that LockId is null. Additionally, we can also check that LockTime is after a specific window: this way we can discard previous locks if they’re expired.

Using the FindOneAndUpdateAsync API, we can fetch the document and in the same operation, we can set both LockId and LockTime.

We’ll also configure the call to be an upsert: this way if the document is not in the DB yet, we can also create it. Moreover, the next time someone is trying to access it, the engine will throw a MongoCommandException instead.

When we’re done with the document, we can release it by simply setting to null both LockId and LockTime.

Just for you to know, a while ago I started working on OpenSleigh, a distributed saga management library for .NET Core. It uses the same technique in its MongoDB persistence driver.

The next time we’ll see a small demo and dig a bit more into the details. Stay tuned!

MongoDB .NET

Opinions expressed by DZone contributors are their own.

Related

  • Write Integration Tests on MongoDB With .NET Core and Docker
  • Loading XML into MongoDB
  • Feature Flags in .NET 8 and Azure
  • Implementing CRUD Operations With NLP Using Microsoft.Extensions.AI

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!