{"id":7451,"date":"2024-01-11T07:00:47","date_gmt":"2024-01-11T15:00:47","guid":{"rendered":"https:\/\/devblogs.microsoft.com\/cosmosdb\/?p=7451"},"modified":"2024-01-30T11:56:54","modified_gmt":"2024-01-30T19:56:54","slug":"azure-cosmos-db-design-patterns-part-5-document-versioning","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/cosmosdb\/azure-cosmos-db-design-patterns-part-5-document-versioning\/","title":{"rendered":"Azure Cosmos DB design patterns \u2013 Part 5: Document versioning"},"content":{"rendered":"<p>Welcome to part five of our series of blog posts focused on sharing common design patterns you can use to build applications with Azure Cosmos DB for NoSQL. 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 <a id=\"post-7451-_Int_Ovd5WDRB\"><\/a>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-7452\" src=\"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/azure-samples-cosmsos-db-design-patterns-1.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-1.jpeg 1024w, https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/azure-samples-cosmsos-db-design-patterns-1-300x150.jpeg 300w, https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/azure-samples-cosmsos-db-design-patterns-1-768x384.jpeg 768w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/p>\n<p>We have been capturing these patterns and sharing them with customers individually. We felt now was <a id=\"post-7451-_Int_qkjxpWAx\"><\/a>a good time to publish some of these more broadly to make it 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 have created a blog post series on each of them. Each post will focus on a specific design pattern with a corresponding sample application that is featured in this repository. We hope you enjoy and find this series useful.<\/p>\n<p>Here is 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<li><a href=\"https:\/\/devblogs.microsoft.com\/cosmosdb\/azure-cosmos-db-design-patterns-part-4-global-distributed-lock\/\" target=\"_blank\" rel=\"noopener\">Part 4: Global distributed lock<\/a><\/li>\n<\/ul>\n<h2>Azure Cosmos DB design pattern: Document versioning<\/h2>\n<p><img decoding=\"async\" width=\"1024\" height=\"1024\" class=\"wp-image-7453\" src=\"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/word-image-7451-2.jpeg\" srcset=\"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/word-image-7451-2.jpeg 1024w, https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/word-image-7451-2-300x300.jpeg 300w, https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/word-image-7451-2-150x150.jpeg 150w, https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/word-image-7451-2-768x768.jpeg 768w, https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/word-image-7451-2-24x24.jpeg 24w, https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/word-image-7451-2-48x48.jpeg 48w, https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/word-image-7451-2-96x96.jpeg 96w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/p>\n<p>This post will focus on the <a href=\"https:\/\/github.com\/Azure-Samples\/cosmos-db-design-patterns\/tree\/main\/document-versioning\" target=\"_blank\" rel=\"noopener\">document versioning design pattern<\/a>. Document versioning in NoSQL databases is a design pattern that enables the tracking and management of changes to documents over time. This method is particularly useful in environments where data evolves frequently and where maintaining a historical record of these changes is essential. In a typical setup, each document is assigned a version number, which is updated as changes are made. The most recent version of the document is kept in a primary collection, while previous versions are stored in a separate historical collection. This approach ensures easy access to the latest data while preserving a complete history of document revisions.<\/p>\n<p>The key advantage of document versioning is its ability to provide a comprehensive audit trail for data changes, which is critical in scenarios <a id=\"post-7451-_Int_F4YaaxBm\"><\/a>where understanding the evolution of data over time is important. However, this pattern also introduces additional complexity in data management. It increases the volume of write operations since each change results in <a id=\"post-7451-_Int_rFwqYXaA\"><\/a>a new version of the document. Furthermore, accessing historical data may require querying a separate collection, adding an extra layer of complexity to database interactions. Despite these challenges, document versioning remains a valuable tool in managing evolving data within NoSQL environments.<\/p>\n<h2>The Scenario:<\/h2>\n<p>In a common scenario across various industries, adherence to regulatory guidelines necessitates the retention and tracking of historical document versions. This is particularly relevant in sectors where data retention for auditing and document control is critical. To accommodate this, a two-pronged storage strategy is often implemented. The most current versions of documents are stored in a dedicated collection, named to reflect its purpose of holding present-day records. Conversely, a separate collection is earmarked for archiving historical documents. This division enhances the efficiency of data queries, as it allows for prompt access to current documents without the interference of historical records. It is noteworthy that the responsibility for managing document versioning typically falls on the application layer and is not a direct function of the database system, such as Azure Cosmos DB.<\/p>\n<p>This approach is a hallmark of how NoSQL databases, like Azure Cosmos DB, can be tailored to meet specific regulatory compliance and data management needs in various industries. The separation of current and historical data not only aligns with legal requirements but also optimizes data retrieval, ensuring ease of access to both current and historical information as needed.<\/p>\n<h3>Sample Implementation:<\/h3>\n<p>In the sample implementation for document versioning in an eCommerce environment using Azure Cosmos DB for NoSQL, we manage order documents that undergo changes in their lifecycle. Here is how it is structured:<\/p>\n<h3>Original Order Document<\/h3>\n<p>At the beginning, an order is placed, and the document looks like this:<\/p>\n<pre class=\"prettyprint language-json\"><code class=\"language-json\">{\r\n    \"customerId\": 10,\r\n    \"orderId\": 1101,\r\n<strong>    \"status\": \"Submitted\",\r\n<\/strong>    \"orderDetails\": [\r\n        {\r\n            \"productName\": \"Product 1\",\r\n            \"quantity\": 1\r\n        },\r\n        {\r\n            \"productName\": \"Product 2\",\r\n            \"quantity\": 3\r\n        }\r\n    ]\r\n}<\/code><\/pre>\n<p>This document is stored in the <strong><span style=\"font-family: 'courier new', courier, monospace;\">CurrentOrderStatus<\/span> <\/strong>container, representing the latest status of the order.<\/p>\n<h3>Updated Order Document (After Cancellation)<\/h3>\n<p>Suppose the customer decides to cancel the order. The document is updated to reflect this change:<\/p>\n<pre class=\"prettyprint language-json\"><code class=\"language-json\">{\r\n    \"customerId\": 10,\r\n    \"orderId\": 1101,\r\n<strong>    \"status\": \"Cancelled\",\r\n<\/strong>    \"orderDetails\": [\r\n        {\r\n            \"productName\": \"Product 1\",\r\n            \"quantity\": 1\r\n        },\r\n        {\r\n            \"productName\": \"Product 2\",\r\n            \"quantity\": 3\r\n        }\r\n    ]\r\n}\r\n<\/code><\/pre>\n<p>The updated document, showing the order&#8217;s cancellation, is then saved back to the <strong>CurrentOrderStatus <\/strong>container.<\/p>\n<h2>Implementing Document Versioning<\/h2>\n<p>In this implementation, the document versioning is handled at the application layer. Each time an order document is modified, a new version is created, and the following happens:<\/p>\n<ul>\n<li>The updated document (with the latest status) is saved in the <strong><span style=\"font-family: 'courier new', courier, monospace;\">CurrentOrderStatus<\/span> <\/strong>container.<\/li>\n<li>A Function App monitors changes using Azure Cosmos DB&#8217;s change feed feature.<\/li>\n<li>The Function App then copies this versioned document into the <strong><span style=\"font-family: 'courier new', courier, monospace;\">HistoricalOrderStatus<\/span> <\/strong>container, preserving a record of each state of the order for historical tracking.<\/li>\n<\/ul>\n<p><img decoding=\"async\" width=\"866\" height=\"671\" class=\"wp-image-7454\" src=\"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/word-image-7451-3.png\" srcset=\"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/word-image-7451-3.png 866w, https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/word-image-7451-3-300x232.png 300w, https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-content\/uploads\/sites\/52\/2024\/01\/word-image-7451-3-768x595.png 768w\" sizes=\"(max-width: 866px) 100vw, 866px\" \/><\/p>\n<p>This process not only maintains the current state of each order but also builds a comprehensive history of changes, ensuring compliance with data retention policies and providing valuable insights for auditing and data analysis.<\/p>\n<h2>Why it Matters:<\/h2>\n<p>Using document versioning in database systems, particularly in NoSQL environments, is crucial for several reasons:<\/p>\n<ul>\n<li><strong>Regulatory Compliance and Auditing:<\/strong> Many industries are governed by strict regulations that require the retention and tracking of historical data for compliance purposes. Document versioning enables organizations to maintain an audit trail of changes, thereby complying with legal requirements and facilitating audits.<\/li>\n<li><strong>Data Integrity and Recovery:<\/strong> With document versioning, it is easier to track changes and revert to previous versions in case of errors or data corruption. This capability is vital for maintaining data integrity and ensuring reliable data recovery mechanisms.<\/li>\n<li><strong>Change Management and Collaboration:<\/strong> In scenarios where multiple users or systems might update documents concurrently, versioning helps in managing these changes effectively. It avoids conflicts by keeping a record of who made what changes and when, thus enhancing collaboration.<\/li>\n<li><strong>Historical Analysis and Reporting:<\/strong> Keeping historical versions of documents allows for detailed analysis and reporting. Organizations can track the evolution of data over time, gaining insights into trends, patterns, and operational efficiency.<\/li>\n<li><strong>System Performance Optimization:<\/strong> By segregating current and historical data into different collections or containers, document versioning can improve query performance. Systems can access current data more swiftly without sifting through a vast history of changes.<\/li>\n<li><strong>Bespoke Business Logic Implementation:<\/strong> Document versioning allows businesses to implement custom logic based on historical data changes. This might include triggering specific actions when data reaches certain states or maintaining custom logs for business analysis.<\/li>\n<li><strong>Enhanced User Experience:<\/strong> For applications that rely on historical data (like version control systems or content management systems), document versioning is essential for providing a rich user experience, allowing users to view, compare, and revert changes as needed.<\/li>\n<li><strong>Scalability and Futureproofing:<\/strong> As businesses grow and evolve, their data management needs become more complex. Document versioning offers a scalable way to manage data changes over time, ensuring that the system remains robust and adaptable for future requirements.<\/li>\n<\/ul>\n<p>In summary, document versioning is a pivotal feature in modern database management, offering significant benefits in terms of compliance, data integrity, collaboration, and operational efficiency. Its implementation can be a key factor in an organization&#8217;s ability to manage data effectively in a dynamic and evolving business environment.<\/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\/document-versioning\" target=\"_blank\" rel=\"noopener\">Document versioning 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 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 are 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<div class=\"row justify-content-center\"><\/div>\n<h2>About Azure Cosmos DB<\/h2>\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<h2>Try Azure Cosmos DB free with Azure AI Advantage<\/h2>\n<p>Sign up for the\u00a0<a href=\"https:\/\/aka.ms\/AzureAIAdvantageSignupForm\" target=\"_blank\" rel=\"noopener\">Azure AI Advantage!\u00a0<\/a>The Azure AI Advantage offer is for existing Azure AI and GitHub Copilot customers who want to use Azure Cosmos DB as part of their solution stack. With this offer, you get\u00a0<span class=\"ui-provider a b c d e f g h i j k l m n o p q r s t u v w x y z ab ac ae af ag ah ai aj ak\" dir=\"ltr\">40,000 free RUs, equivalent of up to $6,000 in savings.<\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Welcome to part five of our series of blog posts focused on sharing common design patterns you can use to build applications with Azure Cosmos DB for NoSQL. 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 [&hellip;]<\/p>\n","protected":false},"author":39313,"featured_media":7452,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[14],"tags":[1882],"class_list":["post-7451","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-core-sql-api","tag-design-patterns"],"acf":[],"blog_post_summary":"<p>Welcome to part five of our series of blog posts focused on sharing common design patterns you can use to build applications with Azure Cosmos DB for NoSQL. 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 [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/posts\/7451","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=7451"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/posts\/7451\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/media\/7452"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/media?parent=7451"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/categories?post=7451"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/tags?post=7451"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}