{"id":7441,"date":"2024-01-04T07:15:34","date_gmt":"2024-01-04T15:15:34","guid":{"rendered":"https:\/\/devblogs.microsoft.com\/cosmosdb\/?p=7441"},"modified":"2024-01-30T11:56:44","modified_gmt":"2024-01-30T19:56:44","slug":"azure-cosmos-db-design-patterns-part-4-global-distributed-lock","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/cosmosdb\/azure-cosmos-db-design-patterns-part-4-global-distributed-lock\/","title":{"rendered":"Azure Cosmos DB design patterns \u2013 Part 4: Global distributed lock"},"content":{"rendered":"<p>Over the years, customers have asked us for help in designing applications around specific scenarios they were trying to achieve. In some cases, these centered around implementing certain patterns using a JSON-based NoSQL database. Some of these patterns are very common in the NoSQL world, but not well understood by those new to NoSQL databases. Other patterns were very specific to the Cosmos DB service itself in demonstrating how to leverage specific capabilities to solve difficult architectural challenges.<\/p>\n<p><img decoding=\"async\" width=\"1024\" height=\"512\" class=\"wp-image-7442 aligncenter\" src=\"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/azure-samples-cosmsos-db-design-patterns.jpeg\" alt=\"Azure Samples \/ cosmsos-db-design-patterns\" srcset=\"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/azure-samples-cosmsos-db-design-patterns.jpeg 1024w, https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/azure-samples-cosmsos-db-design-patterns-300x150.jpeg 300w, https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/azure-samples-cosmsos-db-design-patterns-768x384.jpeg 768w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/p>\n<p>We\u2019ve been capturing these patterns and sharing them with customers individually. We felt now was a good time to publish some of these more broadly to make more discoverable by users. The result is <a href=\"https:\/\/github.com\/Azure-Samples\/cosmos-db-design-patterns\" target=\"_blank\" rel=\"noopener\">Azure Cosmos DB Design Patterns<\/a>. A repository on GitHub that includes a wide variety of samples that show how to implement specific patterns that will allow you to solve design-related challenges when using Azure Cosmos DB for your solutions.<\/p>\n<p>To help share these, we\u2019ve created a blog post series on each of them. Each post will focus on a specific design pattern with a corresponding sample application that\u2019s featured in this repository. We hope you enjoy and find this series useful.<\/p>\n<p>Here\u2019s a list of the previous posts in this series:<\/p>\n<ul>\n<li><a href=\"https:\/\/devblogs.microsoft.com\/cosmosdb\/azure-cosmos-db-design-patterns-part-1-attribute-array\/\" target=\"_blank\" rel=\"noopener\">Part 1: Attribute Array<\/a><\/li>\n<li><a href=\"https:\/\/devblogs.microsoft.com\/cosmosdb\/azure-cosmos-db-design-patterns-part-2-data-binning\/\" target=\"_blank\" rel=\"noopener\">Part 2: Data Binning<\/a><\/li>\n<li><a href=\"https:\/\/devblogs.microsoft.com\/cosmosdb\/azure-cosmos-db-design-patterns-part-3-distributed-counter\/\" target=\"_blank\" rel=\"noopener\">Part 3: Distributed counter<\/a><\/li>\n<\/ul>\n<h2>Azure Cosmos DB design pattern: Global Distributed Lock<\/h2>\n<p>This blog post will focus on the <a href=\"https:\/\/github.com\/Azure-Samples\/cosmos-db-design-patterns\/tree\/main\/distributed-lock\" target=\"_blank\" rel=\"noopener\">Global Distributed Lock Pattern example we\u2019ve provided in this GitHub repository<\/a>. The NoSQL Global Distributed Lock Design Pattern is designed for synchronizing access to shared resources in distributed systems. It allows a process to acquire a global lock, ensuring exclusive access to a resource and preventing concurrent modifications. This pattern is superior to regular locks as it handles challenges like network delays, system failures, and data partitioning in a distributed environment. Key features include fence tokens for secure operation ordering, high availability, fault tolerance, scalability, and effective management of network partitions and failures. It&#8217;s ideal for large-scale applications requiring consistent access to shared resources across multiple nodes.<\/p>\n<p><a href=\"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/dist-lock.jpg\"><img decoding=\"async\" class=\"aligncenter size-full wp-image-7444\" src=\"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/dist-lock.jpg\" alt=\"Azure Cosmos DB design pattern: Global Distributed Lock\" width=\"1024\" height=\"1024\" srcset=\"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/dist-lock.jpg 1024w, https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/dist-lock-300x300.jpg 300w, https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/dist-lock-150x150.jpg 150w, https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/dist-lock-768x768.jpg 768w, https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/dist-lock-24x24.jpg 24w, https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/dist-lock-48x48.jpg 48w, https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/dist-lock-96x96.jpg 96w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/a><\/p>\n<h2>The Scenario:<\/h2>\n<p>A distributed global lock in the NoSQL design pattern is commonly used for enforcing mutual exclusion or coordination across multiple nodes or processes in a distributed system. Here are some examples:<\/p>\n<ol>\n<li><strong>Critical Sections<\/strong>: In distributed systems, some operations or code segments, known as critical sections, require atomic execution by only one node at a time. A distributed global lock ensures that only one node or process enters this critical section at any given moment, thereby preventing conflicts and maintaining data consistency.<\/li>\n<li><strong>Resource Synchronization<\/strong>: For scenarios where multiple nodes or processes simultaneously access and modify a shared resource, a distributed lock coordinates this access. For instance, in a document-oriented NoSQL database, if several nodes are updating the same document, a distributed lock guarantees that only one node modifies the document at a time, thus avoiding conflicts and preserving data integrity.<\/li>\n<li><strong>Concurrency Control<\/strong>: In situations where multiple nodes or processes execute parallel operations on shared data, distributed locks are crucial for concurrency control. By securing a lock on a specific resource or data entity, a node ensures exclusive access, preventing concurrent modifications that could result in inconsistency or errors.<\/li>\n<li><strong>Distributed Transactions<\/strong>: Distributed locks are pivotal in distributed transactional systems, where multiple operations across different nodes must be executed atomically. They facilitate the coordination of various transaction phases, ensuring no conflicting operations occur during the transaction.<\/li>\n<\/ol>\n<p>Utilizing a distributed global lock allows for the coordination and synchronization of actions across multiple nodes or processes, thus ensuring consistency and preventing conflicts in a distributed setting. However, it\u2019s vital to recognize the complexity in correctly and efficiently implementing distributed locks. The specific mechanisms and techniques employed may vary depending on the NoSQL database in use.<\/p>\n<h2>Sample Implementation:<\/h2>\n<p>In this example, the application generates a Lock using a user-provided Name and Time to Live (TTL). This Lock is established within Azure Cosmos DB, allowing it to be monitored by multiple worker threads distributed across various locations. The example illustrates this by creating three threads that persistently attempt to acquire the lock. Once a worker thread successfully obtains the lock, it retains it for a randomly determined duration in milliseconds before relinquishing it. Should the lock not be released within the specified TTL, it is automatically freed.<\/p>\n<p><img decoding=\"async\" width=\"1275\" height=\"944\" class=\"wp-image-7443 aligncenter\" src=\"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/a-screenshot-of-a-computer-program-description-au.png\" alt=\"A screenshot of a computer program Description automatically generated\" srcset=\"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/a-screenshot-of-a-computer-program-description-au.png 1275w, https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/a-screenshot-of-a-computer-program-description-au-300x222.png 300w, https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/a-screenshot-of-a-computer-program-description-au-1024x758.png 1024w, https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/a-screenshot-of-a-computer-program-description-au-768x569.png 768w\" sizes=\"(max-width: 1275px) 100vw, 1275px\" \/><\/p>\n<p>The implementation leverages the TTL feature to automatically dispose of a lease object, eliminating the need for clients to manually verify a &#8216;<span style=\"font-family: 'andale mono', monospace;\">leasedUntil<\/span>&#8216; date. However, there&#8217;s still a requirement to ensure that two clients aren&#8217;t attempting to lease the same object simultaneously. This concurrency check is efficiently handled in Azure Cosmos DB using the &#8216;etag&#8217; property associated with the object. The screenshot provided demonstrates the Distributed Lock Application in operation.<\/p>\n<h2>Why It Matters:<\/h2>\n<p>The use of the Global Distributed Lock Design Pattern is crucial for software developers, particularly when dealing with distributed systems, for several key reasons:<\/p>\n<ol>\n<li><strong>Ensures Data Consistency<\/strong>: In distributed systems, where multiple processes or nodes might attempt to access or modify a shared resource simultaneously, this pattern helps in maintaining data consistency. It prevents conflicting updates and ensures that each operation on the resource is performed atomically.<\/li>\n<li><strong>Avoids Race Conditions<\/strong>: Race conditions occur when the behavior of a system depends on the sequence or timing of uncontrollable events. The global distributed lock mitigates this by controlling access to shared resources, ensuring that only one process can operate on a resource at a time.<\/li>\n<li><strong>Facilitates Synchronization Across Multiple Nodes<\/strong>: In distributed systems that span across multiple geographical locations or networks, this pattern synchronizes operations across all nodes. It&#8217;s essential for operations that need to be coordinated globally.<\/li>\n<li><strong>Improves System Reliability<\/strong>: By managing access to shared resources effectively, the pattern reduces the likelihood of system crashes or failures due to concurrent access or data corruption, thus enhancing the overall reliability of the system.<\/li>\n<li><strong>Supports Scalability<\/strong>: As systems grow and more nodes or processes need to access shared resources, a global distributed lock scales to accommodate this growth, ensuring that the system continues to function efficiently and consistently.<\/li>\n<li><strong>Handles Network Partitions and Failures<\/strong>: In distributed systems, network issues and node failures are common. The global distributed lock pattern is designed to handle these situations gracefully, ensuring that the system remains robust and operational.<\/li>\n<li><strong>Facilitates Complex Operations in Distributed Transactions<\/strong>: For complex operations that span multiple databases or services, this pattern can be critical in ensuring that the entire operation either completes successfully or rolls back in case of a failure, maintaining data integrity.<\/li>\n<li><strong>Simplifies Development<\/strong>: While the underlying mechanisms of global distributed locks can be complex, using a well-designed pattern simplifies the development process by providing a clear and tested method for handling concurrency in distributed systems.<\/li>\n<li><strong>Promotes Best Practices<\/strong>: Utilizing such patterns encourages developers to think in terms of global, distributed architectures, promoting best practices in designing and building scalable, high-performance applications.<\/li>\n<\/ol>\n<p>In summary, the Global Distributed Lock Design Pattern is a vital tool for software developers working with distributed systems, as it addresses key challenges such as data consistency, race conditions, synchronization, scalability, and system reliability.<\/p>\n<h2>Getting Started with Azure Cosmos DB Design Patterns<\/h2>\n<p>You can review the sample code by visiting the\u00a0<a href=\"https:\/\/github.com\/Azure-Samples\/cosmos-db-design-patterns\/tree\/main\/distributed-lock\" target=\"_blank\" rel=\"noopener\">Global Distributed Lock Pattern\u00a0on GitHub<\/a>. You can also try this out for yourself by visiting the\u00a0<a href=\"https:\/\/github.com\/Azure-Samples\/cosmos-db-design-patterns\" target=\"_blank\" rel=\"noopener\">Azure Cosmos DB Design Patterns<\/a>\u00a0GitHub repo and cloning or forking it. Then run locally or from Code Spaces in GitHub. If you are new to Azure Cosmos DB, we have got you covered with a\u00a0<a href=\"https:\/\/aka.ms\/trycosmosdb\" target=\"_blank\" rel=\"noopener\">free Azure Cosmos DB account\u00a0<\/a>for 30 days, no credit card required. If you want more time, you can extend the free period. You can even upgrade too.<\/p>\n<p>Sign up for your free Azure Cosmos DB account at\u00a0<a href=\"https:\/\/aka.ms\/trycosmosdb\" target=\"_blank\" rel=\"noopener\">aka.ms\/trycosmosdb<\/a>.<\/p>\n<p>Explore this and the other design patterns and see how Azure Cosmos DB can enhance your application development and data modeling efforts. Whether you\u2019re an experienced developer or just getting started, the free trial allows you to discover the benefits firsthand.<\/p>\n<p>To get started with Azure Cosmos DB Design Patterns, follow these steps:<\/p>\n<ol>\n<li>Visit the\u00a0<a href=\"https:\/\/github.com\/Azure-Samples\/cosmos-db-design-patterns\" target=\"_blank\" rel=\"noopener\">GitHub repository\u00a0<\/a>and explore the various design patterns and best practices provided.<\/li>\n<li>Clone or download the repository to access the sample code and documentation.<\/li>\n<li>Review the README files and documentation for each design pattern to understand when and how to apply them to your Azure Cosmos DB projects.<\/li>\n<li>Experiment with the sample code and adapt it to your specific use cases.<\/li>\n<\/ol>\n<h3>About Azure Cosmos DB<\/h3>\n<p>Azure Cosmos DB is a fully managed and serverless distributed database for modern app development, with SLA-backed speed and availability, automatic and instant scalability, and support for open-source PostgreSQL, MongoDB, and Apache Cassandra.\u00a0<a href=\"https:\/\/cosmos.azure.com\/try\/\" target=\"_blank\" rel=\"noopener\">Try Azure Cosmos DB for free here.<\/a>\u00a0To stay in the loop on Azure Cosmos DB updates, follow us on\u00a0<a href=\"https:\/\/twitter.com\/AzureCosmosDB\" target=\"_blank\" rel=\"noopener\">Twitter<\/a>,\u00a0<a href=\"https:\/\/www.youtube.com\/AzureCosmosDB\" target=\"_blank\" rel=\"noopener\">YouTube<\/a>, and\u00a0<a href=\"https:\/\/www.linkedin.com\/company\/azure-cosmos-db\/\" target=\"_blank\" rel=\"noopener\">LinkedIn<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Over the years, customers have asked us for help in designing applications around specific scenarios they were trying to achieve. In some cases, these centered around implementing certain patterns using a JSON-based NoSQL database. Some of these patterns are very common in the NoSQL world, but not well understood by those new to NoSQL databases. [&hellip;]<\/p>\n","protected":false},"author":39313,"featured_media":7442,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[14],"tags":[1882],"class_list":["post-7441","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-core-sql-api","tag-design-patterns"],"acf":[],"blog_post_summary":"<p>Over the years, customers have asked us for help in designing applications around specific scenarios they were trying to achieve. In some cases, these centered around implementing certain patterns using a JSON-based NoSQL database. Some of these patterns are very common in the NoSQL world, but not well understood by those new to NoSQL databases. [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/posts\/7441","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/users\/39313"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/comments?post=7441"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/posts\/7441\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/media\/7442"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/media?parent=7441"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/categories?post=7441"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/tags?post=7441"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}