<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Deepak Singh on Medium]]></title>
        <description><![CDATA[Stories by Deepak Singh on Medium]]></description>
        <link>https://medium.com/@deepak.singh_27102?source=rss-c63a92e7babd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kgjhxAC4FDYr1rDpVRXEJg.jpeg</url>
            <title>Stories by Deepak Singh on Medium</title>
            <link>https://medium.com/@deepak.singh_27102?source=rss-c63a92e7babd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 15:48:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@deepak.singh_27102/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Design patterns for cloud based MicroServices]]></title>
            <link>https://medium.com/clairvoyantblog/design-patterns-for-cloud-based-microservices-91aae19e2f4d?source=rss-c63a92e7babd------2</link>
            <guid isPermaLink="false">https://medium.com/p/91aae19e2f4d</guid>
            <category><![CDATA[containerization]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Deepak Singh]]></dc:creator>
            <pubDate>Tue, 17 Nov 2020 14:03:08 GMT</pubDate>
            <atom:updated>2021-09-22T06:18:54.219Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Design Patterns for Cloud-based MicroServices</strong></h3><h4>Design Patterns for containerized MicroServices</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*tzuxposyL7-LaHFeQSpxuQ.png" /><figcaption><a href="https://www.homestratosphere.com/wp-content/uploads/2018/04/example-of-cool-container-home-hs-apr17-2018.jpg">Containerized microservices</a></figcaption></figure><h4><strong>Introduction</strong></h4><p>Design patterns help us build software faster without requiring the experience that led to the creation of those patterns. They help developers understand each other quickly, facilitating knowledge sharing and learning.</p><p><a href="https://www.clairvoyant.ai/">Clairvoyant’s</a> software development methodology helps build easier, transparent, and faster solutions. We have also recently introduced accelerators which are code snippets with high reusability and the ability to easily customize to match the requirements of clients across domains. But taking the concept further, our software development philosophy is such that we divide our codes into containers, and design each of these containers to manage a certain functionality. Each container becomes a self-explanatory solution for certain problems.</p><p>For example, now that the idea of the “sidecar” container has spread in the developer community, we don’t need to explain the concept to those who have already worked on it before. We can instead, focus on how it can be used to solve a certain problem.</p><p>Another benefit of design patterns is that it helps us identify common components that can be implemented just once and then reused.</p><p><strong>Distributed Design Patterns</strong></p><p>To understand the motivation behind the design patterns, it’s helpful to know the benefits of using containers. Containers help us establish boundaries for applications, e.g if App A needs 8GB of memory, we can enforce that using a Docker. They also help us separate concerns with each container image having a well-defined function.</p><p>When our applications are packaged in containers and deployed to cloud environments, there are certain best practices we can follow to simplify the development process. Distributed design patterns help us implement these best practices when deploying our container-based application to a cloud environment. We can classify these design patterns into two types: single-node container patterns and multi-node container patterns.</p><p><strong>Single Node Container Patterns</strong></p><p>The basic element of design, when it comes to distributed systems, is the container. It is the basic building block for distributed system design patterns. The benefit of container use, as already mentioned, is that it provides an incentive for us to split an application into a group of containers, rather than having to run them all on a single container.</p><p>For example, let’s say we have an application that needs to monitor its configuration property files, to check whether they have been modified, and load those properties to memory if so. This provides an opportunity for separation of concerns. We could separate the application and the configuration loader module into two different containers that are co-scheduled. The application container would focus on the business logic, and the configuration container would be responsible for managing the configuration properties. With this approach, we can assign a higher priority to the application container, since it is responsible for handling end-user requests. In the case of high memory utilization, the configuration container could be terminated to keep the application container running.</p><p>In this way, we can achieve resource isolation by splitting our application into multiple containers that run on a single node. In addition, it increases the reusability of code. When another team builds a new application, they can simply reuse the configuration container instead of writing it all over again. Since the application is in a container that has an http interface, the other applications written in different programming languages can also use it. It also means that different modules independent of each other can be deployed resulting in more reliable deployments.</p><p><strong>Sidecar Pattern</strong></p><p>The sidecar pattern relies on the concept of an “atomic container group”. The atomic container group is a set of containers co-scheduled to the same machine, in addition to sharing some resources such as the network and some parts of the filesystem. In Kubernetes, this concept is represented by a Pod object.</p><p>In the sidecar pattern, we have two containers. The first container has the main application, for example, a web service. In addition to this container, there is another container referred to as the sidecar. This container is used to add functionality to the main service, without the main service knowing about it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jGmFnstcjp3k-biPKffoAw.png" /></figure><p>One use case for this pattern is configuration synchronization. A web service may store application properties using a configuration file located on the filesystem. In this case, updating a property would require a restart of the application. In a cloud environment, applications may need to be highly available and it would be preferable to update configuration settings without requiring a restart.</p><p>To solve this using the sidecar pattern, we would have two containers — the main container would be the server application and the sidecar container would be a configuration manager application. The two containers would be grouped together as part of a pod so that they would be co-scheduled. When the main application starts, it reads the configuration from the filesystem. The configuration manager application could read the latest value of the configuration, for example, from a properties file located on Git. If it identifies a difference between the local properties and the remote files, it would download the remote file and call an API on the main application to notify that it should reload the properties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nWlo96zT4tQQgRYARkIigA.png" /></figure><p><strong>Ambassador pattern</strong></p><p>Similar to the sidecar pattern, the ambassador pattern relies on two containers that are co-scheduled. In the ambassador pattern, the interactions between the application container and external services are managed by an ambassador container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*0UwMKaksZq2NIaVHjUU0yg.png" /></figure><p>One of the benefits of this pattern is that, as with the sidecar pattern, reusability is increased. We can create an ambassador container and use it with different application containers.</p><p>An example use case for ambassador pattern is sharding a service.</p><p>In a sharded service, we create multiple replicas of the service. Each of these replicas is capable of serving a subset of the received requests. This is different from a replicated service (multiple instances behind a load balancer), where each replica is capable of handling any request. In a sharded service, we have a load-balancing node that receives requests and determines which replica, or shard, should process that request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*CJdAuHJdmg-yYzOiIs7NuA.png" /></figure><p>A sharded service is useful when you want to build a service that maintains state, such as a database. If you have a database where one instance is not able to store all the data, by sharding the database service and adding multiple instances with each storing a subset of the data, you are able to scale the service on the basis of the size of the data that needs to be stored. An ambassador container, with the logic required to route each request to the shard, can be introduced to process that request. The client application only connects to this application and is unaware of the shards.</p><p><strong>Multi-Node application patterns</strong></p><p>Until now you have learned the patterns you can apply to run them as reusable containers, and how these can be used by different deployed application containers.</p><p>Multi-Node deployment architecture helps in building scalable, resilient, highly available, and manageable systems.</p><p><strong>Leader Election Pattern</strong></p><p>Replication is a common way of sharing the load among multiple identical instances of a component. One of the complex uses of replications is an application that needs to distinguish one replica as a “leader” from the set.</p><p>In a Distributed System, the most common problem is Leader election and there are a number of libraries/Algorithm (Raft, Paxos, Leases, software like Zookeeper, etc.) for performing the same. Implementation of these libraries is complex, difficult to understand, challenging, and redundant.</p><p>A system can run multiple leader selections in parallel, for example, to determine a leader in multiple shards (For example- a sharded cluster design in MongoDB, where each shard contains 3 member replica sets, in which one should be selected as a Primary and the others will work as secondaries).</p><p>We can apply a similar concept of reusability and link the Leader election library to the application to use the leader election container. Now multiple services can utilize the same container and application services are spared to focus on their business problems.</p><p>This pattern represents the principles of reusability, abstractions, and encapsulation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w0fGYtk_kMQJmYKyFDwt8Q.png" /></figure><p><strong>Work Queue Pattern</strong></p><p>Work Queue System helps to perform a batch of work. In batch processing, each piece of work is completely independent of the other and can be processed independently too.</p><p>So, identify the functionality that can be provided by a shared set of libraries and any independent work from the actual work being done by your application and containerize them.</p><p>Work queue is another example of a distributed system. The goals of Work Queue system are to make sure that each piece of work is processed within a certain amount of time. To handle each task efficiently, workers can be scaled up and down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nnAGXjisDHfyHOc4NsERdw.png" /><figcaption>Image Source: Designing Distributed Systems by Brendan Burns</figcaption></figure><p><strong>Scatter/gather (a.k.a. Fan Out/Fan In) pattern</strong></p><p>The last distribution pattern that we want to highlight is the Scatter/gather (a.k.a. Fan-out/Fan-In) pattern. This pattern helps you achieve parallelism in servicing requests, enabling you to service the client significantly faster than you would if you had to serve them sequentially.</p><p>In this system, the external client sends an initial request to the “root” or “parent” node. This root fans-out the request to multiple servers to perform parallel computations. Each shard returns partial data, and the root gathers the response from other shards and returns a single response.</p><p>This kind of pattern is commonly used in search engines. If you notice, building such systems requires a lot of boilerplate code: fanning out the requests, gathering the response, handling client requests, etc. These codes are quite generic and can be containerized and reused by the application containers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*u3Y-ggRP3gcz7IksyRfwWQ.png" /></figure><p><strong>Conclusion</strong></p><p>Similar to the Object-Oriented programming that leads to “Design patterns” to solve commonly occurring problems, we can see that container based architectures also lead to design patterns for container-based distributed systems.</p><p>In this post, we have covered the single-container pattern for system management, single-node patterns for closely co-operating containers, and multi-node patterns for distributed algorithms. In all the cases, containers provide many of the same benefits as Object-Oriented systems do, such as reusability, abstraction, encapsulation, upgrading components independently, and the ability to be written in a mixture of languages.</p><p>The set of container patterns will grow as we evolve and revolutionize distributed systems programming as was the case with object-oriented programming in the earlier decades.</p><p><strong>References</strong></p><ul><li>Design patterns for container-based distributed systems white paper by <strong><em>Brendan Burns </em></strong><em>and</em> <strong>David Oppenheimer.</strong></li><li><a href="https://www.amazon.com/Designing-Distributed-Systems-Patterns-Paradigms/dp/1491983647#:~:text=Author%20Brendan%20Burns%E2%80%94Director%20of,and%20building%20reliable%20distributed%20applications.">Designing Distributed Systems </a>by Brendan Burns</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91aae19e2f4d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/clairvoyantblog/design-patterns-for-cloud-based-microservices-91aae19e2f4d">Design patterns for cloud based MicroServices</a> was originally published in <a href="https://medium.com/clairvoyantblog">Clairvoyant Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MongoDB Transaction Management]]></title>
            <link>https://medium.com/clairvoyantblog/mongodb-transaction-management-884f82f62767?source=rss-c63a92e7babd------2</link>
            <guid isPermaLink="false">https://medium.com/p/884f82f62767</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-mongo-db]]></category>
            <category><![CDATA[transactions]]></category>
            <category><![CDATA[mongo]]></category>
            <dc:creator><![CDATA[Deepak Singh]]></dc:creator>
            <pubDate>Wed, 14 Oct 2020 13:08:20 GMT</pubDate>
            <atom:updated>2020-10-14T13:08:20.053Z</atom:updated>
            <content:encoded><![CDATA[<h4>Here’s how to use Retryable and MongoTemplate for the MongoDB Transaction</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nOJnrus-j51IJA0FsRBdhA.png" /><figcaption><a href="https://www.pngwave.com/png-clip-art-bwpkb">MongoDB</a></figcaption></figure><p>Transaction management is a critical aspect of building applications. Let’s discuss how Mongo DB and its latest releases can help us accomplish that.</p><p>MongoDB, with its 4.0 release, added support for Multi-Document Transaction which works across replica sets. This support has also been extended to Sharded Cluster with the 4.2 release.</p><p>This blog can help you-</p><ol><li>add Transaction support in your application using Java Spring Data and Java Mongo Drivers, and</li><li>with the best practices that are to be followed</li></ol><h3>Prerequisites</h3><p>You need to have an understanding of the Core-Java, Spring and Spring-Data frameworks, and a basic understanding of Mongo Queries and concepts.</p><h3>MongoDB NoSQL Database</h3><p>MongoDB is a NoSQL database and is fundamentally different from SQL data modeling in that it always encourages having related data in a single document (remember MongoDB will perform better if you use it correctly; avoid using it as a Relational database). Since MongoDB supports ACID transactions in a single document, the application developers don’t have to worry about ACID guarantees across multiple documents.</p><p>But sometimes based on your application’s needs and design, you can not have everything in one document. You might want the documents spread across multiple collections, and such scenarios call for ACID guarantees.</p><p>So let’s discuss a few concepts around MongoDB Transaction support. Later in the blog, I will also share the code snippet which will help you add transactional support in your application.</p><h3>Write operation outside of the Transactions</h3><p>Multiple write operations performed simultaneously on the same document outside of the transactional scope also cause WriteConflict. But as a developer, you don’t have to worry about the issue since WiredTiger internally handles WriteConfilct errors and continues to retry updates until it can complete without encountering any conflicts or within a defined <a href="https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS/">MaxTime</a>.</p><h3>Why do WriteConflicts happen?</h3><p>MongoDB uses optimistic updates for document-level concurrency and WriteConflict indicates when multiple users are simultaneously trying to update the same document.</p><p>MongoDB uses WiredTiger Storage Engine to handle such issues. Any non-zero WriteConflict notifies the engine that update requests to the document can cause data concurrency violation. Whenever the WiredTiger API detects a WriteConflict due to concurrency violation, it increments the WriteConflict metrics and MongoDB internally retries updates until it completes without encountering any conflicts.</p><p>Large numbers of WriteConflict can cause a delay in the application response and you will be left trying to find the cause.</p><h3>Write operation in Transaction Scope</h3><p>As already mentioned, any update causing write conflicts outside of the transaction gets retried automatically by the WiredTiger storage engine.</p><p>Writing inside the transaction scope works a bit differently. In WiredTiger, an update to a document is optimistic and aborts the transaction in case a conflict gets detected.</p><p>Let’s consider the following example depicted in the diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*1cbyh63zZ8AiNrdGY0jUBQ.png" /></figure><p>If a different/same application tries to modify the same document before a transaction ends, it will throw a WriteConflict error.</p><p>From the above diagram, you can see that a Transaction (t1) is subjected to WriteConflict as the same document (D1) gets simultaneously modified by another application before the transaction ends. It doesn’t matter if the other write operation is in the transaction scope or not.</p><p>Example of a WriteConflict error:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad0ee904f4f22a3cc6d8bcc1f60e7ef8/href">https://medium.com/media/ad0ee904f4f22a3cc6d8bcc1f60e7ef8/href</a></iframe><h3>Write Operation in Transaction Scope in a Multi-Sharded Cluster</h3><p>A Write operation behavior in a Sharded cluster is similar to what has been explained above. In a Sharded environment, you might see an error like “StaleConflict” which occurs during a <a href="https://docs.mongodb.com/manual/core/transactions-sharded-clusters/#chunk-migrations">chunk migration</a>. (Note: Chunk Migration will be covered in another post) But, in brief, MongoDB uses this mechanism to split the data and distribute it evenly based on the Shard key.</p><p>The application developers should have a logic to abort the current transaction and retry for any exceptions, such as MVCC (Multiversion Concurrency Control) which includes a write conflict, transient network failure, or a primary replica election.</p><p>If you are using a core Mongo-Java Driver, the new <a href="https://docs.mongodb.com/manual/core/transactions/">callback API</a> incorporates retry logic for TransientTransactionError or UnknownTransactionCommitResult commit errors.</p><p>Following are the Code Snippets to introduce transaction management-</p><h3>Configure Mongo Transaction Manager</h3><p>To use Spring-Data Transaction Management, you must configure MongoTransactionManager Bean.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d23a86ec898f1292aa44a7b609c4a971/href">https://medium.com/media/d23a86ec898f1292aa44a7b609c4a971/href</a></iframe><h3>Transactional Support with Spring-data</h3><p>With Transactional and Retryable annotations, you don’t have to write retry the logic on your own to handle the transaction manually.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/792e0d96e81760ead0161baac458c5f8/href">https://medium.com/media/792e0d96e81760ead0161baac458c5f8/href</a></iframe><h3>MongoClientOption</h3><p>You can set the Read and Write Concern through the MongoClientOption.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/170df8b0fba9ba16dafb1e2a964a9408/href">https://medium.com/media/170df8b0fba9ba16dafb1e2a964a9408/href</a></iframe><h3>Best Practices-</h3><h3>Avoid creating long-running Transactions</h3><p>Creating long-running transactions and performing excessive operations can cause high pressure on the WiredTiger Storage Engine cache.</p><h3>Transaction Run-time limit</h3><p>MongoDB’s default transaction limit is 60 sec and any transaction running outside of the limit will be aborted. You have the flexibility to change this number and run the transaction for a longer time.</p><p>To avoid the timeout issue, transactions should be broken into smaller parts while performing nothing other than the DB operations (avoid performing any application/business logic within the transaction).</p><h3>Transaction in a Distributed multi-sharded cluster</h3><p>Transactions that affect multiple shards cause greater performance cost as the query gets broadcasted across multiple participating nodes over the network.<br>Identify queries and give proper indexing. If you want consistent reading in Distributed multi-shard, use the readConcern “snapshot”. This provides a consistent snapshot of your data across multiple shards. Use the readConcern level ‘local’ if latency is a concern for the application.</p><h3>Choosing Write Concern in a distributed multi-sharded cluster</h3><p>MongoDB allows you to specify the <a href="https://docs.mongodb.com/manual/reference/write-concern/">WriteConcern</a> to define the level of durability guarantee when writing to the database.</p><p>Note that write concerns are applicable to any operation that is executed against the database, irrespective of whether you are running a regular operation against a single document or a multi-document transaction.</p><p>The following are the WriteConcern options you can configure on a per-connection, per-database, per-collection, or even per-operation basis.</p><p>The options are as follows-</p><p><strong>Write Acknowledged-</strong> This will use the default Write concern configured on the server and wait for the server’s acknowledgment.</p><p>You can pass the <strong>w</strong> value to define the Write Acknowledgement behavior.</p><p><strong>W0: </strong>With this concern, the write operation will not wait for an acknowledgment from the server. In this case, the data can be rolled back if the primary step-down before the write operation is replicated to secondary.</p><p><strong>W1: </strong>With this concern, the write operation will wait for an acknowledgment from Primary in case of a replica set. In this case, data can be rolled back if the primary step-down gets replicated to the secondary before the write operation.</p><p><strong>W2: </strong>With this concern, the write operation will wait for an acknowledgment from the Primary and one of the Secondaries.</p><p><strong>W3: </strong>With this concern, the write operation will wait for an acknowledgment from the Primary and both the Secondaries.</p><p><strong>Journal Acknowledged:</strong> With this concern, the Write operation will be confirmed by the server after it gets flushed to the journal on the primary. Write operation with this concern ensures durable data on the disk, even if the MongoDB server crashes.</p><p><strong>Replica Acknowledged:</strong> This is a deprecated option and the preferred option is to use the WriteConcern W2, which behaves the same as the Replica-set acknowledgment concern.</p><p><strong>Majority:</strong> With this concern, the write operation waits for a majority of the replica set data-bearing and electable members, and it cannot be rolled-back even in the event of a primary election. This concern also ensures that the write operation gets recorded in the journal on a majority of replicas, including primary.</p><h3>What next?</h3><p>If you are a new/an intermediately experienced developer using MongoDB in your application, learn the MongoDB concepts from the <a href="https://university.mongodb.com/courses/catalog">mongodb-university</a> website. All the courses are free!</p><p>I hope the article was helpful for the people looking to add Transaction support in MongoDB with Spring-data framework.</p><p>Thanks for reading!</p><h3>Reference:</h3><p><a href="https://docs.mongodb.com/manual/reference/write-concern/">https://docs.mongodb.com/manual/reference/write-concern/</a><br><a href="https://docs.mongodb.com/manual/core/transactions/">https://docs.mongodb.com/manual/core/transactions/</a><br>https://www.youtube.com/watch?v=3x_Pf9rQGCo</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=884f82f62767" width="1" height="1" alt=""><hr><p><a href="https://medium.com/clairvoyantblog/mongodb-transaction-management-884f82f62767">MongoDB Transaction Management</a> was originally published in <a href="https://medium.com/clairvoyantblog">Clairvoyant Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>